blob: f8d9918c8b2ae33415442789b602bf59744bb67a [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker919cb2a2015-02-05 21:58:25 -080046#include <keymaster/soft_keymaster_device.h>
Shawn Willden9e5016a2015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Shawn Willden9e5016a2015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willdenef572b62015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Chad Brubaker94436162015-05-12 15:18:26 -0700155 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100156 P_GET = 1 << 1,
157 P_INSERT = 1 << 2,
158 P_DELETE = 1 << 3,
159 P_EXIST = 1 << 4,
Chad Brubaker94436162015-05-12 15:18:26 -0700160 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100161 P_RESET = 1 << 6,
162 P_PASSWORD = 1 << 7,
163 P_LOCK = 1 << 8,
164 P_UNLOCK = 1 << 9,
Chad Brubaker94436162015-05-12 15:18:26 -0700165 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100166 P_SIGN = 1 << 11,
167 P_VERIFY = 1 << 12,
168 P_GRANT = 1 << 13,
169 P_DUPLICATE = 1 << 14,
170 P_CLEAR_UID = 1 << 15,
Chad Brubaker94436162015-05-12 15:18:26 -0700171 P_ADD_AUTH = 1 << 16,
172 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700173} perm_t;
174
175static struct user_euid {
176 uid_t uid;
177 uid_t euid;
178} user_euids[] = {
179 {AID_VPN, AID_SYSTEM},
180 {AID_WIFI, AID_SYSTEM},
181 {AID_ROOT, AID_SYSTEM},
182};
183
Riley Spahneaabae92014-06-30 12:39:52 -0700184/* perm_labels associcated with keystore_key SELinux class verbs. */
185const char *perm_labels[] = {
Chad Brubaker94436162015-05-12 15:18:26 -0700186 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700187 "get",
188 "insert",
189 "delete",
190 "exist",
Chad Brubaker94436162015-05-12 15:18:26 -0700191 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700192 "reset",
193 "password",
194 "lock",
195 "unlock",
Chad Brubaker94436162015-05-12 15:18:26 -0700196 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700197 "sign",
198 "verify",
199 "grant",
200 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100201 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700202 "add_auth",
Chad Brubakerfd777e72015-05-12 10:43:10 -0700203 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700204};
205
Kenny Root07438c82012-11-02 15:41:02 -0700206static struct user_perm {
207 uid_t uid;
208 perm_t perms;
209} user_perms[] = {
210 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
211 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
212 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
213 {AID_ROOT, static_cast<perm_t>(P_GET) },
214};
215
Chad Brubaker94436162015-05-12 15:18:26 -0700216static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
217 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700218
William Robertse46b8552015-10-02 08:19:52 -0700219struct audit_data {
220 pid_t pid;
221 uid_t uid;
222};
223
Riley Spahneaabae92014-06-30 12:39:52 -0700224static char *tctx;
225static int ks_is_selinux_enabled;
226
227static const char *get_perm_label(perm_t perm) {
228 unsigned int index = ffs(perm);
229 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
230 return perm_labels[index - 1];
231 } else {
232 ALOGE("Keystore: Failed to retrieve permission label.\n");
233 abort();
234 }
235}
236
Kenny Root655b9582013-04-04 08:37:42 -0700237/**
238 * Returns the app ID (in the Android multi-user sense) for the current
239 * UNIX UID.
240 */
241static uid_t get_app_id(uid_t uid) {
242 return uid % AID_USER;
243}
244
245/**
246 * Returns the user ID (in the Android multi-user sense) for the current
247 * UNIX UID.
248 */
249static uid_t get_user_id(uid_t uid) {
250 return uid / AID_USER;
251}
252
William Robertse46b8552015-10-02 08:19:52 -0700253static int audit_callback(void *data, security_class_t /* cls */, char *buf, size_t len)
254{
255 struct audit_data *ad = reinterpret_cast<struct audit_data *>(data);
256 if (!ad) {
257 ALOGE("No keystore audit data");
258 return 0;
259 }
260
261 snprintf(buf, len, "pid=%d uid=%d", ad->pid, ad->uid);
262 return 0;
263}
264
265static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700266 if (!ks_is_selinux_enabled) {
267 return true;
268 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000269
William Robertse46b8552015-10-02 08:19:52 -0700270 audit_data ad;
Riley Spahneaabae92014-06-30 12:39:52 -0700271 char *sctx = NULL;
272 const char *selinux_class = "keystore_key";
273 const char *str_perm = get_perm_label(perm);
274
275 if (!str_perm) {
276 return false;
277 }
278
279 if (getpidcon(spid, &sctx) != 0) {
280 ALOGE("SELinux: Failed to get source pid context.\n");
281 return false;
282 }
283
William Robertse46b8552015-10-02 08:19:52 -0700284 ad.pid = spid;
285 ad.uid = uid;
286
Riley Spahneaabae92014-06-30 12:39:52 -0700287 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
William Robertse46b8552015-10-02 08:19:52 -0700288 reinterpret_cast<void *>(&ad)) == 0;
Riley Spahneaabae92014-06-30 12:39:52 -0700289 freecon(sctx);
290 return allowed;
291}
292
293static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700294 // All system users are equivalent for multi-user support.
295 if (get_app_id(uid) == AID_SYSTEM) {
296 uid = AID_SYSTEM;
297 }
298
Kenny Root07438c82012-11-02 15:41:02 -0700299 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
300 struct user_perm user = user_perms[i];
301 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700302 return (user.perms & perm) &&
303 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700304 }
305 }
306
Riley Spahneaabae92014-06-30 12:39:52 -0700307 return (DEFAULT_PERMS & perm) &&
308 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700309}
310
Kenny Root49468902013-03-19 13:41:33 -0700311/**
312 * Returns the UID that the callingUid should act as. This is here for
313 * legacy support of the WiFi and VPN systems and should be removed
314 * when WiFi can operate in its own namespace.
315 */
Kenny Root07438c82012-11-02 15:41:02 -0700316static uid_t get_keystore_euid(uid_t uid) {
317 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
318 struct user_euid user = user_euids[i];
319 if (user.uid == uid) {
320 return user.euid;
321 }
322 }
323
324 return uid;
325}
326
Kenny Root49468902013-03-19 13:41:33 -0700327/**
328 * Returns true if the callingUid is allowed to interact in the targetUid's
329 * namespace.
330 */
331static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700332 if (callingUid == targetUid) {
333 return true;
334 }
Kenny Root49468902013-03-19 13:41:33 -0700335 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
336 struct user_euid user = user_euids[i];
337 if (user.euid == callingUid && user.uid == targetUid) {
338 return true;
339 }
340 }
341
342 return false;
343}
344
Kenny Roota91203b2012-02-15 15:00:46 -0800345/* Here is the encoding of keys. This is necessary in order to allow arbitrary
346 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
347 * into two bytes. The first byte is one of [+-.] which represents the first
348 * two bits of the character. The second byte encodes the rest of the bits into
349 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
350 * that Base64 cannot be used here due to the need of prefix match on keys. */
351
Kenny Root655b9582013-04-04 08:37:42 -0700352static size_t encode_key_length(const android::String8& keyName) {
353 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
354 size_t length = keyName.length();
355 for (int i = length; i > 0; --i, ++in) {
356 if (*in < '0' || *in > '~') {
357 ++length;
358 }
359 }
360 return length;
361}
362
Kenny Root07438c82012-11-02 15:41:02 -0700363static int encode_key(char* out, const android::String8& keyName) {
364 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
365 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800366 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700367 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800368 *out = '+' + (*in >> 6);
369 *++out = '0' + (*in & 0x3F);
370 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700371 } else {
372 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800373 }
374 }
375 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800376 return length;
377}
378
Kenny Root07438c82012-11-02 15:41:02 -0700379/*
380 * Converts from the "escaped" format on disk to actual name.
381 * This will be smaller than the input string.
382 *
383 * Characters that should combine with the next at the end will be truncated.
384 */
385static size_t decode_key_length(const char* in, size_t length) {
386 size_t outLength = 0;
387
388 for (const char* end = in + length; in < end; in++) {
389 /* This combines with the next character. */
390 if (*in < '0' || *in > '~') {
391 continue;
392 }
393
394 outLength++;
395 }
396 return outLength;
397}
398
399static void decode_key(char* out, const char* in, size_t length) {
400 for (const char* end = in + length; in < end; in++) {
401 if (*in < '0' || *in > '~') {
402 /* Truncate combining characters at the end. */
403 if (in + 1 >= end) {
404 break;
405 }
406
407 *out = (*in++ - '+') << 6;
408 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800409 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700410 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800411 }
412 }
413 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800414}
415
416static size_t readFully(int fd, uint8_t* data, size_t size) {
417 size_t remaining = size;
418 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800419 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800420 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800421 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800422 }
423 data += n;
424 remaining -= n;
425 }
426 return size;
427}
428
429static size_t writeFully(int fd, uint8_t* data, size_t size) {
430 size_t remaining = size;
431 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800432 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
433 if (n < 0) {
434 ALOGW("write failed: %s", strerror(errno));
435 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800436 }
437 data += n;
438 remaining -= n;
439 }
440 return size;
441}
442
443class Entropy {
444public:
445 Entropy() : mRandom(-1) {}
446 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800447 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800448 close(mRandom);
449 }
450 }
451
452 bool open() {
453 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800454 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
455 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800456 ALOGE("open: %s: %s", randomDevice, strerror(errno));
457 return false;
458 }
459 return true;
460 }
461
Kenny Root51878182012-03-13 12:53:19 -0700462 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800463 return (readFully(mRandom, data, size) == size);
464 }
465
466private:
467 int mRandom;
468};
469
470/* Here is the file format. There are two parts in blob.value, the secret and
471 * the description. The secret is stored in ciphertext, and its original size
472 * can be found in blob.length. The description is stored after the secret in
473 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700474 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700475 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800476 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
477 * and decryptBlob(). Thus they should not be accessed from outside. */
478
Kenny Root822c3a92012-03-23 16:34:39 -0700479/* ** Note to future implementors of encryption: **
480 * Currently this is the construction:
481 * metadata || Enc(MD5(data) || data)
482 *
483 * This should be the construction used for encrypting if re-implementing:
484 *
485 * Derive independent keys for encryption and MAC:
486 * Kenc = AES_encrypt(masterKey, "Encrypt")
487 * Kmac = AES_encrypt(masterKey, "MAC")
488 *
489 * Store this:
490 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
491 * HMAC(Kmac, metadata || Enc(data))
492 */
Kenny Roota91203b2012-02-15 15:00:46 -0800493struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700494 uint8_t version;
495 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700496 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800497 uint8_t info;
498 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700499 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800500 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700501 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800502 int32_t length; // in network byte order when encrypted
503 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
504};
505
Kenny Root822c3a92012-03-23 16:34:39 -0700506typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700507 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700508 TYPE_GENERIC = 1,
509 TYPE_MASTER_KEY = 2,
510 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800511 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700512} BlobType;
513
Kenny Rootf9119d62013-04-03 09:22:15 -0700514static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700515
Kenny Roota91203b2012-02-15 15:00:46 -0800516class Blob {
517public:
Kenny Root07438c82012-11-02 15:41:02 -0700518 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
519 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800520 mBlob.length = valueLength;
521 memcpy(mBlob.value, value, valueLength);
522
523 mBlob.info = infoLength;
524 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700525
Kenny Root07438c82012-11-02 15:41:02 -0700526 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700527 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700528
Kenny Rootee8068b2013-10-07 09:49:15 -0700529 if (type == TYPE_MASTER_KEY) {
530 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
531 } else {
532 mBlob.flags = KEYSTORE_FLAG_NONE;
533 }
Kenny Roota91203b2012-02-15 15:00:46 -0800534 }
535
536 Blob(blob b) {
537 mBlob = b;
538 }
539
540 Blob() {}
541
Kenny Root51878182012-03-13 12:53:19 -0700542 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800543 return mBlob.value;
544 }
545
Kenny Root51878182012-03-13 12:53:19 -0700546 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800547 return mBlob.length;
548 }
549
Kenny Root51878182012-03-13 12:53:19 -0700550 const uint8_t* getInfo() const {
551 return mBlob.value + mBlob.length;
552 }
553
554 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800555 return mBlob.info;
556 }
557
Kenny Root822c3a92012-03-23 16:34:39 -0700558 uint8_t getVersion() const {
559 return mBlob.version;
560 }
561
Kenny Rootf9119d62013-04-03 09:22:15 -0700562 bool isEncrypted() const {
563 if (mBlob.version < 2) {
564 return true;
565 }
566
567 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
568 }
569
570 void setEncrypted(bool encrypted) {
571 if (encrypted) {
572 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
573 } else {
574 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
575 }
576 }
577
Kenny Root17208e02013-09-04 13:56:03 -0700578 bool isFallback() const {
579 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
580 }
581
582 void setFallback(bool fallback) {
583 if (fallback) {
584 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
585 } else {
586 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
587 }
588 }
589
Kenny Root822c3a92012-03-23 16:34:39 -0700590 void setVersion(uint8_t version) {
591 mBlob.version = version;
592 }
593
594 BlobType getType() const {
595 return BlobType(mBlob.type);
596 }
597
598 void setType(BlobType type) {
599 mBlob.type = uint8_t(type);
600 }
601
Kenny Rootf9119d62013-04-03 09:22:15 -0700602 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
603 ALOGV("writing blob %s", filename);
604 if (isEncrypted()) {
605 if (state != STATE_NO_ERROR) {
606 ALOGD("couldn't insert encrypted blob while not unlocked");
607 return LOCKED;
608 }
609
610 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
611 ALOGW("Could not read random data for: %s", filename);
612 return SYSTEM_ERROR;
613 }
Kenny Roota91203b2012-02-15 15:00:46 -0800614 }
615
616 // data includes the value and the value's length
617 size_t dataLength = mBlob.length + sizeof(mBlob.length);
618 // pad data to the AES_BLOCK_SIZE
619 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
620 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
621 // encrypted data includes the digest value
622 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
623 // move info after space for padding
624 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
625 // zero padding area
626 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
627
628 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800629
Kenny Rootf9119d62013-04-03 09:22:15 -0700630 if (isEncrypted()) {
631 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800632
Kenny Rootf9119d62013-04-03 09:22:15 -0700633 uint8_t vector[AES_BLOCK_SIZE];
634 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
635 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
636 aes_key, vector, AES_ENCRYPT);
637 }
638
Kenny Roota91203b2012-02-15 15:00:46 -0800639 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
640 size_t fileLength = encryptedLength + headerLength + mBlob.info;
641
642 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800643 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
644 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
645 if (out < 0) {
646 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800647 return SYSTEM_ERROR;
648 }
649 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
650 if (close(out) != 0) {
651 return SYSTEM_ERROR;
652 }
653 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800654 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800655 unlink(tmpFileName);
656 return SYSTEM_ERROR;
657 }
Kenny Root150ca932012-11-14 14:29:02 -0800658 if (rename(tmpFileName, filename) == -1) {
659 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
660 return SYSTEM_ERROR;
661 }
662 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800663 }
664
Kenny Rootf9119d62013-04-03 09:22:15 -0700665 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
666 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800667 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
668 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800669 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
670 }
671 // fileLength may be less than sizeof(mBlob) since the in
672 // memory version has extra padding to tolerate rounding up to
673 // the AES_BLOCK_SIZE
674 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
675 if (close(in) != 0) {
676 return SYSTEM_ERROR;
677 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700678
679 if (isEncrypted() && (state != STATE_NO_ERROR)) {
680 return LOCKED;
681 }
682
Kenny Roota91203b2012-02-15 15:00:46 -0800683 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
684 if (fileLength < headerLength) {
685 return VALUE_CORRUPTED;
686 }
687
688 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700689 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800690 return VALUE_CORRUPTED;
691 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700692
693 ssize_t digestedLength;
694 if (isEncrypted()) {
695 if (encryptedLength % AES_BLOCK_SIZE != 0) {
696 return VALUE_CORRUPTED;
697 }
698
699 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
700 mBlob.vector, AES_DECRYPT);
701 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
702 uint8_t computedDigest[MD5_DIGEST_LENGTH];
703 MD5(mBlob.digested, digestedLength, computedDigest);
704 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
705 return VALUE_CORRUPTED;
706 }
707 } else {
708 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800709 }
710
711 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
712 mBlob.length = ntohl(mBlob.length);
713 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
714 return VALUE_CORRUPTED;
715 }
716 if (mBlob.info != 0) {
717 // move info from after padding to after data
718 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
719 }
Kenny Root07438c82012-11-02 15:41:02 -0700720 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800721 }
722
723private:
724 struct blob mBlob;
725};
726
Kenny Root655b9582013-04-04 08:37:42 -0700727class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800728public:
Kenny Root655b9582013-04-04 08:37:42 -0700729 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
730 asprintf(&mUserDir, "user_%u", mUserId);
731 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
732 }
733
734 ~UserState() {
735 free(mUserDir);
736 free(mMasterKeyFile);
737 }
738
739 bool initialize() {
740 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
741 ALOGE("Could not create directory '%s'", mUserDir);
742 return false;
743 }
744
745 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800746 setState(STATE_LOCKED);
747 } else {
748 setState(STATE_UNINITIALIZED);
749 }
Kenny Root70e3a862012-02-15 17:20:23 -0800750
Kenny Root655b9582013-04-04 08:37:42 -0700751 return true;
752 }
753
754 uid_t getUserId() const {
755 return mUserId;
756 }
757
758 const char* getUserDirName() const {
759 return mUserDir;
760 }
761
762 const char* getMasterKeyFileName() const {
763 return mMasterKeyFile;
764 }
765
766 void setState(State state) {
767 mState = state;
768 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
769 mRetry = MAX_RETRY;
770 }
Kenny Roota91203b2012-02-15 15:00:46 -0800771 }
772
Kenny Root51878182012-03-13 12:53:19 -0700773 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800774 return mState;
775 }
776
Kenny Root51878182012-03-13 12:53:19 -0700777 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800778 return mRetry;
779 }
780
Kenny Root655b9582013-04-04 08:37:42 -0700781 void zeroizeMasterKeysInMemory() {
782 memset(mMasterKey, 0, sizeof(mMasterKey));
783 memset(mSalt, 0, sizeof(mSalt));
784 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
785 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800786 }
787
Chad Brubakereecdd122015-05-07 10:19:40 -0700788 bool deleteMasterKey() {
789 setState(STATE_UNINITIALIZED);
790 zeroizeMasterKeysInMemory();
791 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
792 }
793
Kenny Root655b9582013-04-04 08:37:42 -0700794 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
795 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800796 return SYSTEM_ERROR;
797 }
Kenny Root655b9582013-04-04 08:37:42 -0700798 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800799 if (response != NO_ERROR) {
800 return response;
801 }
802 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700803 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800804 }
805
Robin Lee4e865752014-08-19 17:37:55 +0100806 ResponseCode copyMasterKey(UserState* src) {
807 if (mState != STATE_UNINITIALIZED) {
808 return ::SYSTEM_ERROR;
809 }
810 if (src->getState() != STATE_NO_ERROR) {
811 return ::SYSTEM_ERROR;
812 }
813 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
814 setupMasterKeys();
815 return ::NO_ERROR;
816 }
817
Kenny Root655b9582013-04-04 08:37:42 -0700818 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800819 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
820 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
821 AES_KEY passwordAesKey;
822 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700823 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700824 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800825 }
826
Kenny Root655b9582013-04-04 08:37:42 -0700827 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
828 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800829 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800830 return SYSTEM_ERROR;
831 }
832
833 // we read the raw blob to just to get the salt to generate
834 // the AES key, then we create the Blob to use with decryptBlob
835 blob rawBlob;
836 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
837 if (close(in) != 0) {
838 return SYSTEM_ERROR;
839 }
840 // find salt at EOF if present, otherwise we have an old file
841 uint8_t* salt;
842 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
843 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
844 } else {
845 salt = NULL;
846 }
847 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
848 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
849 AES_KEY passwordAesKey;
850 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
851 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700852 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
853 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800854 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700855 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800856 }
857 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
858 // if salt was missing, generate one and write a new master key file with the salt.
859 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700860 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800861 return SYSTEM_ERROR;
862 }
Kenny Root655b9582013-04-04 08:37:42 -0700863 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800864 }
865 if (response == NO_ERROR) {
866 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
867 setupMasterKeys();
868 }
869 return response;
870 }
871 if (mRetry <= 0) {
872 reset();
873 return UNINITIALIZED;
874 }
875 --mRetry;
876 switch (mRetry) {
877 case 0: return WRONG_PASSWORD_0;
878 case 1: return WRONG_PASSWORD_1;
879 case 2: return WRONG_PASSWORD_2;
880 case 3: return WRONG_PASSWORD_3;
881 default: return WRONG_PASSWORD_3;
882 }
883 }
884
Kenny Root655b9582013-04-04 08:37:42 -0700885 AES_KEY* getEncryptionKey() {
886 return &mMasterKeyEncryption;
887 }
888
889 AES_KEY* getDecryptionKey() {
890 return &mMasterKeyDecryption;
891 }
892
Kenny Roota91203b2012-02-15 15:00:46 -0800893 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700894 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800895 if (!dir) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700896 // If the directory doesn't exist then nothing to do.
897 if (errno == ENOENT) {
898 return true;
899 }
Kenny Root655b9582013-04-04 08:37:42 -0700900 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800901 return false;
902 }
Kenny Root655b9582013-04-04 08:37:42 -0700903
904 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800905 while ((file = readdir(dir)) != NULL) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700906 // skip . and ..
907 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700908 continue;
909 }
910
911 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800912 }
913 closedir(dir);
914 return true;
915 }
916
Kenny Root655b9582013-04-04 08:37:42 -0700917private:
918 static const int MASTER_KEY_SIZE_BYTES = 16;
919 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
920
921 static const int MAX_RETRY = 4;
922 static const size_t SALT_SIZE = 16;
923
924 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
925 uint8_t* salt) {
926 size_t saltSize;
927 if (salt != NULL) {
928 saltSize = SALT_SIZE;
929 } else {
930 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
931 salt = (uint8_t*) "keystore";
932 // sizeof = 9, not strlen = 8
933 saltSize = sizeof("keystore");
934 }
935
936 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
937 saltSize, 8192, keySize, key);
938 }
939
940 bool generateSalt(Entropy* entropy) {
941 return entropy->generate_random_data(mSalt, sizeof(mSalt));
942 }
943
944 bool generateMasterKey(Entropy* entropy) {
945 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
946 return false;
947 }
948 if (!generateSalt(entropy)) {
949 return false;
950 }
951 return true;
952 }
953
954 void setupMasterKeys() {
955 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
956 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
957 setState(STATE_NO_ERROR);
958 }
959
960 uid_t mUserId;
961
962 char* mUserDir;
963 char* mMasterKeyFile;
964
965 State mState;
966 int8_t mRetry;
967
968 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
969 uint8_t mSalt[SALT_SIZE];
970
971 AES_KEY mMasterKeyEncryption;
972 AES_KEY mMasterKeyDecryption;
973};
974
975typedef struct {
976 uint32_t uid;
977 const uint8_t* filename;
978} grant_t;
979
980class KeyStore {
981public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800982 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700983 : mEntropy(entropy)
984 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800985 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700986 {
987 memset(&mMetaData, '\0', sizeof(mMetaData));
988 }
989
990 ~KeyStore() {
991 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
992 it != mGrants.end(); it++) {
993 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700994 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800995 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700996
997 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
998 it != mMasterKeys.end(); it++) {
999 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001000 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001001 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001002 }
1003
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001004 /**
1005 * Depending on the hardware keymaster version is this may return a
1006 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1007 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1008 * be guarded by a check on the device's version.
1009 */
1010 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001011 return mDevice;
1012 }
1013
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001014 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001015 return mFallbackDevice;
1016 }
1017
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001018 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001019 return blob.isFallback() ? mFallbackDevice: mDevice;
1020 }
1021
Kenny Root655b9582013-04-04 08:37:42 -07001022 ResponseCode initialize() {
1023 readMetaData();
1024 if (upgradeKeystore()) {
1025 writeMetaData();
1026 }
1027
1028 return ::NO_ERROR;
1029 }
1030
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001031 State getState(uid_t userId) {
1032 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001033 }
1034
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001035 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1036 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001037 return userState->initialize(pw, mEntropy);
1038 }
1039
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001040 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1041 UserState *userState = getUserState(dstUser);
1042 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001043 return userState->copyMasterKey(initState);
1044 }
1045
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001046 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1047 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001048 return userState->writeMasterKey(pw, mEntropy);
1049 }
1050
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001051 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1052 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001053 return userState->readMasterKey(pw, mEntropy);
1054 }
1055
1056 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001057 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001058 encode_key(encoded, keyName);
1059 return android::String8(encoded);
1060 }
1061
1062 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001063 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001064 encode_key(encoded, keyName);
1065 return android::String8::format("%u_%s", uid, encoded);
1066 }
1067
1068 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001069 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001070 encode_key(encoded, keyName);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001071 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001072 encoded);
1073 }
1074
Chad Brubakereecdd122015-05-07 10:19:40 -07001075 /*
1076 * Delete entries owned by userId. If keepUnencryptedEntries is true
1077 * then only encrypted entries will be removed, otherwise all entries will
1078 * be removed.
1079 */
1080 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001081 android::String8 prefix("");
1082 android::Vector<android::String16> aliases;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001083 UserState* userState = getUserState(userId);
Chad Brubaker94436162015-05-12 15:18:26 -07001084 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001085 return;
1086 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001087 for (uint32_t i = 0; i < aliases.size(); i++) {
1088 android::String8 filename(aliases[i]);
1089 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubakereecdd122015-05-07 10:19:40 -07001090 getKeyName(filename).string());
1091 bool shouldDelete = true;
1092 if (keepUnenryptedEntries) {
1093 Blob blob;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001094 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001095
Chad Brubakereecdd122015-05-07 10:19:40 -07001096 /* get can fail if the blob is encrypted and the state is
1097 * not unlocked, only skip deleting blobs that were loaded and
1098 * who are not encrypted. If there are blobs we fail to read for
1099 * other reasons err on the safe side and delete them since we
1100 * can't tell if they're encrypted.
1101 */
1102 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1103 }
1104 if (shouldDelete) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001105 del(filename, ::TYPE_ANY, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001106 }
1107 }
1108 if (!userState->deleteMasterKey()) {
1109 ALOGE("Failed to delete user %d's master key", userId);
1110 }
1111 if (!keepUnenryptedEntries) {
1112 if(!userState->reset()) {
1113 ALOGE("Failed to remove user %d's directory", userId);
1114 }
1115 }
Kenny Root655b9582013-04-04 08:37:42 -07001116 }
1117
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001118 bool isEmpty(uid_t userId) const {
1119 const UserState* userState = getUserState(userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001120 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001121 return true;
1122 }
1123
1124 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001125 if (!dir) {
1126 return true;
1127 }
Kenny Root31e27462014-09-10 11:28:03 -07001128
Kenny Roota91203b2012-02-15 15:00:46 -08001129 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001130 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001131 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001132 // We only care about files.
1133 if (file->d_type != DT_REG) {
1134 continue;
1135 }
1136
1137 // Skip anything that starts with a "."
1138 if (file->d_name[0] == '.') {
1139 continue;
1140 }
1141
Kenny Root31e27462014-09-10 11:28:03 -07001142 result = false;
1143 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001144 }
1145 closedir(dir);
1146 return result;
1147 }
1148
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001149 void lock(uid_t userId) {
1150 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001151 userState->zeroizeMasterKeysInMemory();
1152 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001153 }
1154
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001155 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1156 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001157 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1158 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001159 if (rc != NO_ERROR) {
1160 return rc;
1161 }
1162
1163 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001164 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001165 /* If we upgrade the key, we need to write it to disk again. Then
1166 * it must be read it again since the blob is encrypted each time
1167 * it's written.
1168 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001169 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1170 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001171 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1172 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001173 return rc;
1174 }
1175 }
Kenny Root822c3a92012-03-23 16:34:39 -07001176 }
1177
Kenny Root17208e02013-09-04 13:56:03 -07001178 /*
1179 * This will upgrade software-backed keys to hardware-backed keys when
1180 * the HAL for the device supports the newer key types.
1181 */
1182 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1183 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1184 && keyBlob->isFallback()) {
1185 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001186 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001187
1188 // The HAL allowed the import, reget the key to have the "fresh"
1189 // version.
1190 if (imported == NO_ERROR) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001191 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001192 }
1193 }
1194
Kenny Rootd53bc922013-03-21 14:10:15 -07001195 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001196 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1197 return KEY_NOT_FOUND;
1198 }
1199
1200 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001201 }
1202
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001203 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1204 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001205 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1206 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001207 }
1208
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001209 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001210 Blob keyBlob;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001211 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001212 if (rc != ::NO_ERROR) {
1213 return rc;
1214 }
1215
1216 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1217 // A device doesn't have to implement delete_keypair.
1218 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1219 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1220 rc = ::SYSTEM_ERROR;
1221 }
1222 }
1223 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001224 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1225 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1226 if (dev->delete_key) {
1227 keymaster_key_blob_t blob;
1228 blob.key_material = keyBlob.getValue();
1229 blob.key_material_size = keyBlob.getLength();
1230 dev->delete_key(dev, &blob);
1231 }
1232 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001233 if (rc != ::NO_ERROR) {
1234 return rc;
1235 }
1236
1237 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1238 }
1239
Chad Brubaker94436162015-05-12 15:18:26 -07001240 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001241 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001242
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001243 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001244 size_t n = prefix.length();
1245
1246 DIR* dir = opendir(userState->getUserDirName());
1247 if (!dir) {
1248 ALOGW("can't open directory for user: %s", strerror(errno));
1249 return ::SYSTEM_ERROR;
1250 }
1251
1252 struct dirent* file;
1253 while ((file = readdir(dir)) != NULL) {
1254 // We only care about files.
1255 if (file->d_type != DT_REG) {
1256 continue;
1257 }
1258
1259 // Skip anything that starts with a "."
1260 if (file->d_name[0] == '.') {
1261 continue;
1262 }
1263
1264 if (!strncmp(prefix.string(), file->d_name, n)) {
1265 const char* p = &file->d_name[n];
1266 size_t plen = strlen(p);
1267
1268 size_t extra = decode_key_length(p, plen);
1269 char *match = (char*) malloc(extra + 1);
1270 if (match != NULL) {
1271 decode_key(match, p, plen);
1272 matches->push(android::String16(match, extra));
1273 free(match);
1274 } else {
1275 ALOGW("could not allocate match of size %zd", extra);
1276 }
1277 }
1278 }
1279 closedir(dir);
1280 return ::NO_ERROR;
1281 }
1282
Kenny Root07438c82012-11-02 15:41:02 -07001283 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001284 const grant_t* existing = getGrant(filename, granteeUid);
1285 if (existing == NULL) {
1286 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001287 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001288 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001289 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001290 }
1291 }
1292
Kenny Root07438c82012-11-02 15:41:02 -07001293 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001294 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1295 it != mGrants.end(); it++) {
1296 grant_t* grant = *it;
1297 if (grant->uid == granteeUid
1298 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1299 mGrants.erase(it);
1300 return true;
1301 }
Kenny Root70e3a862012-02-15 17:20:23 -08001302 }
Kenny Root70e3a862012-02-15 17:20:23 -08001303 return false;
1304 }
1305
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001306 bool hasGrant(const char* filename, const uid_t uid) const {
1307 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001308 }
1309
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001310 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001311 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001312 uint8_t* data;
1313 size_t dataLength;
1314 int rc;
1315
1316 if (mDevice->import_keypair == NULL) {
1317 ALOGE("Keymaster doesn't support import!");
1318 return SYSTEM_ERROR;
1319 }
1320
Kenny Root17208e02013-09-04 13:56:03 -07001321 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001322 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001323 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001324 /*
1325 * Maybe the device doesn't support this type of key. Try to use the
1326 * software fallback keymaster implementation. This is a little bit
1327 * lazier than checking the PKCS#8 key type, but the software
1328 * implementation will do that anyway.
1329 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001330 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001331 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001332
1333 if (rc) {
1334 ALOGE("Error while importing keypair: %d", rc);
1335 return SYSTEM_ERROR;
1336 }
Kenny Root822c3a92012-03-23 16:34:39 -07001337 }
1338
1339 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1340 free(data);
1341
Kenny Rootf9119d62013-04-03 09:22:15 -07001342 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001343 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001344
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001345 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001346 }
1347
Kenny Root1b0e3932013-09-05 13:06:32 -07001348 bool isHardwareBacked(const android::String16& keyType) const {
1349 if (mDevice == NULL) {
1350 ALOGW("can't get keymaster device");
1351 return false;
1352 }
1353
1354 if (sRSAKeyType == keyType) {
1355 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1356 } else {
1357 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1358 && (mDevice->common.module->module_api_version
1359 >= KEYMASTER_MODULE_API_VERSION_0_2);
1360 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001361 }
1362
Kenny Root655b9582013-04-04 08:37:42 -07001363 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1364 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001365 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001366 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001367
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001368 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001369 if (responseCode == NO_ERROR) {
1370 return responseCode;
1371 }
1372
1373 // If this is one of the legacy UID->UID mappings, use it.
1374 uid_t euid = get_keystore_euid(uid);
1375 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001376 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001377 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001378 if (responseCode == NO_ERROR) {
1379 return responseCode;
1380 }
1381 }
1382
1383 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001384 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001385 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001386 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001387 if (end[0] != '_' || end[1] == 0) {
1388 return KEY_NOT_FOUND;
1389 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001390 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001391 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001392 if (!hasGrant(filepath8.string(), uid)) {
1393 return responseCode;
1394 }
1395
1396 // It is a granted key. Try to load it.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001397 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001398 }
1399
1400 /**
1401 * Returns any existing UserState or creates it if it doesn't exist.
1402 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001403 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001404 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1405 it != mMasterKeys.end(); it++) {
1406 UserState* state = *it;
1407 if (state->getUserId() == userId) {
1408 return state;
1409 }
1410 }
1411
1412 UserState* userState = new UserState(userId);
1413 if (!userState->initialize()) {
1414 /* There's not much we can do if initialization fails. Trying to
1415 * unlock the keystore for that user will fail as well, so any
1416 * subsequent request for this user will just return SYSTEM_ERROR.
1417 */
1418 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1419 }
1420 mMasterKeys.add(userState);
1421 return userState;
1422 }
1423
1424 /**
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001425 * Returns any existing UserState or creates it if it doesn't exist.
1426 */
1427 UserState* getUserStateByUid(uid_t uid) {
1428 uid_t userId = get_user_id(uid);
1429 return getUserState(userId);
1430 }
1431
1432 /**
Kenny Root655b9582013-04-04 08:37:42 -07001433 * Returns NULL if the UserState doesn't already exist.
1434 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001435 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001436 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1437 it != mMasterKeys.end(); it++) {
1438 UserState* state = *it;
1439 if (state->getUserId() == userId) {
1440 return state;
1441 }
1442 }
1443
1444 return NULL;
1445 }
1446
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001447 /**
1448 * Returns NULL if the UserState doesn't already exist.
1449 */
1450 const UserState* getUserStateByUid(uid_t uid) const {
1451 uid_t userId = get_user_id(uid);
1452 return getUserState(userId);
1453 }
1454
Kenny Roota91203b2012-02-15 15:00:46 -08001455private:
Kenny Root655b9582013-04-04 08:37:42 -07001456 static const char* sOldMasterKey;
1457 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001458 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001459 Entropy* mEntropy;
1460
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001461 keymaster1_device_t* mDevice;
1462 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001463
Kenny Root655b9582013-04-04 08:37:42 -07001464 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001465
Kenny Root655b9582013-04-04 08:37:42 -07001466 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001467
Kenny Root655b9582013-04-04 08:37:42 -07001468 typedef struct {
1469 uint32_t version;
1470 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001471
Kenny Root655b9582013-04-04 08:37:42 -07001472 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001473
Kenny Root655b9582013-04-04 08:37:42 -07001474 const grant_t* getGrant(const char* filename, uid_t uid) const {
1475 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1476 it != mGrants.end(); it++) {
1477 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001478 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001479 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001480 return grant;
1481 }
1482 }
Kenny Root70e3a862012-02-15 17:20:23 -08001483 return NULL;
1484 }
1485
Kenny Root822c3a92012-03-23 16:34:39 -07001486 /**
1487 * Upgrade code. This will upgrade the key from the current version
1488 * to whatever is newest.
1489 */
Kenny Root655b9582013-04-04 08:37:42 -07001490 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1491 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001492 bool updated = false;
1493 uint8_t version = oldVersion;
1494
1495 /* From V0 -> V1: All old types were unknown */
1496 if (version == 0) {
1497 ALOGV("upgrading to version 1 and setting type %d", type);
1498
1499 blob->setType(type);
1500 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001501 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001502 }
1503 version = 1;
1504 updated = true;
1505 }
1506
Kenny Rootf9119d62013-04-03 09:22:15 -07001507 /* From V1 -> V2: All old keys were encrypted */
1508 if (version == 1) {
1509 ALOGV("upgrading to version 2");
1510
1511 blob->setEncrypted(true);
1512 version = 2;
1513 updated = true;
1514 }
1515
Kenny Root822c3a92012-03-23 16:34:39 -07001516 /*
1517 * If we've updated, set the key blob to the right version
1518 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001519 */
Kenny Root822c3a92012-03-23 16:34:39 -07001520 if (updated) {
1521 ALOGV("updated and writing file %s", filename);
1522 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001523 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001524
1525 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001526 }
1527
1528 /**
1529 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1530 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1531 * Then it overwrites the original blob with the new blob
1532 * format that is returned from the keymaster.
1533 */
Kenny Root655b9582013-04-04 08:37:42 -07001534 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001535 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1536 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1537 if (b.get() == NULL) {
1538 ALOGE("Problem instantiating BIO");
1539 return SYSTEM_ERROR;
1540 }
1541
1542 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1543 if (pkey.get() == NULL) {
1544 ALOGE("Couldn't read old PEM file");
1545 return SYSTEM_ERROR;
1546 }
1547
1548 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1549 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1550 if (len < 0) {
1551 ALOGE("Couldn't measure PKCS#8 length");
1552 return SYSTEM_ERROR;
1553 }
1554
Kenny Root70c98892013-02-07 09:10:36 -08001555 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1556 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001557 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1558 ALOGE("Couldn't convert to PKCS#8");
1559 return SYSTEM_ERROR;
1560 }
1561
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001562 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001563 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001564 if (rc != NO_ERROR) {
1565 return rc;
1566 }
1567
Kenny Root655b9582013-04-04 08:37:42 -07001568 return get(filename, blob, TYPE_KEY_PAIR, uid);
1569 }
1570
1571 void readMetaData() {
1572 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1573 if (in < 0) {
1574 return;
1575 }
1576 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1577 if (fileLength != sizeof(mMetaData)) {
1578 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1579 sizeof(mMetaData));
1580 }
1581 close(in);
1582 }
1583
1584 void writeMetaData() {
1585 const char* tmpFileName = ".metadata.tmp";
1586 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1587 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1588 if (out < 0) {
1589 ALOGE("couldn't write metadata file: %s", strerror(errno));
1590 return;
1591 }
1592 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1593 if (fileLength != sizeof(mMetaData)) {
1594 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1595 sizeof(mMetaData));
1596 }
1597 close(out);
1598 rename(tmpFileName, sMetaDataFile);
1599 }
1600
1601 bool upgradeKeystore() {
1602 bool upgraded = false;
1603
1604 if (mMetaData.version == 0) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001605 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001606
1607 // Initialize first so the directory is made.
1608 userState->initialize();
1609
1610 // Migrate the old .masterkey file to user 0.
1611 if (access(sOldMasterKey, R_OK) == 0) {
1612 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1613 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1614 return false;
1615 }
1616 }
1617
1618 // Initialize again in case we had a key.
1619 userState->initialize();
1620
1621 // Try to migrate existing keys.
1622 DIR* dir = opendir(".");
1623 if (!dir) {
1624 // Give up now; maybe we can upgrade later.
1625 ALOGE("couldn't open keystore's directory; something is wrong");
1626 return false;
1627 }
1628
1629 struct dirent* file;
1630 while ((file = readdir(dir)) != NULL) {
1631 // We only care about files.
1632 if (file->d_type != DT_REG) {
1633 continue;
1634 }
1635
1636 // Skip anything that starts with a "."
1637 if (file->d_name[0] == '.') {
1638 continue;
1639 }
1640
1641 // Find the current file's user.
1642 char* end;
1643 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1644 if (end[0] != '_' || end[1] == 0) {
1645 continue;
1646 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001647 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001648 if (otherUser->getUserId() != 0) {
1649 unlinkat(dirfd(dir), file->d_name, 0);
1650 }
1651
1652 // Rename the file into user directory.
1653 DIR* otherdir = opendir(otherUser->getUserDirName());
1654 if (otherdir == NULL) {
1655 ALOGW("couldn't open user directory for rename");
1656 continue;
1657 }
1658 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1659 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1660 }
1661 closedir(otherdir);
1662 }
1663 closedir(dir);
1664
1665 mMetaData.version = 1;
1666 upgraded = true;
1667 }
1668
1669 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001670 }
Kenny Roota91203b2012-02-15 15:00:46 -08001671};
1672
Kenny Root655b9582013-04-04 08:37:42 -07001673const char* KeyStore::sOldMasterKey = ".masterkey";
1674const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001675
Kenny Root1b0e3932013-09-05 13:06:32 -07001676const android::String16 KeyStore::sRSAKeyType("RSA");
1677
Kenny Root07438c82012-11-02 15:41:02 -07001678namespace android {
1679class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1680public:
1681 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001682 : mKeyStore(keyStore),
1683 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001684 {
Kenny Roota91203b2012-02-15 15:00:46 -08001685 }
Kenny Roota91203b2012-02-15 15:00:46 -08001686
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001687 void binderDied(const wp<IBinder>& who) {
1688 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1689 for (auto token: operations) {
1690 abort(token);
1691 }
Kenny Root822c3a92012-03-23 16:34:39 -07001692 }
Kenny Roota91203b2012-02-15 15:00:46 -08001693
Chad Brubaker94436162015-05-12 15:18:26 -07001694 int32_t getState(int32_t userId) {
1695 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001696 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001697 }
Kenny Roota91203b2012-02-15 15:00:46 -08001698
Chad Brubaker94436162015-05-12 15:18:26 -07001699 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001700 }
1701
Kenny Root07438c82012-11-02 15:41:02 -07001702 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001703 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001704 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001705 }
Kenny Root07438c82012-11-02 15:41:02 -07001706
Chad Brubaker9489b792015-04-14 11:01:45 -07001707 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001708 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001709 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001710
Kenny Root655b9582013-04-04 08:37:42 -07001711 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001712 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001713 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001714 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001715 *item = NULL;
1716 *itemLength = 0;
1717 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001718 }
Kenny Roota91203b2012-02-15 15:00:46 -08001719
Kenny Root07438c82012-11-02 15:41:02 -07001720 *item = (uint8_t*) malloc(keyBlob.getLength());
1721 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1722 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001723
Kenny Root07438c82012-11-02 15:41:02 -07001724 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001725 }
1726
Kenny Rootf9119d62013-04-03 09:22:15 -07001727 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1728 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001729 targetUid = getEffectiveUid(targetUid);
1730 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1731 flags & KEYSTORE_FLAG_ENCRYPTED);
1732 if (result != ::NO_ERROR) {
1733 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001734 }
1735
Kenny Root07438c82012-11-02 15:41:02 -07001736 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001737 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001738
1739 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001740 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1741
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001742 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001743 }
1744
Kenny Root49468902013-03-19 13:41:33 -07001745 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001746 targetUid = getEffectiveUid(targetUid);
1747 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001748 return ::PERMISSION_DENIED;
1749 }
Kenny Root07438c82012-11-02 15:41:02 -07001750 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001751 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001752 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001753 }
1754
Kenny Root49468902013-03-19 13:41:33 -07001755 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001756 targetUid = getEffectiveUid(targetUid);
1757 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001758 return ::PERMISSION_DENIED;
1759 }
1760
Kenny Root07438c82012-11-02 15:41:02 -07001761 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001762 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001763
Kenny Root655b9582013-04-04 08:37:42 -07001764 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001765 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1766 }
1767 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001768 }
1769
Chad Brubaker94436162015-05-12 15:18:26 -07001770 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001771 targetUid = getEffectiveUid(targetUid);
Chad Brubaker94436162015-05-12 15:18:26 -07001772 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001773 return ::PERMISSION_DENIED;
1774 }
Kenny Root07438c82012-11-02 15:41:02 -07001775 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001776 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001777
Chad Brubaker94436162015-05-12 15:18:26 -07001778 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001779 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001780 }
Kenny Root07438c82012-11-02 15:41:02 -07001781 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001782 }
1783
Kenny Root07438c82012-11-02 15:41:02 -07001784 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001785 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001786 return ::PERMISSION_DENIED;
1787 }
1788
Chad Brubaker9489b792015-04-14 11:01:45 -07001789 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubakereecdd122015-05-07 10:19:40 -07001790 mKeyStore->resetUser(get_user_id(callingUid), false);
1791 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001792 }
1793
Chad Brubakereecdd122015-05-07 10:19:40 -07001794 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001795 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001796 return ::PERMISSION_DENIED;
1797 }
Kenny Root70e3a862012-02-15 17:20:23 -08001798
Kenny Root07438c82012-11-02 15:41:02 -07001799 const String8 password8(password);
Chad Brubakereecdd122015-05-07 10:19:40 -07001800 // Flush the auth token table to prevent stale tokens from sticking
1801 // around.
1802 mAuthTokenTable.Clear();
1803
1804 if (password.size() == 0) {
1805 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001806 mKeyStore->resetUser(userId, true);
Chad Brubakereecdd122015-05-07 10:19:40 -07001807 return ::NO_ERROR;
1808 } else {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001809 switch (mKeyStore->getState(userId)) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001810 case ::STATE_UNINITIALIZED: {
1811 // generate master key, encrypt with password, write to file,
1812 // initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001813 return mKeyStore->initializeUser(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001814 }
1815 case ::STATE_NO_ERROR: {
1816 // rewrite master key with new password.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001817 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001818 }
1819 case ::STATE_LOCKED: {
1820 ALOGE("Changing user %d's password while locked, clearing old encryption",
1821 userId);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001822 mKeyStore->resetUser(userId, true);
1823 return mKeyStore->initializeUser(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001824 }
Kenny Root07438c82012-11-02 15:41:02 -07001825 }
Chad Brubakereecdd122015-05-07 10:19:40 -07001826 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001827 }
Kenny Root70e3a862012-02-15 17:20:23 -08001828 }
1829
Chad Brubakerfd777e72015-05-12 10:43:10 -07001830 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1831 if (!checkBinderPermission(P_USER_CHANGED)) {
1832 return ::PERMISSION_DENIED;
1833 }
1834
1835 // Sanity check that the new user has an empty keystore.
1836 if (!mKeyStore->isEmpty(userId)) {
Chad Brubaker8df54382015-05-12 19:18:40 -07001837 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
Chad Brubakerfd777e72015-05-12 10:43:10 -07001838 }
1839 // Unconditionally clear the keystore, just to be safe.
1840 mKeyStore->resetUser(userId, false);
1841
1842 // If the user has a parent user then use the parent's
1843 // masterkey/password, otherwise there's nothing to do.
1844 if (parentId != -1) {
1845 return mKeyStore->copyMasterKey(parentId, userId);
1846 } else {
1847 return ::NO_ERROR;
1848 }
1849 }
1850
1851 int32_t onUserRemoved(int32_t userId) {
1852 if (!checkBinderPermission(P_USER_CHANGED)) {
1853 return ::PERMISSION_DENIED;
1854 }
1855
1856 mKeyStore->resetUser(userId, false);
1857 return ::NO_ERROR;
1858 }
1859
Chad Brubaker94436162015-05-12 15:18:26 -07001860 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001861 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001862 return ::PERMISSION_DENIED;
1863 }
Kenny Root70e3a862012-02-15 17:20:23 -08001864
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001865 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001866 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001867 ALOGD("calling lock in state: %d", state);
1868 return state;
1869 }
1870
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001871 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001872 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001873 }
1874
Chad Brubakereecdd122015-05-07 10:19:40 -07001875 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001876 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001877 return ::PERMISSION_DENIED;
1878 }
1879
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001880 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001881 if (state != ::STATE_LOCKED) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001882 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001883 return state;
1884 }
1885
1886 const String8 password8(pw);
Chad Brubakereecdd122015-05-07 10:19:40 -07001887 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001888 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001889 }
1890
Chad Brubaker94436162015-05-12 15:18:26 -07001891 bool isEmpty(int32_t userId) {
1892 if (!checkBinderPermission(P_IS_EMPTY)) {
1893 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001894 }
Kenny Root70e3a862012-02-15 17:20:23 -08001895
Chad Brubaker94436162015-05-12 15:18:26 -07001896 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001897 }
1898
Kenny Root96427ba2013-08-16 14:02:41 -07001899 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1900 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001901 targetUid = getEffectiveUid(targetUid);
1902 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1903 flags & KEYSTORE_FLAG_ENCRYPTED);
1904 if (result != ::NO_ERROR) {
1905 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001906 }
Kenny Root07438c82012-11-02 15:41:02 -07001907 uint8_t* data;
1908 size_t dataLength;
1909 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001910 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001911
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001912 const keymaster1_device_t* device = mKeyStore->getDevice();
1913 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001914 if (device == NULL) {
1915 return ::SYSTEM_ERROR;
1916 }
1917
1918 if (device->generate_keypair == NULL) {
1919 return ::SYSTEM_ERROR;
1920 }
1921
Kenny Root17208e02013-09-04 13:56:03 -07001922 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001923 keymaster_dsa_keygen_params_t dsa_params;
1924 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001925
Kenny Root96427ba2013-08-16 14:02:41 -07001926 if (keySize == -1) {
1927 keySize = DSA_DEFAULT_KEY_SIZE;
1928 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1929 || keySize > DSA_MAX_KEY_SIZE) {
1930 ALOGI("invalid key size %d", keySize);
1931 return ::SYSTEM_ERROR;
1932 }
1933 dsa_params.key_size = keySize;
1934
1935 if (args->size() == 3) {
1936 sp<KeystoreArg> gArg = args->itemAt(0);
1937 sp<KeystoreArg> pArg = args->itemAt(1);
1938 sp<KeystoreArg> qArg = args->itemAt(2);
1939
1940 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1941 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1942 dsa_params.generator_len = gArg->size();
1943
1944 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1945 dsa_params.prime_p_len = pArg->size();
1946
1947 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1948 dsa_params.prime_q_len = qArg->size();
1949 } else {
1950 ALOGI("not all DSA parameters were read");
1951 return ::SYSTEM_ERROR;
1952 }
1953 } else if (args->size() != 0) {
1954 ALOGI("DSA args must be 3");
1955 return ::SYSTEM_ERROR;
1956 }
1957
Kenny Root1d448c02013-11-21 10:36:53 -08001958 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001959 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1960 } else {
1961 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001962 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1963 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001964 }
1965 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001966 keymaster_ec_keygen_params_t ec_params;
1967 memset(&ec_params, '\0', sizeof(ec_params));
1968
1969 if (keySize == -1) {
1970 keySize = EC_DEFAULT_KEY_SIZE;
1971 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1972 ALOGI("invalid key size %d", keySize);
1973 return ::SYSTEM_ERROR;
1974 }
1975 ec_params.field_size = keySize;
1976
Kenny Root1d448c02013-11-21 10:36:53 -08001977 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001978 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1979 } else {
1980 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001981 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001982 }
Kenny Root96427ba2013-08-16 14:02:41 -07001983 } else if (keyType == EVP_PKEY_RSA) {
1984 keymaster_rsa_keygen_params_t rsa_params;
1985 memset(&rsa_params, '\0', sizeof(rsa_params));
1986 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1987
1988 if (keySize == -1) {
1989 keySize = RSA_DEFAULT_KEY_SIZE;
1990 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1991 ALOGI("invalid key size %d", keySize);
1992 return ::SYSTEM_ERROR;
1993 }
1994 rsa_params.modulus_size = keySize;
1995
1996 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001997 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001998 return ::SYSTEM_ERROR;
1999 } else if (args->size() == 1) {
2000 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
2001 if (pubExpBlob != NULL) {
2002 Unique_BIGNUM pubExpBn(
2003 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
2004 pubExpBlob->size(), NULL));
2005 if (pubExpBn.get() == NULL) {
2006 ALOGI("Could not convert public exponent to BN");
2007 return ::SYSTEM_ERROR;
2008 }
2009 unsigned long pubExp = BN_get_word(pubExpBn.get());
2010 if (pubExp == 0xFFFFFFFFL) {
2011 ALOGI("cannot represent public exponent as a long value");
2012 return ::SYSTEM_ERROR;
2013 }
2014 rsa_params.public_exponent = pubExp;
2015 }
2016 }
2017
2018 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
2019 } else {
2020 ALOGW("Unsupported key type %d", keyType);
2021 rc = -1;
2022 }
2023
Kenny Root07438c82012-11-02 15:41:02 -07002024 if (rc) {
2025 return ::SYSTEM_ERROR;
2026 }
2027
Kenny Root655b9582013-04-04 08:37:42 -07002028 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07002029 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002030
2031 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2032 free(data);
2033
Kenny Rootee8068b2013-10-07 09:49:15 -07002034 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002035 keyBlob.setFallback(isFallback);
2036
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002037 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08002038 }
2039
Kenny Rootf9119d62013-04-03 09:22:15 -07002040 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2041 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002042 targetUid = getEffectiveUid(targetUid);
2043 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2044 flags & KEYSTORE_FLAG_ENCRYPTED);
2045 if (result != ::NO_ERROR) {
2046 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002047 }
Kenny Root07438c82012-11-02 15:41:02 -07002048 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002049 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002050
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002051 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2052 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002053 }
2054
Kenny Root07438c82012-11-02 15:41:02 -07002055 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2056 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002057 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002058 return ::PERMISSION_DENIED;
2059 }
Kenny Root07438c82012-11-02 15:41:02 -07002060
Chad Brubaker9489b792015-04-14 11:01:45 -07002061 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002062 Blob keyBlob;
2063 String8 name8(name);
2064
Kenny Rootd38a0b02013-02-13 12:59:14 -08002065 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002066
Kenny Root655b9582013-04-04 08:37:42 -07002067 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002068 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002069 if (responseCode != ::NO_ERROR) {
2070 return responseCode;
2071 }
2072
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002073 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002074 if (device == NULL) {
2075 ALOGE("no keymaster device; cannot sign");
2076 return ::SYSTEM_ERROR;
2077 }
2078
2079 if (device->sign_data == NULL) {
2080 ALOGE("device doesn't implement signing");
2081 return ::SYSTEM_ERROR;
2082 }
2083
2084 keymaster_rsa_sign_params_t params;
2085 params.digest_type = DIGEST_NONE;
2086 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002087 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002088 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002089 if (rc) {
2090 ALOGW("device couldn't sign data");
2091 return ::SYSTEM_ERROR;
2092 }
2093
2094 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002095 }
2096
Kenny Root07438c82012-11-02 15:41:02 -07002097 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2098 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002099 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002100 return ::PERMISSION_DENIED;
2101 }
Kenny Root70e3a862012-02-15 17:20:23 -08002102
Chad Brubaker9489b792015-04-14 11:01:45 -07002103 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002104 Blob keyBlob;
2105 String8 name8(name);
2106 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002107
Kenny Root655b9582013-04-04 08:37:42 -07002108 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002109 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002110 if (responseCode != ::NO_ERROR) {
2111 return responseCode;
2112 }
Kenny Root70e3a862012-02-15 17:20:23 -08002113
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002114 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002115 if (device == NULL) {
2116 return ::SYSTEM_ERROR;
2117 }
Kenny Root70e3a862012-02-15 17:20:23 -08002118
Kenny Root07438c82012-11-02 15:41:02 -07002119 if (device->verify_data == NULL) {
2120 return ::SYSTEM_ERROR;
2121 }
Kenny Root70e3a862012-02-15 17:20:23 -08002122
Kenny Root07438c82012-11-02 15:41:02 -07002123 keymaster_rsa_sign_params_t params;
2124 params.digest_type = DIGEST_NONE;
2125 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002126
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002127 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2128 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002129 if (rc) {
2130 return ::SYSTEM_ERROR;
2131 } else {
2132 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002133 }
2134 }
Kenny Root07438c82012-11-02 15:41:02 -07002135
2136 /*
2137 * TODO: The abstraction between things stored in hardware and regular blobs
2138 * of data stored on the filesystem should be moved down to keystore itself.
2139 * Unfortunately the Java code that calls this has naming conventions that it
2140 * knows about. Ideally keystore shouldn't be used to store random blobs of
2141 * data.
2142 *
2143 * Until that happens, it's necessary to have a separate "get_pubkey" and
2144 * "del_key" since the Java code doesn't really communicate what it's
2145 * intentions are.
2146 */
2147 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002148 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002149 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002150 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002151 return ::PERMISSION_DENIED;
2152 }
Kenny Root07438c82012-11-02 15:41:02 -07002153
Kenny Root07438c82012-11-02 15:41:02 -07002154 Blob keyBlob;
2155 String8 name8(name);
2156
Kenny Rootd38a0b02013-02-13 12:59:14 -08002157 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002158
Kenny Root655b9582013-04-04 08:37:42 -07002159 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002160 TYPE_KEY_PAIR);
2161 if (responseCode != ::NO_ERROR) {
2162 return responseCode;
2163 }
2164
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002165 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002166 if (device == NULL) {
2167 return ::SYSTEM_ERROR;
2168 }
2169
2170 if (device->get_keypair_public == NULL) {
2171 ALOGE("device has no get_keypair_public implementation!");
2172 return ::SYSTEM_ERROR;
2173 }
2174
Kenny Root17208e02013-09-04 13:56:03 -07002175 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002176 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2177 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002178 if (rc) {
2179 return ::SYSTEM_ERROR;
2180 }
2181
2182 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002183 }
Kenny Root07438c82012-11-02 15:41:02 -07002184
Kenny Root07438c82012-11-02 15:41:02 -07002185 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002186 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002187 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2188 if (result != ::NO_ERROR) {
2189 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002190 }
2191
2192 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002193 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002194
Kenny Root655b9582013-04-04 08:37:42 -07002195 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002196 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2197 }
2198
Kenny Root655b9582013-04-04 08:37:42 -07002199 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002200 return ::NO_ERROR;
2201 }
2202
2203 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002204 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002205 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2206 if (result != ::NO_ERROR) {
2207 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002208 }
2209
2210 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002211 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002212
Kenny Root655b9582013-04-04 08:37:42 -07002213 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002214 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2215 }
2216
Kenny Root655b9582013-04-04 08:37:42 -07002217 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002218 }
2219
2220 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002221 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002222 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002223 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002224 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002225 }
Kenny Root07438c82012-11-02 15:41:02 -07002226
2227 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002228 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002229
Kenny Root655b9582013-04-04 08:37:42 -07002230 if (access(filename.string(), R_OK) == -1) {
2231 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002232 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002233 }
2234
Kenny Root655b9582013-04-04 08:37:42 -07002235 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002236 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002237 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002238 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002239 }
2240
2241 struct stat s;
2242 int ret = fstat(fd, &s);
2243 close(fd);
2244 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002245 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002246 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002247 }
2248
Kenny Root36a9e232013-02-04 14:24:15 -08002249 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002250 }
2251
Kenny Rootd53bc922013-03-21 14:10:15 -07002252 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2253 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002254 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002255 pid_t spid = IPCThreadState::self()->getCallingPid();
2256 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002257 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002258 return -1L;
2259 }
2260
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002261 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002262 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002263 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002264 return state;
2265 }
2266
Kenny Rootd53bc922013-03-21 14:10:15 -07002267 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2268 srcUid = callingUid;
2269 } else if (!is_granted_to(callingUid, srcUid)) {
2270 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002271 return ::PERMISSION_DENIED;
2272 }
2273
Kenny Rootd53bc922013-03-21 14:10:15 -07002274 if (destUid == -1) {
2275 destUid = callingUid;
2276 }
2277
2278 if (srcUid != destUid) {
2279 if (static_cast<uid_t>(srcUid) != callingUid) {
2280 ALOGD("can only duplicate from caller to other or to same uid: "
2281 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2282 return ::PERMISSION_DENIED;
2283 }
2284
2285 if (!is_granted_to(callingUid, destUid)) {
2286 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2287 return ::PERMISSION_DENIED;
2288 }
2289 }
2290
2291 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002292 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002293
Kenny Rootd53bc922013-03-21 14:10:15 -07002294 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002295 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002296
Kenny Root655b9582013-04-04 08:37:42 -07002297 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2298 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002299 return ::SYSTEM_ERROR;
2300 }
2301
Kenny Rootd53bc922013-03-21 14:10:15 -07002302 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002303 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002304 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002305 if (responseCode != ::NO_ERROR) {
2306 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002307 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002308
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002309 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002310 }
2311
Kenny Root1b0e3932013-09-05 13:06:32 -07002312 int32_t is_hardware_backed(const String16& keyType) {
2313 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002314 }
2315
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002316 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002317 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubaker01771ae2015-05-01 10:21:27 -07002318 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002319 return ::PERMISSION_DENIED;
2320 }
2321
Robin Lee4b84fdc2014-09-24 11:56:57 +01002322 String8 prefix = String8::format("%u_", targetUid);
2323 Vector<String16> aliases;
Chad Brubaker94436162015-05-12 15:18:26 -07002324 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002325 return ::SYSTEM_ERROR;
2326 }
2327
Robin Lee4b84fdc2014-09-24 11:56:57 +01002328 for (uint32_t i = 0; i < aliases.size(); i++) {
2329 String8 name8(aliases[i]);
2330 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002331 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002332 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002333 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002334 }
2335
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002336 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2337 const keymaster1_device_t* device = mKeyStore->getDevice();
2338 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2339 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2340 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2341 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2342 device->add_rng_entropy != NULL) {
2343 devResult = device->add_rng_entropy(device, data, dataLength);
2344 }
2345 if (fallback->add_rng_entropy) {
2346 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2347 }
2348 if (devResult) {
2349 return devResult;
2350 }
2351 if (fallbackResult) {
2352 return fallbackResult;
2353 }
2354 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002355 }
2356
Chad Brubaker17d68b92015-02-05 22:04:16 -08002357 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002358 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2359 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002360 uid = getEffectiveUid(uid);
2361 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2362 flags & KEYSTORE_FLAG_ENCRYPTED);
2363 if (rc != ::NO_ERROR) {
2364 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002365 }
2366
Chad Brubaker9489b792015-04-14 11:01:45 -07002367 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002368 bool isFallback = false;
2369 keymaster_key_blob_t blob;
2370 keymaster_key_characteristics_t *out = NULL;
2371
2372 const keymaster1_device_t* device = mKeyStore->getDevice();
2373 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002374 std::vector<keymaster_key_param_t> opParams(params.params);
2375 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002376 if (device == NULL) {
2377 return ::SYSTEM_ERROR;
2378 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002379 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002380 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2381 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002382 if (!entropy) {
2383 rc = KM_ERROR_OK;
2384 } else if (device->add_rng_entropy) {
2385 rc = device->add_rng_entropy(device, entropy, entropyLength);
2386 } else {
2387 rc = KM_ERROR_UNIMPLEMENTED;
2388 }
2389 if (rc == KM_ERROR_OK) {
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002390 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002391 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002392 }
2393 // If the HW device didn't support generate_key or generate_key failed
2394 // fall back to the software implementation.
2395 if (rc && fallback->generate_key != NULL) {
2396 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002397 if (!entropy) {
2398 rc = KM_ERROR_OK;
2399 } else if (fallback->add_rng_entropy) {
2400 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2401 } else {
2402 rc = KM_ERROR_UNIMPLEMENTED;
2403 }
2404 if (rc == KM_ERROR_OK) {
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002405 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002406 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002407 }
2408
2409 if (out) {
2410 if (outCharacteristics) {
2411 outCharacteristics->characteristics = *out;
2412 } else {
2413 keymaster_free_characteristics(out);
2414 }
2415 free(out);
2416 }
2417
2418 if (rc) {
2419 return rc;
2420 }
2421
2422 String8 name8(name);
2423 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2424
2425 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2426 keyBlob.setFallback(isFallback);
2427 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2428
2429 free(const_cast<uint8_t*>(blob.key_material));
2430
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002431 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002432 }
2433
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002434 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002435 const keymaster_blob_t* clientId,
2436 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002437 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002438 if (!outCharacteristics) {
2439 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2440 }
2441
2442 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2443
2444 Blob keyBlob;
2445 String8 name8(name);
2446 int rc;
2447
2448 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2449 TYPE_KEYMASTER_10);
2450 if (responseCode != ::NO_ERROR) {
2451 return responseCode;
2452 }
2453 keymaster_key_blob_t key;
2454 key.key_material_size = keyBlob.getLength();
2455 key.key_material = keyBlob.getValue();
2456 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2457 keymaster_key_characteristics_t *out = NULL;
2458 if (!dev->get_key_characteristics) {
2459 ALOGW("device does not implement get_key_characteristics");
2460 return KM_ERROR_UNIMPLEMENTED;
2461 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002462 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002463 if (out) {
2464 outCharacteristics->characteristics = *out;
2465 free(out);
2466 }
2467 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002468 }
2469
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002470 int32_t importKey(const String16& name, const KeymasterArguments& params,
2471 keymaster_key_format_t format, const uint8_t *keyData,
2472 size_t keyLength, int uid, int flags,
2473 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002474 uid = getEffectiveUid(uid);
2475 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2476 flags & KEYSTORE_FLAG_ENCRYPTED);
2477 if (rc != ::NO_ERROR) {
2478 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002479 }
2480
Chad Brubaker9489b792015-04-14 11:01:45 -07002481 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002482 bool isFallback = false;
2483 keymaster_key_blob_t blob;
2484 keymaster_key_characteristics_t *out = NULL;
2485
2486 const keymaster1_device_t* device = mKeyStore->getDevice();
2487 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002488 std::vector<keymaster_key_param_t> opParams(params.params);
2489 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2490 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002491 if (device == NULL) {
2492 return ::SYSTEM_ERROR;
2493 }
2494 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2495 device->import_key != NULL) {
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002496 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002497 }
2498 if (rc && fallback->import_key != NULL) {
2499 isFallback = true;
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002500 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002501 }
2502 if (out) {
2503 if (outCharacteristics) {
2504 outCharacteristics->characteristics = *out;
2505 } else {
2506 keymaster_free_characteristics(out);
2507 }
2508 free(out);
2509 }
2510 if (rc) {
2511 return rc;
2512 }
2513
2514 String8 name8(name);
2515 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2516
2517 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2518 keyBlob.setFallback(isFallback);
2519 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2520
2521 free((void*) blob.key_material);
2522
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002523 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002524 }
2525
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002526 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002527 const keymaster_blob_t* clientId,
2528 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002529
2530 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2531
2532 Blob keyBlob;
2533 String8 name8(name);
2534 int rc;
2535
2536 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2537 TYPE_KEYMASTER_10);
2538 if (responseCode != ::NO_ERROR) {
2539 result->resultCode = responseCode;
2540 return;
2541 }
2542 keymaster_key_blob_t key;
2543 key.key_material_size = keyBlob.getLength();
2544 key.key_material = keyBlob.getValue();
2545 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2546 if (!dev->export_key) {
2547 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2548 return;
2549 }
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002550 keymaster_blob_t output = {NULL, 0};
2551 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2552 result->exportData.reset(const_cast<uint8_t*>(output.data));
2553 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002554 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002555 }
2556
Chad Brubakerad6514a2015-04-09 14:00:26 -07002557
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002558 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002559 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002560 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002561 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2562 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2563 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2564 result->resultCode = ::PERMISSION_DENIED;
2565 return;
2566 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002567 if (!checkAllowedOperationParams(params.params)) {
2568 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2569 return;
2570 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002571 Blob keyBlob;
2572 String8 name8(name);
2573 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2574 TYPE_KEYMASTER_10);
2575 if (responseCode != ::NO_ERROR) {
2576 result->resultCode = responseCode;
2577 return;
2578 }
2579 keymaster_key_blob_t key;
2580 key.key_material_size = keyBlob.getLength();
2581 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002582 keymaster_operation_handle_t handle;
2583 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002584 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002585 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002586 Unique_keymaster_key_characteristics characteristics;
2587 characteristics.reset(new keymaster_key_characteristics_t);
2588 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2589 if (err) {
2590 result->resultCode = err;
2591 return;
2592 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002593 const hw_auth_token_t* authToken = NULL;
2594 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002595 /*failOnTokenMissing*/ false);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002596 // If per-operation auth is needed we need to begin the operation and
2597 // the client will need to authorize that operation before calling
2598 // update. Any other auth issues stop here.
2599 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2600 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002601 return;
2602 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002603 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002604 // Add entropy to the device first.
2605 if (entropy) {
2606 if (dev->add_rng_entropy) {
2607 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2608 } else {
2609 err = KM_ERROR_UNIMPLEMENTED;
2610 }
2611 if (err) {
2612 result->resultCode = err;
2613 return;
2614 }
2615 }
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002616 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2617 keymaster_key_param_set_t outParams = {NULL, 0};
2618 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002619
2620 // If there are too many operations abort the oldest operation that was
2621 // started as pruneable and try again.
2622 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2623 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2624 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2625 if (abort(oldest) != ::NO_ERROR) {
2626 break;
2627 }
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002628 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002629 }
2630 if (err) {
2631 result->resultCode = err;
2632 return;
2633 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002634
Chad Brubakerad6514a2015-04-09 14:00:26 -07002635 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2636 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002637 pruneable);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002638 if (authToken) {
2639 mOperationMap.setOperationAuthToken(operationToken, authToken);
2640 }
2641 // Return the authentication lookup result. If this is a per operation
2642 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2643 // application should get an auth token using the handle before the
2644 // first call to update, which will fail if keystore hasn't received the
2645 // auth token.
2646 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002647 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002648 result->handle = handle;
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002649 if (outParams.params) {
2650 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2651 free(outParams.params);
2652 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002653 }
2654
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002655 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2656 size_t dataLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002657 if (!checkAllowedOperationParams(params.params)) {
2658 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2659 return;
2660 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002661 const keymaster1_device_t* dev;
2662 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002663 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002664 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2665 return;
2666 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002667 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002668 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2669 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002670 result->resultCode = authResult;
2671 return;
2672 }
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002673 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2674 keymaster_blob_t input = {data, dataLength};
2675 size_t consumed = 0;
2676 keymaster_blob_t output = {NULL, 0};
2677 keymaster_key_param_set_t outParams = {NULL, 0};
2678
2679 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2680 &output);
2681 result->data.reset(const_cast<uint8_t*>(output.data));
2682 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002683 result->inputConsumed = consumed;
2684 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002685 if (outParams.params) {
2686 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2687 free(outParams.params);
2688 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002689 }
2690
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002691 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker8cfb8ac2015-05-29 12:30:19 -07002692 const uint8_t* signature, size_t signatureLength,
2693 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002694 if (!checkAllowedOperationParams(params.params)) {
2695 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2696 return;
2697 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002698 const keymaster1_device_t* dev;
2699 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002700 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002701 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2702 return;
2703 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002704 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002705 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2706 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002707 result->resultCode = authResult;
2708 return;
2709 }
Chad Brubaker8cfb8ac2015-05-29 12:30:19 -07002710 keymaster_error_t err;
2711 if (entropy) {
2712 if (dev->add_rng_entropy) {
2713 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2714 } else {
2715 err = KM_ERROR_UNIMPLEMENTED;
2716 }
2717 if (err) {
2718 result->resultCode = err;
2719 return;
2720 }
2721 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002722
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002723 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2724 keymaster_blob_t input = {signature, signatureLength};
2725 keymaster_blob_t output = {NULL, 0};
2726 keymaster_key_param_set_t outParams = {NULL, 0};
2727 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002728 // Remove the operation regardless of the result
2729 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002730 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002731
2732 result->data.reset(const_cast<uint8_t*>(output.data));
2733 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002734 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker773a2ba2015-06-01 12:59:00 -07002735 if (outParams.params) {
2736 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2737 free(outParams.params);
2738 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002739 }
2740
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002741 int32_t abort(const sp<IBinder>& token) {
2742 const keymaster1_device_t* dev;
2743 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002744 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002745 return KM_ERROR_INVALID_OPERATION_HANDLE;
2746 }
2747 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002748 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002749 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002750 rc = KM_ERROR_UNIMPLEMENTED;
2751 } else {
2752 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002753 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002754 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002755 if (rc) {
2756 return rc;
2757 }
2758 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002759 }
2760
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002761 bool isOperationAuthorized(const sp<IBinder>& token) {
2762 const keymaster1_device_t* dev;
2763 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002764 const keymaster_key_characteristics_t* characteristics;
2765 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002766 return false;
2767 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002768 const hw_auth_token_t* authToken = NULL;
2769 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002770 std::vector<keymaster_key_param_t> ignored;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002771 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2772 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002773 }
2774
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002775 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002776 if (!checkBinderPermission(P_ADD_AUTH)) {
2777 ALOGW("addAuthToken: permission denied for %d",
2778 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002779 return ::PERMISSION_DENIED;
2780 }
2781 if (length != sizeof(hw_auth_token_t)) {
2782 return KM_ERROR_INVALID_ARGUMENT;
2783 }
2784 hw_auth_token_t* authToken = new hw_auth_token_t;
2785 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2786 // The table takes ownership of authToken.
2787 mAuthTokenTable.AddAuthenticationToken(authToken);
2788 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002789 }
2790
Kenny Root07438c82012-11-02 15:41:02 -07002791private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002792 static const int32_t UID_SELF = -1;
2793
2794 /**
2795 * Get the effective target uid for a binder operation that takes an
2796 * optional uid as the target.
2797 */
2798 inline uid_t getEffectiveUid(int32_t targetUid) {
2799 if (targetUid == UID_SELF) {
2800 return IPCThreadState::self()->getCallingUid();
2801 }
2802 return static_cast<uid_t>(targetUid);
2803 }
2804
2805 /**
2806 * Check if the caller of the current binder method has the required
2807 * permission and if acting on other uids the grants to do so.
2808 */
2809 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2810 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2811 pid_t spid = IPCThreadState::self()->getCallingPid();
2812 if (!has_permission(callingUid, permission, spid)) {
2813 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2814 return false;
2815 }
2816 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2817 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2818 return false;
2819 }
2820 return true;
2821 }
2822
2823 /**
2824 * Check if the caller of the current binder method has the required
Chad Brubaker01771ae2015-05-01 10:21:27 -07002825 * permission and the target uid is the caller or the caller is system.
2826 */
2827 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2828 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2829 pid_t spid = IPCThreadState::self()->getCallingPid();
2830 if (!has_permission(callingUid, permission, spid)) {
2831 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2832 return false;
2833 }
2834 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2835 }
2836
2837 /**
2838 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002839 * permission or the target of the operation is the caller's uid. This is
2840 * for operation where the permission is only for cross-uid activity and all
2841 * uids are allowed to act on their own (ie: clearing all entries for a
2842 * given uid).
2843 */
2844 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2845 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2846 if (getEffectiveUid(targetUid) == callingUid) {
2847 return true;
2848 } else {
2849 return checkBinderPermission(permission, targetUid);
2850 }
2851 }
2852
2853 /**
2854 * Helper method to check that the caller has the required permission as
2855 * well as the keystore is in the unlocked state if checkUnlocked is true.
2856 *
2857 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2858 * otherwise the state of keystore when not unlocked and checkUnlocked is
2859 * true.
2860 */
2861 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2862 bool checkUnlocked = true) {
2863 if (!checkBinderPermission(permission, targetUid)) {
2864 return ::PERMISSION_DENIED;
2865 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002866 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002867 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2868 return state;
2869 }
2870
2871 return ::NO_ERROR;
2872
2873 }
2874
Kenny Root9d45d1c2013-02-14 10:32:30 -08002875 inline bool isKeystoreUnlocked(State state) {
2876 switch (state) {
2877 case ::STATE_NO_ERROR:
2878 return true;
2879 case ::STATE_UNINITIALIZED:
2880 case ::STATE_LOCKED:
2881 return false;
2882 }
2883 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002884 }
2885
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002886 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002887 const int32_t device_api = device->common.module->module_api_version;
2888 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2889 switch (keyType) {
2890 case TYPE_RSA:
2891 case TYPE_DSA:
2892 case TYPE_EC:
2893 return true;
2894 default:
2895 return false;
2896 }
2897 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2898 switch (keyType) {
2899 case TYPE_RSA:
2900 return true;
2901 case TYPE_DSA:
2902 return device->flags & KEYMASTER_SUPPORTS_DSA;
2903 case TYPE_EC:
2904 return device->flags & KEYMASTER_SUPPORTS_EC;
2905 default:
2906 return false;
2907 }
2908 } else {
2909 return keyType == TYPE_RSA;
2910 }
2911 }
2912
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002913 /**
2914 * Check that all keymaster_key_param_t's provided by the application are
2915 * allowed. Any parameter that keystore adds itself should be disallowed here.
2916 */
2917 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2918 for (auto param: params) {
2919 switch (param.tag) {
2920 case KM_TAG_AUTH_TOKEN:
2921 return false;
2922 default:
2923 break;
2924 }
2925 }
2926 return true;
2927 }
2928
2929 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2930 const keymaster1_device_t* dev,
2931 const std::vector<keymaster_key_param_t>& params,
2932 keymaster_key_characteristics_t* out) {
2933 UniquePtr<keymaster_blob_t> appId;
2934 UniquePtr<keymaster_blob_t> appData;
2935 for (auto param : params) {
2936 if (param.tag == KM_TAG_APPLICATION_ID) {
2937 appId.reset(new keymaster_blob_t);
2938 appId->data = param.blob.data;
2939 appId->data_length = param.blob.data_length;
2940 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2941 appData.reset(new keymaster_blob_t);
2942 appData->data = param.blob.data;
2943 appData->data_length = param.blob.data_length;
2944 }
2945 }
2946 keymaster_key_characteristics_t* result = NULL;
2947 if (!dev->get_key_characteristics) {
2948 return KM_ERROR_UNIMPLEMENTED;
2949 }
2950 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2951 appData.get(), &result);
2952 if (result) {
2953 *out = *result;
2954 free(result);
2955 }
2956 return error;
2957 }
2958
2959 /**
2960 * Get the auth token for this operation from the auth token table.
2961 *
2962 * Returns ::NO_ERROR if the auth token was set or none was required.
2963 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2964 * authorization token exists for that operation and
2965 * failOnTokenMissing is false.
2966 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2967 * token for the operation
2968 */
2969 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2970 keymaster_operation_handle_t handle,
2971 const hw_auth_token_t** authToken,
2972 bool failOnTokenMissing = true) {
2973
2974 std::vector<keymaster_key_param_t> allCharacteristics;
2975 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2976 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2977 }
2978 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2979 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2980 }
2981 keymaster::AuthTokenTable::Error err =
2982 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2983 allCharacteristics.size(), handle, authToken);
2984 switch (err) {
2985 case keymaster::AuthTokenTable::OK:
2986 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2987 return ::NO_ERROR;
2988 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2989 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2990 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2991 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2992 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2993 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2994 (int32_t) ::OP_AUTH_NEEDED;
2995 default:
2996 ALOGE("Unexpected FindAuthorization return value %d", err);
2997 return KM_ERROR_INVALID_ARGUMENT;
2998 }
2999 }
3000
3001 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3002 const hw_auth_token_t* token) {
3003 if (token) {
3004 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3005 reinterpret_cast<const uint8_t*>(token),
3006 sizeof(hw_auth_token_t)));
3007 }
3008 }
3009
3010 /**
3011 * Add the auth token for the operation to the param list if the operation
3012 * requires authorization. Uses the cached result in the OperationMap if available
3013 * otherwise gets the token from the AuthTokenTable and caches the result.
3014 *
3015 * Returns ::NO_ERROR if the auth token was added or not needed.
3016 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3017 * authenticated.
3018 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3019 * operation token.
3020 */
3021 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3022 std::vector<keymaster_key_param_t>* params) {
3023 const hw_auth_token_t* authToken = NULL;
Chad Brubaker6b541162015-04-29 19:58:34 -07003024 mOperationMap.getOperationAuthToken(token, &authToken);
3025 if (!authToken) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07003026 const keymaster1_device_t* dev;
3027 keymaster_operation_handle_t handle;
3028 const keymaster_key_characteristics_t* characteristics = NULL;
3029 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3030 return KM_ERROR_INVALID_OPERATION_HANDLE;
3031 }
3032 int32_t result = getAuthToken(characteristics, handle, &authToken);
3033 if (result != ::NO_ERROR) {
3034 return result;
3035 }
3036 if (authToken) {
3037 mOperationMap.setOperationAuthToken(token, authToken);
3038 }
3039 }
3040 addAuthToParams(params, authToken);
3041 return ::NO_ERROR;
3042 }
3043
Kenny Root07438c82012-11-02 15:41:02 -07003044 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003045 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003046 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003047};
3048
3049}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003050
3051int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003052 if (argc < 2) {
3053 ALOGE("A directory must be specified!");
3054 return 1;
3055 }
3056 if (chdir(argv[1]) == -1) {
3057 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3058 return 1;
3059 }
3060
3061 Entropy entropy;
3062 if (!entropy.open()) {
3063 return 1;
3064 }
Kenny Root70e3a862012-02-15 17:20:23 -08003065
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07003066 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003067 if (keymaster_device_initialize(&dev)) {
3068 ALOGE("keystore keymaster could not be initialized; exiting");
3069 return 1;
3070 }
3071
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003072 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003073 if (fallback_keymaster_device_initialize(&fallback)) {
3074 ALOGE("software keymaster could not be initialized; exiting");
3075 return 1;
3076 }
3077
Riley Spahneaabae92014-06-30 12:39:52 -07003078 ks_is_selinux_enabled = is_selinux_enabled();
3079 if (ks_is_selinux_enabled) {
3080 union selinux_callback cb;
William Robertse46b8552015-10-02 08:19:52 -07003081 cb.func_audit = audit_callback;
3082 selinux_set_callback(SELINUX_CB_AUDIT, cb);
Riley Spahneaabae92014-06-30 12:39:52 -07003083 cb.func_log = selinux_log_callback;
3084 selinux_set_callback(SELINUX_CB_LOG, cb);
3085 if (getcon(&tctx) != 0) {
3086 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3087 return -1;
3088 }
3089 } else {
3090 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3091 }
3092
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003093 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003094 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003095 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3096 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3097 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3098 if (ret != android::OK) {
3099 ALOGE("Couldn't register binder service!");
3100 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003101 }
Kenny Root07438c82012-11-02 15:41:02 -07003102
3103 /*
3104 * We're the only thread in existence, so we're just going to process
3105 * Binder transaction as a single-threaded program.
3106 */
3107 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003108
3109 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003110 return 1;
3111}