blob: b36f65fb2a0b8a7c8f4e7a8ec9cd7d9b9b2b6b62 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubaker3a7d9e62015-06-04 15:01:46 -070066#include <sstream>
67
Chad Brubakerd80c7b42015-03-31 11:04:28 -070068#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069#include "defaults.h"
Shawn Willden9221bff2015-06-18 18:23:54 -060070#include "keystore_keymaster_enforcement.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080071#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070072
Kenny Roota91203b2012-02-15 15:00:46 -080073/* KeyStore is a secured storage for key-value pairs. In this implementation,
74 * each file stores one key-value pair. Keys are encoded in file names, and
75 * values are encrypted with checksums. The encryption key is protected by a
76 * user-defined password. To keep things simple, buffers are always larger than
77 * the maximum space we needed, so boundary checks on buffers are omitted. */
78
79#define KEY_SIZE ((NAME_MAX - 15) / 2)
80#define VALUE_SIZE 32768
81#define PASSWORD_SIZE VALUE_SIZE
82
Kenny Root822c3a92012-03-23 16:34:39 -070083
Kenny Root96427ba2013-08-16 14:02:41 -070084struct BIGNUM_Delete {
85 void operator()(BIGNUM* p) const {
86 BN_free(p);
87 }
88};
89typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
90
Kenny Root822c3a92012-03-23 16:34:39 -070091struct BIO_Delete {
92 void operator()(BIO* p) const {
93 BIO_free(p);
94 }
95};
96typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
97
98struct EVP_PKEY_Delete {
99 void operator()(EVP_PKEY* p) const {
100 EVP_PKEY_free(p);
101 }
102};
103typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
104
105struct PKCS8_PRIV_KEY_INFO_Delete {
106 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
107 PKCS8_PRIV_KEY_INFO_free(p);
108 }
109};
110typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
111
Chad Brubakerbd07a232015-06-01 10:44:27 -0700112static int keymaster_device_initialize(keymaster1_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800113 int rc;
114
115 const hw_module_t* mod;
Chad Brubakerbd07a232015-06-01 10:44:27 -0700116 keymaster::SoftKeymasterDevice* softkeymaster = NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800117 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
118 if (rc) {
119 ALOGE("could not find any keystore module");
120 goto out;
121 }
122
Chad Brubakerbd07a232015-06-01 10:44:27 -0700123 rc = mod->methods->open(mod, KEYSTORE_KEYMASTER, reinterpret_cast<struct hw_device_t**>(dev));
Kenny Root70e3a862012-02-15 17:20:23 -0800124 if (rc) {
125 ALOGE("could not open keymaster device in %s (%s)",
126 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
127 goto out;
128 }
129
Chad Brubakerbd07a232015-06-01 10:44:27 -0700130 // Wrap older hardware modules with a softkeymaster adapter.
131 if ((*dev)->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0) {
132 return 0;
133 }
134 softkeymaster =
135 new keymaster::SoftKeymasterDevice(reinterpret_cast<keymaster0_device_t*>(*dev));
136 *dev = softkeymaster->keymaster_device();
Kenny Root70e3a862012-02-15 17:20:23 -0800137 return 0;
138
139out:
140 *dev = NULL;
141 return rc;
142}
143
Shawn Willden04006752015-04-30 11:12:33 -0600144// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
145// logger used by SoftKeymasterDevice.
146static keymaster::SoftKeymasterLogger softkeymaster_logger;
147
Chad Brubaker67d2a502015-03-11 17:21:18 +0000148static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
149 keymaster::SoftKeymasterDevice* softkeymaster =
150 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600151 *dev = softkeymaster->keymaster_device();
152 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800153 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800154}
155
Chad Brubakerbd07a232015-06-01 10:44:27 -0700156static void keymaster_device_release(keymaster1_device_t* dev) {
157 dev->common.close(&dev->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800158}
159
Kenny Root07438c82012-11-02 15:41:02 -0700160/***************
161 * PERMISSIONS *
162 ***************/
163
164/* Here are the permissions, actions, users, and the main function. */
165typedef enum {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700166 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100167 P_GET = 1 << 1,
168 P_INSERT = 1 << 2,
169 P_DELETE = 1 << 3,
170 P_EXIST = 1 << 4,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700171 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100172 P_RESET = 1 << 6,
173 P_PASSWORD = 1 << 7,
174 P_LOCK = 1 << 8,
175 P_UNLOCK = 1 << 9,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700176 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100177 P_SIGN = 1 << 11,
178 P_VERIFY = 1 << 12,
179 P_GRANT = 1 << 13,
180 P_DUPLICATE = 1 << 14,
181 P_CLEAR_UID = 1 << 15,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700182 P_ADD_AUTH = 1 << 16,
183 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700184} perm_t;
185
186static struct user_euid {
187 uid_t uid;
188 uid_t euid;
189} user_euids[] = {
190 {AID_VPN, AID_SYSTEM},
191 {AID_WIFI, AID_SYSTEM},
192 {AID_ROOT, AID_SYSTEM},
193};
194
Riley Spahneaabae92014-06-30 12:39:52 -0700195/* perm_labels associcated with keystore_key SELinux class verbs. */
196const char *perm_labels[] = {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700197 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700198 "get",
199 "insert",
200 "delete",
201 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700202 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700203 "reset",
204 "password",
205 "lock",
206 "unlock",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700207 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700208 "sign",
209 "verify",
210 "grant",
211 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100212 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700213 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700214 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700215};
216
Kenny Root07438c82012-11-02 15:41:02 -0700217static struct user_perm {
218 uid_t uid;
219 perm_t perms;
220} user_perms[] = {
221 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
222 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
223 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
224 {AID_ROOT, static_cast<perm_t>(P_GET) },
225};
226
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700227static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
228 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700229
Riley Spahneaabae92014-06-30 12:39:52 -0700230static char *tctx;
231static int ks_is_selinux_enabled;
232
233static const char *get_perm_label(perm_t perm) {
234 unsigned int index = ffs(perm);
235 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
236 return perm_labels[index - 1];
237 } else {
238 ALOGE("Keystore: Failed to retrieve permission label.\n");
239 abort();
240 }
241}
242
Kenny Root655b9582013-04-04 08:37:42 -0700243/**
244 * Returns the app ID (in the Android multi-user sense) for the current
245 * UNIX UID.
246 */
247static uid_t get_app_id(uid_t uid) {
248 return uid % AID_USER;
249}
250
251/**
252 * Returns the user ID (in the Android multi-user sense) for the current
253 * UNIX UID.
254 */
255static uid_t get_user_id(uid_t uid) {
256 return uid / AID_USER;
257}
258
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700259static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700260 if (!ks_is_selinux_enabled) {
261 return true;
262 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000263
Riley Spahneaabae92014-06-30 12:39:52 -0700264 char *sctx = NULL;
265 const char *selinux_class = "keystore_key";
266 const char *str_perm = get_perm_label(perm);
267
268 if (!str_perm) {
269 return false;
270 }
271
272 if (getpidcon(spid, &sctx) != 0) {
273 ALOGE("SELinux: Failed to get source pid context.\n");
274 return false;
275 }
276
277 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
278 NULL) == 0;
279 freecon(sctx);
280 return allowed;
281}
282
283static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700284 // All system users are equivalent for multi-user support.
285 if (get_app_id(uid) == AID_SYSTEM) {
286 uid = AID_SYSTEM;
287 }
288
Kenny Root07438c82012-11-02 15:41:02 -0700289 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
290 struct user_perm user = user_perms[i];
291 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700292 return (user.perms & perm) &&
293 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700294 }
295 }
296
Riley Spahneaabae92014-06-30 12:39:52 -0700297 return (DEFAULT_PERMS & perm) &&
298 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700299}
300
Kenny Root49468902013-03-19 13:41:33 -0700301/**
302 * Returns the UID that the callingUid should act as. This is here for
303 * legacy support of the WiFi and VPN systems and should be removed
304 * when WiFi can operate in its own namespace.
305 */
Kenny Root07438c82012-11-02 15:41:02 -0700306static uid_t get_keystore_euid(uid_t uid) {
307 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
308 struct user_euid user = user_euids[i];
309 if (user.uid == uid) {
310 return user.euid;
311 }
312 }
313
314 return uid;
315}
316
Kenny Root49468902013-03-19 13:41:33 -0700317/**
318 * Returns true if the callingUid is allowed to interact in the targetUid's
319 * namespace.
320 */
321static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700322 if (callingUid == targetUid) {
323 return true;
324 }
Kenny Root49468902013-03-19 13:41:33 -0700325 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
326 struct user_euid user = user_euids[i];
327 if (user.euid == callingUid && user.uid == targetUid) {
328 return true;
329 }
330 }
331
332 return false;
333}
334
Kenny Roota91203b2012-02-15 15:00:46 -0800335/* Here is the encoding of keys. This is necessary in order to allow arbitrary
336 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
337 * into two bytes. The first byte is one of [+-.] which represents the first
338 * two bits of the character. The second byte encodes the rest of the bits into
339 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
340 * that Base64 cannot be used here due to the need of prefix match on keys. */
341
Kenny Root655b9582013-04-04 08:37:42 -0700342static size_t encode_key_length(const android::String8& keyName) {
343 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
344 size_t length = keyName.length();
345 for (int i = length; i > 0; --i, ++in) {
346 if (*in < '0' || *in > '~') {
347 ++length;
348 }
349 }
350 return length;
351}
352
Kenny Root07438c82012-11-02 15:41:02 -0700353static int encode_key(char* out, const android::String8& keyName) {
354 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
355 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800356 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700357 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800358 *out = '+' + (*in >> 6);
359 *++out = '0' + (*in & 0x3F);
360 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700361 } else {
362 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800363 }
364 }
365 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800366 return length;
367}
368
Kenny Root07438c82012-11-02 15:41:02 -0700369/*
370 * Converts from the "escaped" format on disk to actual name.
371 * This will be smaller than the input string.
372 *
373 * Characters that should combine with the next at the end will be truncated.
374 */
375static size_t decode_key_length(const char* in, size_t length) {
376 size_t outLength = 0;
377
378 for (const char* end = in + length; in < end; in++) {
379 /* This combines with the next character. */
380 if (*in < '0' || *in > '~') {
381 continue;
382 }
383
384 outLength++;
385 }
386 return outLength;
387}
388
389static void decode_key(char* out, const char* in, size_t length) {
390 for (const char* end = in + length; in < end; in++) {
391 if (*in < '0' || *in > '~') {
392 /* Truncate combining characters at the end. */
393 if (in + 1 >= end) {
394 break;
395 }
396
397 *out = (*in++ - '+') << 6;
398 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800399 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700400 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800401 }
402 }
403 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800404}
405
406static size_t readFully(int fd, uint8_t* data, size_t size) {
407 size_t remaining = size;
408 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800409 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800410 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800411 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800412 }
413 data += n;
414 remaining -= n;
415 }
416 return size;
417}
418
419static size_t writeFully(int fd, uint8_t* data, size_t size) {
420 size_t remaining = size;
421 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800422 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
423 if (n < 0) {
424 ALOGW("write failed: %s", strerror(errno));
425 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800426 }
427 data += n;
428 remaining -= n;
429 }
430 return size;
431}
432
433class Entropy {
434public:
435 Entropy() : mRandom(-1) {}
436 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800437 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800438 close(mRandom);
439 }
440 }
441
442 bool open() {
443 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800444 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
445 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800446 ALOGE("open: %s: %s", randomDevice, strerror(errno));
447 return false;
448 }
449 return true;
450 }
451
Kenny Root51878182012-03-13 12:53:19 -0700452 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800453 return (readFully(mRandom, data, size) == size);
454 }
455
456private:
457 int mRandom;
458};
459
460/* Here is the file format. There are two parts in blob.value, the secret and
461 * the description. The secret is stored in ciphertext, and its original size
462 * can be found in blob.length. The description is stored after the secret in
463 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700464 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700465 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800466 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
467 * and decryptBlob(). Thus they should not be accessed from outside. */
468
Kenny Root822c3a92012-03-23 16:34:39 -0700469/* ** Note to future implementors of encryption: **
470 * Currently this is the construction:
471 * metadata || Enc(MD5(data) || data)
472 *
473 * This should be the construction used for encrypting if re-implementing:
474 *
475 * Derive independent keys for encryption and MAC:
476 * Kenc = AES_encrypt(masterKey, "Encrypt")
477 * Kmac = AES_encrypt(masterKey, "MAC")
478 *
479 * Store this:
480 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
481 * HMAC(Kmac, metadata || Enc(data))
482 */
Kenny Roota91203b2012-02-15 15:00:46 -0800483struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700484 uint8_t version;
485 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700486 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800487 uint8_t info;
488 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700489 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800490 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700491 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800492 int32_t length; // in network byte order when encrypted
493 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
494};
495
Kenny Root822c3a92012-03-23 16:34:39 -0700496typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700497 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700498 TYPE_GENERIC = 1,
499 TYPE_MASTER_KEY = 2,
500 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800501 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700502} BlobType;
503
Kenny Rootf9119d62013-04-03 09:22:15 -0700504static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700505
Kenny Roota91203b2012-02-15 15:00:46 -0800506class Blob {
507public:
Kenny Root07438c82012-11-02 15:41:02 -0700508 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
509 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800510 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800511 mBlob.length = valueLength;
512 memcpy(mBlob.value, value, valueLength);
513
514 mBlob.info = infoLength;
515 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700516
Kenny Root07438c82012-11-02 15:41:02 -0700517 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700518 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700519
Kenny Rootee8068b2013-10-07 09:49:15 -0700520 if (type == TYPE_MASTER_KEY) {
521 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
522 } else {
523 mBlob.flags = KEYSTORE_FLAG_NONE;
524 }
Kenny Roota91203b2012-02-15 15:00:46 -0800525 }
526
527 Blob(blob b) {
528 mBlob = b;
529 }
530
Alex Klyubin1773b442015-02-20 12:33:33 -0800531 Blob() {
532 memset(&mBlob, 0, sizeof(mBlob));
533 }
Kenny Roota91203b2012-02-15 15:00:46 -0800534
Kenny Root51878182012-03-13 12:53:19 -0700535 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800536 return mBlob.value;
537 }
538
Kenny Root51878182012-03-13 12:53:19 -0700539 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800540 return mBlob.length;
541 }
542
Kenny Root51878182012-03-13 12:53:19 -0700543 const uint8_t* getInfo() const {
544 return mBlob.value + mBlob.length;
545 }
546
547 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800548 return mBlob.info;
549 }
550
Kenny Root822c3a92012-03-23 16:34:39 -0700551 uint8_t getVersion() const {
552 return mBlob.version;
553 }
554
Kenny Rootf9119d62013-04-03 09:22:15 -0700555 bool isEncrypted() const {
556 if (mBlob.version < 2) {
557 return true;
558 }
559
560 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
561 }
562
563 void setEncrypted(bool encrypted) {
564 if (encrypted) {
565 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
566 } else {
567 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
568 }
569 }
570
Kenny Root17208e02013-09-04 13:56:03 -0700571 bool isFallback() const {
572 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
573 }
574
575 void setFallback(bool fallback) {
576 if (fallback) {
577 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
578 } else {
579 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
580 }
581 }
582
Kenny Root822c3a92012-03-23 16:34:39 -0700583 void setVersion(uint8_t version) {
584 mBlob.version = version;
585 }
586
587 BlobType getType() const {
588 return BlobType(mBlob.type);
589 }
590
591 void setType(BlobType type) {
592 mBlob.type = uint8_t(type);
593 }
594
Kenny Rootf9119d62013-04-03 09:22:15 -0700595 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
596 ALOGV("writing blob %s", filename);
597 if (isEncrypted()) {
598 if (state != STATE_NO_ERROR) {
599 ALOGD("couldn't insert encrypted blob while not unlocked");
600 return LOCKED;
601 }
602
603 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
604 ALOGW("Could not read random data for: %s", filename);
605 return SYSTEM_ERROR;
606 }
Kenny Roota91203b2012-02-15 15:00:46 -0800607 }
608
609 // data includes the value and the value's length
610 size_t dataLength = mBlob.length + sizeof(mBlob.length);
611 // pad data to the AES_BLOCK_SIZE
612 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
613 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
614 // encrypted data includes the digest value
615 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
616 // move info after space for padding
617 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
618 // zero padding area
619 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
620
621 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800622
Kenny Rootf9119d62013-04-03 09:22:15 -0700623 if (isEncrypted()) {
624 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800625
Kenny Rootf9119d62013-04-03 09:22:15 -0700626 uint8_t vector[AES_BLOCK_SIZE];
627 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
628 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
629 aes_key, vector, AES_ENCRYPT);
630 }
631
Kenny Roota91203b2012-02-15 15:00:46 -0800632 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
633 size_t fileLength = encryptedLength + headerLength + mBlob.info;
634
635 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800636 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
637 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
638 if (out < 0) {
639 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800640 return SYSTEM_ERROR;
641 }
642 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
643 if (close(out) != 0) {
644 return SYSTEM_ERROR;
645 }
646 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800647 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800648 unlink(tmpFileName);
649 return SYSTEM_ERROR;
650 }
Kenny Root150ca932012-11-14 14:29:02 -0800651 if (rename(tmpFileName, filename) == -1) {
652 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
653 return SYSTEM_ERROR;
654 }
655 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800656 }
657
Kenny Rootf9119d62013-04-03 09:22:15 -0700658 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
659 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800660 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
661 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800662 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
663 }
664 // fileLength may be less than sizeof(mBlob) since the in
665 // memory version has extra padding to tolerate rounding up to
666 // the AES_BLOCK_SIZE
667 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
668 if (close(in) != 0) {
669 return SYSTEM_ERROR;
670 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700671
672 if (isEncrypted() && (state != STATE_NO_ERROR)) {
673 return LOCKED;
674 }
675
Kenny Roota91203b2012-02-15 15:00:46 -0800676 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
677 if (fileLength < headerLength) {
678 return VALUE_CORRUPTED;
679 }
680
681 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700682 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800683 return VALUE_CORRUPTED;
684 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700685
686 ssize_t digestedLength;
687 if (isEncrypted()) {
688 if (encryptedLength % AES_BLOCK_SIZE != 0) {
689 return VALUE_CORRUPTED;
690 }
691
692 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
693 mBlob.vector, AES_DECRYPT);
694 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
695 uint8_t computedDigest[MD5_DIGEST_LENGTH];
696 MD5(mBlob.digested, digestedLength, computedDigest);
697 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
698 return VALUE_CORRUPTED;
699 }
700 } else {
701 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800702 }
703
704 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
705 mBlob.length = ntohl(mBlob.length);
706 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
707 return VALUE_CORRUPTED;
708 }
709 if (mBlob.info != 0) {
710 // move info from after padding to after data
711 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
712 }
Kenny Root07438c82012-11-02 15:41:02 -0700713 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800714 }
715
716private:
717 struct blob mBlob;
718};
719
Kenny Root655b9582013-04-04 08:37:42 -0700720class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800721public:
Kenny Root655b9582013-04-04 08:37:42 -0700722 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
723 asprintf(&mUserDir, "user_%u", mUserId);
724 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
725 }
726
727 ~UserState() {
728 free(mUserDir);
729 free(mMasterKeyFile);
730 }
731
732 bool initialize() {
733 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
734 ALOGE("Could not create directory '%s'", mUserDir);
735 return false;
736 }
737
738 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800739 setState(STATE_LOCKED);
740 } else {
741 setState(STATE_UNINITIALIZED);
742 }
Kenny Root70e3a862012-02-15 17:20:23 -0800743
Kenny Root655b9582013-04-04 08:37:42 -0700744 return true;
745 }
746
747 uid_t getUserId() const {
748 return mUserId;
749 }
750
751 const char* getUserDirName() const {
752 return mUserDir;
753 }
754
755 const char* getMasterKeyFileName() const {
756 return mMasterKeyFile;
757 }
758
759 void setState(State state) {
760 mState = state;
761 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
762 mRetry = MAX_RETRY;
763 }
Kenny Roota91203b2012-02-15 15:00:46 -0800764 }
765
Kenny Root51878182012-03-13 12:53:19 -0700766 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800767 return mState;
768 }
769
Kenny Root51878182012-03-13 12:53:19 -0700770 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800771 return mRetry;
772 }
773
Kenny Root655b9582013-04-04 08:37:42 -0700774 void zeroizeMasterKeysInMemory() {
775 memset(mMasterKey, 0, sizeof(mMasterKey));
776 memset(mSalt, 0, sizeof(mSalt));
777 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
778 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800779 }
780
Chad Brubaker96d6d782015-05-07 10:19:40 -0700781 bool deleteMasterKey() {
782 setState(STATE_UNINITIALIZED);
783 zeroizeMasterKeysInMemory();
784 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
785 }
786
Kenny Root655b9582013-04-04 08:37:42 -0700787 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
788 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800789 return SYSTEM_ERROR;
790 }
Kenny Root655b9582013-04-04 08:37:42 -0700791 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800792 if (response != NO_ERROR) {
793 return response;
794 }
795 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700796 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800797 }
798
Robin Lee4e865752014-08-19 17:37:55 +0100799 ResponseCode copyMasterKey(UserState* src) {
800 if (mState != STATE_UNINITIALIZED) {
801 return ::SYSTEM_ERROR;
802 }
803 if (src->getState() != STATE_NO_ERROR) {
804 return ::SYSTEM_ERROR;
805 }
806 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
807 setupMasterKeys();
808 return ::NO_ERROR;
809 }
810
Kenny Root655b9582013-04-04 08:37:42 -0700811 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800812 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
813 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
814 AES_KEY passwordAesKey;
815 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700816 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700817 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800818 }
819
Kenny Root655b9582013-04-04 08:37:42 -0700820 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
821 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800822 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800823 return SYSTEM_ERROR;
824 }
825
826 // we read the raw blob to just to get the salt to generate
827 // the AES key, then we create the Blob to use with decryptBlob
828 blob rawBlob;
829 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
830 if (close(in) != 0) {
831 return SYSTEM_ERROR;
832 }
833 // find salt at EOF if present, otherwise we have an old file
834 uint8_t* salt;
835 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
836 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
837 } else {
838 salt = NULL;
839 }
840 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
841 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
842 AES_KEY passwordAesKey;
843 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
844 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700845 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
846 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800847 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700848 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800849 }
850 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
851 // if salt was missing, generate one and write a new master key file with the salt.
852 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700853 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800854 return SYSTEM_ERROR;
855 }
Kenny Root655b9582013-04-04 08:37:42 -0700856 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800857 }
858 if (response == NO_ERROR) {
859 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
860 setupMasterKeys();
861 }
862 return response;
863 }
864 if (mRetry <= 0) {
865 reset();
866 return UNINITIALIZED;
867 }
868 --mRetry;
869 switch (mRetry) {
870 case 0: return WRONG_PASSWORD_0;
871 case 1: return WRONG_PASSWORD_1;
872 case 2: return WRONG_PASSWORD_2;
873 case 3: return WRONG_PASSWORD_3;
874 default: return WRONG_PASSWORD_3;
875 }
876 }
877
Kenny Root655b9582013-04-04 08:37:42 -0700878 AES_KEY* getEncryptionKey() {
879 return &mMasterKeyEncryption;
880 }
881
882 AES_KEY* getDecryptionKey() {
883 return &mMasterKeyDecryption;
884 }
885
Kenny Roota91203b2012-02-15 15:00:46 -0800886 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700887 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800888 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700889 // If the directory doesn't exist then nothing to do.
890 if (errno == ENOENT) {
891 return true;
892 }
Kenny Root655b9582013-04-04 08:37:42 -0700893 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800894 return false;
895 }
Kenny Root655b9582013-04-04 08:37:42 -0700896
897 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800898 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700899 // skip . and ..
900 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700901 continue;
902 }
903
904 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800905 }
906 closedir(dir);
907 return true;
908 }
909
Kenny Root655b9582013-04-04 08:37:42 -0700910private:
911 static const int MASTER_KEY_SIZE_BYTES = 16;
912 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
913
914 static const int MAX_RETRY = 4;
915 static const size_t SALT_SIZE = 16;
916
917 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
918 uint8_t* salt) {
919 size_t saltSize;
920 if (salt != NULL) {
921 saltSize = SALT_SIZE;
922 } else {
923 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
924 salt = (uint8_t*) "keystore";
925 // sizeof = 9, not strlen = 8
926 saltSize = sizeof("keystore");
927 }
928
929 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
930 saltSize, 8192, keySize, key);
931 }
932
933 bool generateSalt(Entropy* entropy) {
934 return entropy->generate_random_data(mSalt, sizeof(mSalt));
935 }
936
937 bool generateMasterKey(Entropy* entropy) {
938 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
939 return false;
940 }
941 if (!generateSalt(entropy)) {
942 return false;
943 }
944 return true;
945 }
946
947 void setupMasterKeys() {
948 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
949 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
950 setState(STATE_NO_ERROR);
951 }
952
953 uid_t mUserId;
954
955 char* mUserDir;
956 char* mMasterKeyFile;
957
958 State mState;
959 int8_t mRetry;
960
961 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
962 uint8_t mSalt[SALT_SIZE];
963
964 AES_KEY mMasterKeyEncryption;
965 AES_KEY mMasterKeyDecryption;
966};
967
968typedef struct {
969 uint32_t uid;
970 const uint8_t* filename;
971} grant_t;
972
973class KeyStore {
974public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000975 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700976 : mEntropy(entropy)
977 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800978 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700979 {
980 memset(&mMetaData, '\0', sizeof(mMetaData));
981 }
982
983 ~KeyStore() {
984 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
985 it != mGrants.end(); it++) {
986 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700987 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800988 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700989
990 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
991 it != mMasterKeys.end(); it++) {
992 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700993 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800994 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700995 }
996
Chad Brubaker67d2a502015-03-11 17:21:18 +0000997 /**
998 * Depending on the hardware keymaster version is this may return a
999 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1000 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1001 * be guarded by a check on the device's version.
1002 */
1003 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001004 return mDevice;
1005 }
1006
Chad Brubaker67d2a502015-03-11 17:21:18 +00001007 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001008 return mFallbackDevice;
1009 }
1010
Chad Brubaker67d2a502015-03-11 17:21:18 +00001011 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001012 return blob.isFallback() ? mFallbackDevice: mDevice;
1013 }
1014
Kenny Root655b9582013-04-04 08:37:42 -07001015 ResponseCode initialize() {
1016 readMetaData();
1017 if (upgradeKeystore()) {
1018 writeMetaData();
1019 }
1020
1021 return ::NO_ERROR;
1022 }
1023
Chad Brubaker72593ee2015-05-12 10:42:00 -07001024 State getState(uid_t userId) {
1025 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001026 }
1027
Chad Brubaker72593ee2015-05-12 10:42:00 -07001028 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1029 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001030 return userState->initialize(pw, mEntropy);
1031 }
1032
Chad Brubaker72593ee2015-05-12 10:42:00 -07001033 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1034 UserState *userState = getUserState(dstUser);
1035 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001036 return userState->copyMasterKey(initState);
1037 }
1038
Chad Brubaker72593ee2015-05-12 10:42:00 -07001039 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1040 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001041 return userState->writeMasterKey(pw, mEntropy);
1042 }
1043
Chad Brubaker72593ee2015-05-12 10:42:00 -07001044 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1045 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001046 return userState->readMasterKey(pw, mEntropy);
1047 }
1048
1049 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001050 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001051 encode_key(encoded, keyName);
1052 return android::String8(encoded);
1053 }
1054
1055 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001056 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001057 encode_key(encoded, keyName);
1058 return android::String8::format("%u_%s", uid, encoded);
1059 }
1060
1061 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001062 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001063 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001064 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001065 encoded);
1066 }
1067
Chad Brubaker96d6d782015-05-07 10:19:40 -07001068 /*
1069 * Delete entries owned by userId. If keepUnencryptedEntries is true
1070 * then only encrypted entries will be removed, otherwise all entries will
1071 * be removed.
1072 */
1073 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001074 android::String8 prefix("");
1075 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001076 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001077 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001078 return;
1079 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001080 for (uint32_t i = 0; i < aliases.size(); i++) {
1081 android::String8 filename(aliases[i]);
1082 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001083 getKeyName(filename).string());
1084 bool shouldDelete = true;
1085 if (keepUnenryptedEntries) {
1086 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001087 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001088
Chad Brubaker96d6d782015-05-07 10:19:40 -07001089 /* get can fail if the blob is encrypted and the state is
1090 * not unlocked, only skip deleting blobs that were loaded and
1091 * who are not encrypted. If there are blobs we fail to read for
1092 * other reasons err on the safe side and delete them since we
1093 * can't tell if they're encrypted.
1094 */
1095 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1096 }
1097 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001098 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001099 }
1100 }
1101 if (!userState->deleteMasterKey()) {
1102 ALOGE("Failed to delete user %d's master key", userId);
1103 }
1104 if (!keepUnenryptedEntries) {
1105 if(!userState->reset()) {
1106 ALOGE("Failed to remove user %d's directory", userId);
1107 }
1108 }
Kenny Root655b9582013-04-04 08:37:42 -07001109 }
1110
Chad Brubaker72593ee2015-05-12 10:42:00 -07001111 bool isEmpty(uid_t userId) const {
1112 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001113 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001114 return true;
1115 }
1116
1117 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001118 if (!dir) {
1119 return true;
1120 }
Kenny Root31e27462014-09-10 11:28:03 -07001121
Kenny Roota91203b2012-02-15 15:00:46 -08001122 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001123 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001124 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001125 // We only care about files.
1126 if (file->d_type != DT_REG) {
1127 continue;
1128 }
1129
1130 // Skip anything that starts with a "."
1131 if (file->d_name[0] == '.') {
1132 continue;
1133 }
1134
Kenny Root31e27462014-09-10 11:28:03 -07001135 result = false;
1136 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001137 }
1138 closedir(dir);
1139 return result;
1140 }
1141
Chad Brubaker72593ee2015-05-12 10:42:00 -07001142 void lock(uid_t userId) {
1143 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001144 userState->zeroizeMasterKeysInMemory();
1145 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001146 }
1147
Chad Brubaker72593ee2015-05-12 10:42:00 -07001148 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1149 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001150 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1151 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001152 if (rc != NO_ERROR) {
1153 return rc;
1154 }
1155
1156 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001157 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001158 /* If we upgrade the key, we need to write it to disk again. Then
1159 * it must be read it again since the blob is encrypted each time
1160 * it's written.
1161 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001162 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1163 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001164 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1165 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001166 return rc;
1167 }
1168 }
Kenny Root822c3a92012-03-23 16:34:39 -07001169 }
1170
Kenny Root17208e02013-09-04 13:56:03 -07001171 /*
1172 * This will upgrade software-backed keys to hardware-backed keys when
1173 * the HAL for the device supports the newer key types.
1174 */
1175 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1176 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1177 && keyBlob->isFallback()) {
1178 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001179 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001180
1181 // The HAL allowed the import, reget the key to have the "fresh"
1182 // version.
1183 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001184 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001185 }
1186 }
1187
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001188 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1189 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001190 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001191 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001192 }
1193
Kenny Rootd53bc922013-03-21 14:10:15 -07001194 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001195 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1196 return KEY_NOT_FOUND;
1197 }
1198
1199 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001200 }
1201
Chad Brubaker72593ee2015-05-12 10:42:00 -07001202 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1203 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001204 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1205 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001206 }
1207
Chad Brubaker72593ee2015-05-12 10:42:00 -07001208 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001209 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001210 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001211 if (rc != ::NO_ERROR) {
1212 return rc;
1213 }
1214
1215 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1216 // A device doesn't have to implement delete_keypair.
1217 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1218 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1219 rc = ::SYSTEM_ERROR;
1220 }
1221 }
1222 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001223 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1224 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1225 if (dev->delete_key) {
1226 keymaster_key_blob_t blob;
1227 blob.key_material = keyBlob.getValue();
1228 blob.key_material_size = keyBlob.getLength();
1229 dev->delete_key(dev, &blob);
1230 }
1231 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001232 if (rc != ::NO_ERROR) {
1233 return rc;
1234 }
1235
1236 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1237 }
1238
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001239 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001240 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001241
Chad Brubaker72593ee2015-05-12 10:42:00 -07001242 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001243 size_t n = prefix.length();
1244
1245 DIR* dir = opendir(userState->getUserDirName());
1246 if (!dir) {
1247 ALOGW("can't open directory for user: %s", strerror(errno));
1248 return ::SYSTEM_ERROR;
1249 }
1250
1251 struct dirent* file;
1252 while ((file = readdir(dir)) != NULL) {
1253 // We only care about files.
1254 if (file->d_type != DT_REG) {
1255 continue;
1256 }
1257
1258 // Skip anything that starts with a "."
1259 if (file->d_name[0] == '.') {
1260 continue;
1261 }
1262
1263 if (!strncmp(prefix.string(), file->d_name, n)) {
1264 const char* p = &file->d_name[n];
1265 size_t plen = strlen(p);
1266
1267 size_t extra = decode_key_length(p, plen);
1268 char *match = (char*) malloc(extra + 1);
1269 if (match != NULL) {
1270 decode_key(match, p, plen);
1271 matches->push(android::String16(match, extra));
1272 free(match);
1273 } else {
1274 ALOGW("could not allocate match of size %zd", extra);
1275 }
1276 }
1277 }
1278 closedir(dir);
1279 return ::NO_ERROR;
1280 }
1281
Kenny Root07438c82012-11-02 15:41:02 -07001282 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001283 const grant_t* existing = getGrant(filename, granteeUid);
1284 if (existing == NULL) {
1285 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001286 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001287 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001288 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001289 }
1290 }
1291
Kenny Root07438c82012-11-02 15:41:02 -07001292 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001293 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1294 it != mGrants.end(); it++) {
1295 grant_t* grant = *it;
1296 if (grant->uid == granteeUid
1297 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1298 mGrants.erase(it);
1299 return true;
1300 }
Kenny Root70e3a862012-02-15 17:20:23 -08001301 }
Kenny Root70e3a862012-02-15 17:20:23 -08001302 return false;
1303 }
1304
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001305 bool hasGrant(const char* filename, const uid_t uid) const {
1306 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001307 }
1308
Chad Brubaker72593ee2015-05-12 10:42:00 -07001309 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001310 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001311 uint8_t* data;
1312 size_t dataLength;
1313 int rc;
1314
1315 if (mDevice->import_keypair == NULL) {
1316 ALOGE("Keymaster doesn't support import!");
1317 return SYSTEM_ERROR;
1318 }
1319
Kenny Root17208e02013-09-04 13:56:03 -07001320 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001321 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001322 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001323 /*
1324 * Maybe the device doesn't support this type of key. Try to use the
1325 * software fallback keymaster implementation. This is a little bit
1326 * lazier than checking the PKCS#8 key type, but the software
1327 * implementation will do that anyway.
1328 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001329 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001330 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001331
1332 if (rc) {
1333 ALOGE("Error while importing keypair: %d", rc);
1334 return SYSTEM_ERROR;
1335 }
Kenny Root822c3a92012-03-23 16:34:39 -07001336 }
1337
1338 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1339 free(data);
1340
Kenny Rootf9119d62013-04-03 09:22:15 -07001341 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001342 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001343
Chad Brubaker72593ee2015-05-12 10:42:00 -07001344 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001345 }
1346
Kenny Root1b0e3932013-09-05 13:06:32 -07001347 bool isHardwareBacked(const android::String16& keyType) const {
1348 if (mDevice == NULL) {
1349 ALOGW("can't get keymaster device");
1350 return false;
1351 }
1352
1353 if (sRSAKeyType == keyType) {
1354 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1355 } else {
1356 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1357 && (mDevice->common.module->module_api_version
1358 >= KEYMASTER_MODULE_API_VERSION_0_2);
1359 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001360 }
1361
Kenny Root655b9582013-04-04 08:37:42 -07001362 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1363 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001364 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001365 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001366
Chad Brubaker72593ee2015-05-12 10:42:00 -07001367 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001368 if (responseCode == NO_ERROR) {
1369 return responseCode;
1370 }
1371
1372 // If this is one of the legacy UID->UID mappings, use it.
1373 uid_t euid = get_keystore_euid(uid);
1374 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001375 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001376 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001377 if (responseCode == NO_ERROR) {
1378 return responseCode;
1379 }
1380 }
1381
1382 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001383 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001384 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001385 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001386 if (end[0] != '_' || end[1] == 0) {
1387 return KEY_NOT_FOUND;
1388 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001389 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001390 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001391 if (!hasGrant(filepath8.string(), uid)) {
1392 return responseCode;
1393 }
1394
1395 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001396 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001397 }
1398
1399 /**
1400 * Returns any existing UserState or creates it if it doesn't exist.
1401 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001402 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001403 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1404 it != mMasterKeys.end(); it++) {
1405 UserState* state = *it;
1406 if (state->getUserId() == userId) {
1407 return state;
1408 }
1409 }
1410
1411 UserState* userState = new UserState(userId);
1412 if (!userState->initialize()) {
1413 /* There's not much we can do if initialization fails. Trying to
1414 * unlock the keystore for that user will fail as well, so any
1415 * subsequent request for this user will just return SYSTEM_ERROR.
1416 */
1417 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1418 }
1419 mMasterKeys.add(userState);
1420 return userState;
1421 }
1422
1423 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001424 * Returns any existing UserState or creates it if it doesn't exist.
1425 */
1426 UserState* getUserStateByUid(uid_t uid) {
1427 uid_t userId = get_user_id(uid);
1428 return getUserState(userId);
1429 }
1430
1431 /**
Kenny Root655b9582013-04-04 08:37:42 -07001432 * Returns NULL if the UserState doesn't already exist.
1433 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001434 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001435 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1436 it != mMasterKeys.end(); it++) {
1437 UserState* state = *it;
1438 if (state->getUserId() == userId) {
1439 return state;
1440 }
1441 }
1442
1443 return NULL;
1444 }
1445
Chad Brubaker72593ee2015-05-12 10:42:00 -07001446 /**
1447 * Returns NULL if the UserState doesn't already exist.
1448 */
1449 const UserState* getUserStateByUid(uid_t uid) const {
1450 uid_t userId = get_user_id(uid);
1451 return getUserState(userId);
1452 }
1453
Kenny Roota91203b2012-02-15 15:00:46 -08001454private:
Kenny Root655b9582013-04-04 08:37:42 -07001455 static const char* sOldMasterKey;
1456 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001457 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001458 Entropy* mEntropy;
1459
Chad Brubaker67d2a502015-03-11 17:21:18 +00001460 keymaster1_device_t* mDevice;
1461 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001462
Kenny Root655b9582013-04-04 08:37:42 -07001463 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001464
Kenny Root655b9582013-04-04 08:37:42 -07001465 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001466
Kenny Root655b9582013-04-04 08:37:42 -07001467 typedef struct {
1468 uint32_t version;
1469 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001470
Kenny Root655b9582013-04-04 08:37:42 -07001471 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001472
Kenny Root655b9582013-04-04 08:37:42 -07001473 const grant_t* getGrant(const char* filename, uid_t uid) const {
1474 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1475 it != mGrants.end(); it++) {
1476 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001477 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001478 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001479 return grant;
1480 }
1481 }
Kenny Root70e3a862012-02-15 17:20:23 -08001482 return NULL;
1483 }
1484
Kenny Root822c3a92012-03-23 16:34:39 -07001485 /**
1486 * Upgrade code. This will upgrade the key from the current version
1487 * to whatever is newest.
1488 */
Kenny Root655b9582013-04-04 08:37:42 -07001489 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1490 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001491 bool updated = false;
1492 uint8_t version = oldVersion;
1493
1494 /* From V0 -> V1: All old types were unknown */
1495 if (version == 0) {
1496 ALOGV("upgrading to version 1 and setting type %d", type);
1497
1498 blob->setType(type);
1499 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001500 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001501 }
1502 version = 1;
1503 updated = true;
1504 }
1505
Kenny Rootf9119d62013-04-03 09:22:15 -07001506 /* From V1 -> V2: All old keys were encrypted */
1507 if (version == 1) {
1508 ALOGV("upgrading to version 2");
1509
1510 blob->setEncrypted(true);
1511 version = 2;
1512 updated = true;
1513 }
1514
Kenny Root822c3a92012-03-23 16:34:39 -07001515 /*
1516 * If we've updated, set the key blob to the right version
1517 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001518 */
Kenny Root822c3a92012-03-23 16:34:39 -07001519 if (updated) {
1520 ALOGV("updated and writing file %s", filename);
1521 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001522 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001523
1524 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001525 }
1526
1527 /**
1528 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1529 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1530 * Then it overwrites the original blob with the new blob
1531 * format that is returned from the keymaster.
1532 */
Kenny Root655b9582013-04-04 08:37:42 -07001533 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001534 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1535 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1536 if (b.get() == NULL) {
1537 ALOGE("Problem instantiating BIO");
1538 return SYSTEM_ERROR;
1539 }
1540
1541 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1542 if (pkey.get() == NULL) {
1543 ALOGE("Couldn't read old PEM file");
1544 return SYSTEM_ERROR;
1545 }
1546
1547 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1548 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1549 if (len < 0) {
1550 ALOGE("Couldn't measure PKCS#8 length");
1551 return SYSTEM_ERROR;
1552 }
1553
Kenny Root70c98892013-02-07 09:10:36 -08001554 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1555 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001556 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1557 ALOGE("Couldn't convert to PKCS#8");
1558 return SYSTEM_ERROR;
1559 }
1560
Chad Brubaker72593ee2015-05-12 10:42:00 -07001561 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001562 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001563 if (rc != NO_ERROR) {
1564 return rc;
1565 }
1566
Kenny Root655b9582013-04-04 08:37:42 -07001567 return get(filename, blob, TYPE_KEY_PAIR, uid);
1568 }
1569
1570 void readMetaData() {
1571 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1572 if (in < 0) {
1573 return;
1574 }
1575 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1576 if (fileLength != sizeof(mMetaData)) {
1577 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1578 sizeof(mMetaData));
1579 }
1580 close(in);
1581 }
1582
1583 void writeMetaData() {
1584 const char* tmpFileName = ".metadata.tmp";
1585 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1586 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1587 if (out < 0) {
1588 ALOGE("couldn't write metadata file: %s", strerror(errno));
1589 return;
1590 }
1591 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1592 if (fileLength != sizeof(mMetaData)) {
1593 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1594 sizeof(mMetaData));
1595 }
1596 close(out);
1597 rename(tmpFileName, sMetaDataFile);
1598 }
1599
1600 bool upgradeKeystore() {
1601 bool upgraded = false;
1602
1603 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001604 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001605
1606 // Initialize first so the directory is made.
1607 userState->initialize();
1608
1609 // Migrate the old .masterkey file to user 0.
1610 if (access(sOldMasterKey, R_OK) == 0) {
1611 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1612 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1613 return false;
1614 }
1615 }
1616
1617 // Initialize again in case we had a key.
1618 userState->initialize();
1619
1620 // Try to migrate existing keys.
1621 DIR* dir = opendir(".");
1622 if (!dir) {
1623 // Give up now; maybe we can upgrade later.
1624 ALOGE("couldn't open keystore's directory; something is wrong");
1625 return false;
1626 }
1627
1628 struct dirent* file;
1629 while ((file = readdir(dir)) != NULL) {
1630 // We only care about files.
1631 if (file->d_type != DT_REG) {
1632 continue;
1633 }
1634
1635 // Skip anything that starts with a "."
1636 if (file->d_name[0] == '.') {
1637 continue;
1638 }
1639
1640 // Find the current file's user.
1641 char* end;
1642 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1643 if (end[0] != '_' || end[1] == 0) {
1644 continue;
1645 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001646 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001647 if (otherUser->getUserId() != 0) {
1648 unlinkat(dirfd(dir), file->d_name, 0);
1649 }
1650
1651 // Rename the file into user directory.
1652 DIR* otherdir = opendir(otherUser->getUserDirName());
1653 if (otherdir == NULL) {
1654 ALOGW("couldn't open user directory for rename");
1655 continue;
1656 }
1657 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1658 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1659 }
1660 closedir(otherdir);
1661 }
1662 closedir(dir);
1663
1664 mMetaData.version = 1;
1665 upgraded = true;
1666 }
1667
1668 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001669 }
Kenny Roota91203b2012-02-15 15:00:46 -08001670};
1671
Kenny Root655b9582013-04-04 08:37:42 -07001672const char* KeyStore::sOldMasterKey = ".masterkey";
1673const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001674
Kenny Root1b0e3932013-09-05 13:06:32 -07001675const android::String16 KeyStore::sRSAKeyType("RSA");
1676
Kenny Root07438c82012-11-02 15:41:02 -07001677namespace android {
1678class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1679public:
1680 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001681 : mKeyStore(keyStore),
1682 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001683 {
Kenny Roota91203b2012-02-15 15:00:46 -08001684 }
Kenny Roota91203b2012-02-15 15:00:46 -08001685
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001686 void binderDied(const wp<IBinder>& who) {
1687 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1688 for (auto token: operations) {
1689 abort(token);
1690 }
Kenny Root822c3a92012-03-23 16:34:39 -07001691 }
Kenny Roota91203b2012-02-15 15:00:46 -08001692
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001693 int32_t getState(int32_t userId) {
1694 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001695 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001696 }
Kenny Roota91203b2012-02-15 15:00:46 -08001697
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001698 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001699 }
1700
Kenny Root07438c82012-11-02 15:41:02 -07001701 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001702 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001703 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001704 }
Kenny Root07438c82012-11-02 15:41:02 -07001705
Chad Brubaker9489b792015-04-14 11:01:45 -07001706 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001707 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001708 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001709
Kenny Root655b9582013-04-04 08:37:42 -07001710 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001711 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001712 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001713 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001714 *item = NULL;
1715 *itemLength = 0;
1716 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001717 }
Kenny Roota91203b2012-02-15 15:00:46 -08001718
Kenny Root07438c82012-11-02 15:41:02 -07001719 *item = (uint8_t*) malloc(keyBlob.getLength());
1720 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1721 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001722
Kenny Root07438c82012-11-02 15:41:02 -07001723 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001724 }
1725
Kenny Rootf9119d62013-04-03 09:22:15 -07001726 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1727 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001728 targetUid = getEffectiveUid(targetUid);
1729 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1730 flags & KEYSTORE_FLAG_ENCRYPTED);
1731 if (result != ::NO_ERROR) {
1732 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001733 }
1734
Kenny Root07438c82012-11-02 15:41:02 -07001735 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001736 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001737
1738 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001739 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1740
Chad Brubaker72593ee2015-05-12 10:42:00 -07001741 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001742 }
1743
Kenny Root49468902013-03-19 13:41:33 -07001744 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001745 targetUid = getEffectiveUid(targetUid);
1746 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001747 return ::PERMISSION_DENIED;
1748 }
Kenny Root07438c82012-11-02 15:41:02 -07001749 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001750 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001751 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001752 }
1753
Kenny Root49468902013-03-19 13:41:33 -07001754 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001755 targetUid = getEffectiveUid(targetUid);
1756 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001757 return ::PERMISSION_DENIED;
1758 }
1759
Kenny Root07438c82012-11-02 15:41:02 -07001760 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001761 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001762
Kenny Root655b9582013-04-04 08:37:42 -07001763 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001764 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1765 }
1766 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001767 }
1768
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001769 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001770 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001771 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001772 return ::PERMISSION_DENIED;
1773 }
Kenny Root07438c82012-11-02 15:41:02 -07001774 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001775 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001776
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001777 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001778 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001779 }
Kenny Root07438c82012-11-02 15:41:02 -07001780 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001781 }
1782
Kenny Root07438c82012-11-02 15:41:02 -07001783 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001784 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001785 return ::PERMISSION_DENIED;
1786 }
1787
Chad Brubaker9489b792015-04-14 11:01:45 -07001788 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001789 mKeyStore->resetUser(get_user_id(callingUid), false);
1790 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001791 }
1792
Chad Brubaker96d6d782015-05-07 10:19:40 -07001793 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001794 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001795 return ::PERMISSION_DENIED;
1796 }
Kenny Root70e3a862012-02-15 17:20:23 -08001797
Kenny Root07438c82012-11-02 15:41:02 -07001798 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001799 // Flush the auth token table to prevent stale tokens from sticking
1800 // around.
1801 mAuthTokenTable.Clear();
1802
1803 if (password.size() == 0) {
1804 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001805 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001806 return ::NO_ERROR;
1807 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001808 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001809 case ::STATE_UNINITIALIZED: {
1810 // generate master key, encrypt with password, write to file,
1811 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001812 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001813 }
1814 case ::STATE_NO_ERROR: {
1815 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001816 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001817 }
1818 case ::STATE_LOCKED: {
1819 ALOGE("Changing user %d's password while locked, clearing old encryption",
1820 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001821 mKeyStore->resetUser(userId, true);
1822 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001823 }
Kenny Root07438c82012-11-02 15:41:02 -07001824 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001825 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001826 }
Kenny Root70e3a862012-02-15 17:20:23 -08001827 }
1828
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001829 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1830 if (!checkBinderPermission(P_USER_CHANGED)) {
1831 return ::PERMISSION_DENIED;
1832 }
1833
1834 // Sanity check that the new user has an empty keystore.
1835 if (!mKeyStore->isEmpty(userId)) {
1836 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1837 }
1838 // Unconditionally clear the keystore, just to be safe.
1839 mKeyStore->resetUser(userId, false);
1840
1841 // If the user has a parent user then use the parent's
1842 // masterkey/password, otherwise there's nothing to do.
1843 if (parentId != -1) {
1844 return mKeyStore->copyMasterKey(parentId, userId);
1845 } else {
1846 return ::NO_ERROR;
1847 }
1848 }
1849
1850 int32_t onUserRemoved(int32_t userId) {
1851 if (!checkBinderPermission(P_USER_CHANGED)) {
1852 return ::PERMISSION_DENIED;
1853 }
1854
1855 mKeyStore->resetUser(userId, false);
1856 return ::NO_ERROR;
1857 }
1858
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001859 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001860 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001861 return ::PERMISSION_DENIED;
1862 }
Kenny Root70e3a862012-02-15 17:20:23 -08001863
Chad Brubaker72593ee2015-05-12 10:42:00 -07001864 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001865 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001866 ALOGD("calling lock in state: %d", state);
1867 return state;
1868 }
1869
Chad Brubaker72593ee2015-05-12 10:42:00 -07001870 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001871 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001872 }
1873
Chad Brubaker96d6d782015-05-07 10:19:40 -07001874 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001875 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001876 return ::PERMISSION_DENIED;
1877 }
1878
Chad Brubaker72593ee2015-05-12 10:42:00 -07001879 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001880 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001881 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001882 return state;
1883 }
1884
1885 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001886 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001887 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001888 }
1889
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001890 bool isEmpty(int32_t userId) {
1891 if (!checkBinderPermission(P_IS_EMPTY)) {
1892 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001893 }
Kenny Root70e3a862012-02-15 17:20:23 -08001894
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001895 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001896 }
1897
Kenny Root96427ba2013-08-16 14:02:41 -07001898 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1899 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001900 targetUid = getEffectiveUid(targetUid);
1901 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1902 flags & KEYSTORE_FLAG_ENCRYPTED);
1903 if (result != ::NO_ERROR) {
1904 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001905 }
Kenny Root07438c82012-11-02 15:41:02 -07001906
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001907 KeymasterArguments params;
1908 addLegacyKeyAuthorizations(params.params);
Kenny Root07438c82012-11-02 15:41:02 -07001909
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001910 switch (keyType) {
1911 case EVP_PKEY_EC: {
1912 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
1913 if (keySize == -1) {
1914 keySize = EC_DEFAULT_KEY_SIZE;
1915 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1916 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07001917 return ::SYSTEM_ERROR;
1918 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001919 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1920 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001921 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001922 case EVP_PKEY_RSA: {
1923 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1924 if (keySize == -1) {
1925 keySize = RSA_DEFAULT_KEY_SIZE;
1926 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1927 ALOGI("invalid key size %d", keySize);
1928 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07001929 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001930 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1931 unsigned long exponent = RSA_DEFAULT_EXPONENT;
1932 if (args->size() > 1) {
1933 ALOGI("invalid number of arguments: %zu", args->size());
1934 return ::SYSTEM_ERROR;
1935 } else if (args->size() == 1) {
1936 sp<KeystoreArg> expArg = args->itemAt(0);
1937 if (expArg != NULL) {
1938 Unique_BIGNUM pubExpBn(
1939 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
1940 expArg->size(), NULL));
1941 if (pubExpBn.get() == NULL) {
1942 ALOGI("Could not convert public exponent to BN");
1943 return ::SYSTEM_ERROR;
1944 }
1945 exponent = BN_get_word(pubExpBn.get());
1946 if (exponent == 0xFFFFFFFFL) {
1947 ALOGW("cannot represent public exponent as a long value");
1948 return ::SYSTEM_ERROR;
1949 }
1950 } else {
1951 ALOGW("public exponent not read");
1952 return ::SYSTEM_ERROR;
1953 }
1954 }
1955 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
1956 exponent));
1957 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001958 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001959 default: {
1960 ALOGW("Unsupported key type %d", keyType);
1961 return ::SYSTEM_ERROR;
1962 }
Kenny Root96427ba2013-08-16 14:02:41 -07001963 }
1964
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001965 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
1966 /*outCharacteristics*/ NULL);
1967 if (rc != ::NO_ERROR) {
1968 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07001969 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001970 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08001971 }
1972
Kenny Rootf9119d62013-04-03 09:22:15 -07001973 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1974 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001975 KeymasterArguments params;
1976 addLegacyKeyAuthorizations(params.params);
1977 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07001978
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001979 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
1980 if (!pkcs8.get()) {
1981 return ::SYSTEM_ERROR;
1982 }
1983 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1984 if (!pkey.get()) {
1985 return ::SYSTEM_ERROR;
1986 }
1987 int type = EVP_PKEY_type(pkey->type);
1988 switch (type) {
1989 case EVP_PKEY_RSA:
1990 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1991 break;
1992 case EVP_PKEY_EC:
1993 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1994 KM_ALGORITHM_EC));
1995 break;
1996 default:
1997 ALOGW("Unsupported key type %d", type);
1998 return ::SYSTEM_ERROR;
1999 }
2000 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2001 /*outCharacteristics*/ NULL);
2002 if (rc != ::NO_ERROR) {
2003 ALOGW("importKey failed: %d", rc);
2004 }
2005 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002006 }
2007
Kenny Root07438c82012-11-02 15:41:02 -07002008 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002009 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002010 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002011 return ::PERMISSION_DENIED;
2012 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002013 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002014 }
2015
Kenny Root07438c82012-11-02 15:41:02 -07002016 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2017 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002018 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002019 return ::PERMISSION_DENIED;
2020 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002021 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2022 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002023 }
Kenny Root07438c82012-11-02 15:41:02 -07002024
2025 /*
2026 * TODO: The abstraction between things stored in hardware and regular blobs
2027 * of data stored on the filesystem should be moved down to keystore itself.
2028 * Unfortunately the Java code that calls this has naming conventions that it
2029 * knows about. Ideally keystore shouldn't be used to store random blobs of
2030 * data.
2031 *
2032 * Until that happens, it's necessary to have a separate "get_pubkey" and
2033 * "del_key" since the Java code doesn't really communicate what it's
2034 * intentions are.
2035 */
2036 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002037 ExportResult result;
2038 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2039 if (result.resultCode != ::NO_ERROR) {
2040 ALOGW("export failed: %d", result.resultCode);
2041 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002042 }
Kenny Root07438c82012-11-02 15:41:02 -07002043
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002044 *pubkey = result.exportData.release();
2045 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002046 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002047 }
Kenny Root07438c82012-11-02 15:41:02 -07002048
Kenny Root07438c82012-11-02 15:41:02 -07002049 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002050 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002051 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2052 if (result != ::NO_ERROR) {
2053 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002054 }
2055
2056 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002057 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002058
Kenny Root655b9582013-04-04 08:37:42 -07002059 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002060 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2061 }
2062
Kenny Root655b9582013-04-04 08:37:42 -07002063 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002064 return ::NO_ERROR;
2065 }
2066
2067 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002068 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002069 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2070 if (result != ::NO_ERROR) {
2071 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002072 }
2073
2074 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002075 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002076
Kenny Root655b9582013-04-04 08:37:42 -07002077 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002078 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2079 }
2080
Kenny Root655b9582013-04-04 08:37:42 -07002081 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002082 }
2083
2084 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002085 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002086 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002087 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002088 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002089 }
Kenny Root07438c82012-11-02 15:41:02 -07002090
2091 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002092 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002093
Kenny Root655b9582013-04-04 08:37:42 -07002094 if (access(filename.string(), R_OK) == -1) {
2095 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002096 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002097 }
2098
Kenny Root655b9582013-04-04 08:37:42 -07002099 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002100 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002101 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002102 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002103 }
2104
2105 struct stat s;
2106 int ret = fstat(fd, &s);
2107 close(fd);
2108 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002109 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002110 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002111 }
2112
Kenny Root36a9e232013-02-04 14:24:15 -08002113 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002114 }
2115
Kenny Rootd53bc922013-03-21 14:10:15 -07002116 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2117 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002118 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002119 pid_t spid = IPCThreadState::self()->getCallingPid();
2120 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002121 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002122 return -1L;
2123 }
2124
Chad Brubaker72593ee2015-05-12 10:42:00 -07002125 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002126 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002127 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002128 return state;
2129 }
2130
Kenny Rootd53bc922013-03-21 14:10:15 -07002131 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2132 srcUid = callingUid;
2133 } else if (!is_granted_to(callingUid, srcUid)) {
2134 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002135 return ::PERMISSION_DENIED;
2136 }
2137
Kenny Rootd53bc922013-03-21 14:10:15 -07002138 if (destUid == -1) {
2139 destUid = callingUid;
2140 }
2141
2142 if (srcUid != destUid) {
2143 if (static_cast<uid_t>(srcUid) != callingUid) {
2144 ALOGD("can only duplicate from caller to other or to same uid: "
2145 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2146 return ::PERMISSION_DENIED;
2147 }
2148
2149 if (!is_granted_to(callingUid, destUid)) {
2150 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2151 return ::PERMISSION_DENIED;
2152 }
2153 }
2154
2155 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002156 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002157
Kenny Rootd53bc922013-03-21 14:10:15 -07002158 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002159 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002160
Kenny Root655b9582013-04-04 08:37:42 -07002161 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2162 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002163 return ::SYSTEM_ERROR;
2164 }
2165
Kenny Rootd53bc922013-03-21 14:10:15 -07002166 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002167 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002168 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002169 if (responseCode != ::NO_ERROR) {
2170 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002171 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002172
Chad Brubaker72593ee2015-05-12 10:42:00 -07002173 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002174 }
2175
Kenny Root1b0e3932013-09-05 13:06:32 -07002176 int32_t is_hardware_backed(const String16& keyType) {
2177 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002178 }
2179
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002180 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002181 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002182 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002183 return ::PERMISSION_DENIED;
2184 }
2185
Robin Lee4b84fdc2014-09-24 11:56:57 +01002186 String8 prefix = String8::format("%u_", targetUid);
2187 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002188 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002189 return ::SYSTEM_ERROR;
2190 }
2191
Robin Lee4b84fdc2014-09-24 11:56:57 +01002192 for (uint32_t i = 0; i < aliases.size(); i++) {
2193 String8 name8(aliases[i]);
2194 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002195 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002196 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002197 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002198 }
2199
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002200 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2201 const keymaster1_device_t* device = mKeyStore->getDevice();
2202 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2203 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2204 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2205 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2206 device->add_rng_entropy != NULL) {
2207 devResult = device->add_rng_entropy(device, data, dataLength);
2208 }
2209 if (fallback->add_rng_entropy) {
2210 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2211 }
2212 if (devResult) {
2213 return devResult;
2214 }
2215 if (fallbackResult) {
2216 return fallbackResult;
2217 }
2218 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002219 }
2220
Chad Brubaker17d68b92015-02-05 22:04:16 -08002221 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002222 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2223 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002224 uid = getEffectiveUid(uid);
2225 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2226 flags & KEYSTORE_FLAG_ENCRYPTED);
2227 if (rc != ::NO_ERROR) {
2228 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002229 }
2230
Chad Brubaker9489b792015-04-14 11:01:45 -07002231 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002232 bool isFallback = false;
2233 keymaster_key_blob_t blob;
2234 keymaster_key_characteristics_t *out = NULL;
2235
2236 const keymaster1_device_t* device = mKeyStore->getDevice();
2237 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002238 std::vector<keymaster_key_param_t> opParams(params.params);
2239 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002240 if (device == NULL) {
2241 return ::SYSTEM_ERROR;
2242 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002243 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002244 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2245 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002246 if (!entropy) {
2247 rc = KM_ERROR_OK;
2248 } else if (device->add_rng_entropy) {
2249 rc = device->add_rng_entropy(device, entropy, entropyLength);
2250 } else {
2251 rc = KM_ERROR_UNIMPLEMENTED;
2252 }
2253 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002254 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002255 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002256 }
2257 // If the HW device didn't support generate_key or generate_key failed
2258 // fall back to the software implementation.
2259 if (rc && fallback->generate_key != NULL) {
2260 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002261 if (!entropy) {
2262 rc = KM_ERROR_OK;
2263 } else if (fallback->add_rng_entropy) {
2264 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2265 } else {
2266 rc = KM_ERROR_UNIMPLEMENTED;
2267 }
2268 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002269 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002270 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002271 }
2272
2273 if (out) {
2274 if (outCharacteristics) {
2275 outCharacteristics->characteristics = *out;
2276 } else {
2277 keymaster_free_characteristics(out);
2278 }
2279 free(out);
2280 }
2281
2282 if (rc) {
2283 return rc;
2284 }
2285
2286 String8 name8(name);
2287 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2288
2289 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2290 keyBlob.setFallback(isFallback);
2291 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2292
2293 free(const_cast<uint8_t*>(blob.key_material));
2294
Chad Brubaker72593ee2015-05-12 10:42:00 -07002295 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002296 }
2297
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002298 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002299 const keymaster_blob_t* clientId,
2300 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002301 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002302 if (!outCharacteristics) {
2303 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2304 }
2305
2306 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2307
2308 Blob keyBlob;
2309 String8 name8(name);
2310 int rc;
2311
2312 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2313 TYPE_KEYMASTER_10);
2314 if (responseCode != ::NO_ERROR) {
2315 return responseCode;
2316 }
2317 keymaster_key_blob_t key;
2318 key.key_material_size = keyBlob.getLength();
2319 key.key_material = keyBlob.getValue();
2320 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2321 keymaster_key_characteristics_t *out = NULL;
2322 if (!dev->get_key_characteristics) {
2323 ALOGW("device does not implement get_key_characteristics");
2324 return KM_ERROR_UNIMPLEMENTED;
2325 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002326 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002327 if (out) {
2328 outCharacteristics->characteristics = *out;
2329 free(out);
2330 }
2331 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002332 }
2333
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002334 int32_t importKey(const String16& name, const KeymasterArguments& params,
2335 keymaster_key_format_t format, const uint8_t *keyData,
2336 size_t keyLength, int uid, int flags,
2337 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002338 uid = getEffectiveUid(uid);
2339 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2340 flags & KEYSTORE_FLAG_ENCRYPTED);
2341 if (rc != ::NO_ERROR) {
2342 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002343 }
2344
Chad Brubaker9489b792015-04-14 11:01:45 -07002345 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002346 bool isFallback = false;
2347 keymaster_key_blob_t blob;
2348 keymaster_key_characteristics_t *out = NULL;
2349
2350 const keymaster1_device_t* device = mKeyStore->getDevice();
2351 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002352 std::vector<keymaster_key_param_t> opParams(params.params);
2353 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2354 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002355 if (device == NULL) {
2356 return ::SYSTEM_ERROR;
2357 }
2358 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2359 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002360 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002361 }
2362 if (rc && fallback->import_key != NULL) {
2363 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002364 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002365 }
2366 if (out) {
2367 if (outCharacteristics) {
2368 outCharacteristics->characteristics = *out;
2369 } else {
2370 keymaster_free_characteristics(out);
2371 }
2372 free(out);
2373 }
2374 if (rc) {
2375 return rc;
2376 }
2377
2378 String8 name8(name);
2379 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2380
2381 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2382 keyBlob.setFallback(isFallback);
2383 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2384
2385 free((void*) blob.key_material);
2386
Chad Brubaker72593ee2015-05-12 10:42:00 -07002387 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002388 }
2389
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002390 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002391 const keymaster_blob_t* clientId,
2392 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002393
2394 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2395
2396 Blob keyBlob;
2397 String8 name8(name);
2398 int rc;
2399
2400 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2401 TYPE_KEYMASTER_10);
2402 if (responseCode != ::NO_ERROR) {
2403 result->resultCode = responseCode;
2404 return;
2405 }
2406 keymaster_key_blob_t key;
2407 key.key_material_size = keyBlob.getLength();
2408 key.key_material = keyBlob.getValue();
2409 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2410 if (!dev->export_key) {
2411 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2412 return;
2413 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002414 keymaster_blob_t output = {NULL, 0};
2415 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2416 result->exportData.reset(const_cast<uint8_t*>(output.data));
2417 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002418 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002419 }
2420
Chad Brubakerad6514a2015-04-09 14:00:26 -07002421
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002422 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002423 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002424 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002425 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2426 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2427 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2428 result->resultCode = ::PERMISSION_DENIED;
2429 return;
2430 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002431 if (!checkAllowedOperationParams(params.params)) {
2432 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2433 return;
2434 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002435 Blob keyBlob;
2436 String8 name8(name);
2437 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2438 TYPE_KEYMASTER_10);
2439 if (responseCode != ::NO_ERROR) {
2440 result->resultCode = responseCode;
2441 return;
2442 }
2443 keymaster_key_blob_t key;
2444 key.key_material_size = keyBlob.getLength();
2445 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002446 keymaster_operation_handle_t handle;
2447 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002448 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002449 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002450 Unique_keymaster_key_characteristics characteristics;
2451 characteristics.reset(new keymaster_key_characteristics_t);
2452 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2453 if (err) {
2454 result->resultCode = err;
2455 return;
2456 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002457 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002458 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002459 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002460 // If per-operation auth is needed we need to begin the operation and
2461 // the client will need to authorize that operation before calling
2462 // update. Any other auth issues stop here.
2463 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2464 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002465 return;
2466 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002467 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002468 // Add entropy to the device first.
2469 if (entropy) {
2470 if (dev->add_rng_entropy) {
2471 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2472 } else {
2473 err = KM_ERROR_UNIMPLEMENTED;
2474 }
2475 if (err) {
2476 result->resultCode = err;
2477 return;
2478 }
2479 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002480 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2481 keymaster_key_param_set_t outParams = {NULL, 0};
2482 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002483
Shawn Willden9221bff2015-06-18 18:23:54 -06002484 // Create a keyid for this key.
2485 keymaster::km_id_t keyid;
2486 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2487 ALOGE("Failed to create a key ID for authorization checking.");
2488 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2489 return;
2490 }
2491
2492 // Check that all key authorization policy requirements are met.
2493 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2494 key_auths.push_back(characteristics->sw_enforced);
2495 keymaster::AuthorizationSet operation_params(inParams);
2496 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2497 0 /* op_handle */,
2498 true /* is_begin_operation */);
2499 if (err) {
2500 result->resultCode = err;
2501 return;
2502 }
2503
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002504 // If there are too many operations abort the oldest operation that was
2505 // started as pruneable and try again.
2506 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2507 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2508 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2509 if (abort(oldest) != ::NO_ERROR) {
2510 break;
2511 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002512 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002513 }
2514 if (err) {
2515 result->resultCode = err;
2516 return;
2517 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002518
Shawn Willden9221bff2015-06-18 18:23:54 -06002519 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2520 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002521 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002522 if (authToken) {
2523 mOperationMap.setOperationAuthToken(operationToken, authToken);
2524 }
2525 // Return the authentication lookup result. If this is a per operation
2526 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2527 // application should get an auth token using the handle before the
2528 // first call to update, which will fail if keystore hasn't received the
2529 // auth token.
2530 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002531 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002532 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002533 if (outParams.params) {
2534 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2535 free(outParams.params);
2536 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002537 }
2538
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002539 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2540 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002541 if (!checkAllowedOperationParams(params.params)) {
2542 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2543 return;
2544 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002545 const keymaster1_device_t* dev;
2546 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002547 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002548 keymaster::km_id_t keyid;
2549 const keymaster_key_characteristics_t* characteristics;
2550 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002551 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2552 return;
2553 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002554 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002555 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2556 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002557 result->resultCode = authResult;
2558 return;
2559 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002560 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2561 keymaster_blob_t input = {data, dataLength};
2562 size_t consumed = 0;
2563 keymaster_blob_t output = {NULL, 0};
2564 keymaster_key_param_set_t outParams = {NULL, 0};
2565
Shawn Willden9221bff2015-06-18 18:23:54 -06002566 // Check that all key authorization policy requirements are met.
2567 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2568 key_auths.push_back(characteristics->sw_enforced);
2569 keymaster::AuthorizationSet operation_params(inParams);
2570 result->resultCode =
2571 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2572 operation_params, handle,
2573 false /* is_begin_operation */);
2574 if (result->resultCode) {
2575 return;
2576 }
2577
Chad Brubaker57e106d2015-06-01 12:59:00 -07002578 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2579 &output);
2580 result->data.reset(const_cast<uint8_t*>(output.data));
2581 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002582 result->inputConsumed = consumed;
2583 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002584 if (outParams.params) {
2585 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2586 free(outParams.params);
2587 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002588 }
2589
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002590 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002591 const uint8_t* signature, size_t signatureLength,
2592 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002593 if (!checkAllowedOperationParams(params.params)) {
2594 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2595 return;
2596 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002597 const keymaster1_device_t* dev;
2598 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002599 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002600 keymaster::km_id_t keyid;
2601 const keymaster_key_characteristics_t* characteristics;
2602 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002603 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2604 return;
2605 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002606 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002607 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2608 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002609 result->resultCode = authResult;
2610 return;
2611 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002612 keymaster_error_t err;
2613 if (entropy) {
2614 if (dev->add_rng_entropy) {
2615 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2616 } else {
2617 err = KM_ERROR_UNIMPLEMENTED;
2618 }
2619 if (err) {
2620 result->resultCode = err;
2621 return;
2622 }
2623 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002624
Chad Brubaker57e106d2015-06-01 12:59:00 -07002625 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2626 keymaster_blob_t input = {signature, signatureLength};
2627 keymaster_blob_t output = {NULL, 0};
2628 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002629
2630 // Check that all key authorization policy requirements are met.
2631 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2632 key_auths.push_back(characteristics->sw_enforced);
2633 keymaster::AuthorizationSet operation_params(inParams);
2634 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2635 handle, false /* is_begin_operation */);
2636 if (err) {
2637 result->resultCode = err;
2638 return;
2639 }
2640
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002641 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002642 // Remove the operation regardless of the result
2643 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002644 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002645
2646 result->data.reset(const_cast<uint8_t*>(output.data));
2647 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002648 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-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 int32_t abort(const sp<IBinder>& token) {
2656 const keymaster1_device_t* dev;
2657 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002658 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002659 keymaster::km_id_t keyid;
2660 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002661 return KM_ERROR_INVALID_OPERATION_HANDLE;
2662 }
2663 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002664 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002665 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002666 rc = KM_ERROR_UNIMPLEMENTED;
2667 } else {
2668 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002669 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002670 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002671 if (rc) {
2672 return rc;
2673 }
2674 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002675 }
2676
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002677 bool isOperationAuthorized(const sp<IBinder>& token) {
2678 const keymaster1_device_t* dev;
2679 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002680 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002681 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002682 keymaster::km_id_t keyid;
2683 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002684 return false;
2685 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002686 const hw_auth_token_t* authToken = NULL;
2687 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002688 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002689 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2690 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002691 }
2692
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002693 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002694 if (!checkBinderPermission(P_ADD_AUTH)) {
2695 ALOGW("addAuthToken: permission denied for %d",
2696 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002697 return ::PERMISSION_DENIED;
2698 }
2699 if (length != sizeof(hw_auth_token_t)) {
2700 return KM_ERROR_INVALID_ARGUMENT;
2701 }
2702 hw_auth_token_t* authToken = new hw_auth_token_t;
2703 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2704 // The table takes ownership of authToken.
2705 mAuthTokenTable.AddAuthenticationToken(authToken);
2706 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002707 }
2708
Kenny Root07438c82012-11-02 15:41:02 -07002709private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002710 static const int32_t UID_SELF = -1;
2711
2712 /**
2713 * Get the effective target uid for a binder operation that takes an
2714 * optional uid as the target.
2715 */
2716 inline uid_t getEffectiveUid(int32_t targetUid) {
2717 if (targetUid == UID_SELF) {
2718 return IPCThreadState::self()->getCallingUid();
2719 }
2720 return static_cast<uid_t>(targetUid);
2721 }
2722
2723 /**
2724 * Check if the caller of the current binder method has the required
2725 * permission and if acting on other uids the grants to do so.
2726 */
2727 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2728 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2729 pid_t spid = IPCThreadState::self()->getCallingPid();
2730 if (!has_permission(callingUid, permission, spid)) {
2731 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2732 return false;
2733 }
2734 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2735 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2736 return false;
2737 }
2738 return true;
2739 }
2740
2741 /**
2742 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002743 * permission and the target uid is the caller or the caller is system.
2744 */
2745 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2746 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2747 pid_t spid = IPCThreadState::self()->getCallingPid();
2748 if (!has_permission(callingUid, permission, spid)) {
2749 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2750 return false;
2751 }
2752 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2753 }
2754
2755 /**
2756 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002757 * permission or the target of the operation is the caller's uid. This is
2758 * for operation where the permission is only for cross-uid activity and all
2759 * uids are allowed to act on their own (ie: clearing all entries for a
2760 * given uid).
2761 */
2762 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2763 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2764 if (getEffectiveUid(targetUid) == callingUid) {
2765 return true;
2766 } else {
2767 return checkBinderPermission(permission, targetUid);
2768 }
2769 }
2770
2771 /**
2772 * Helper method to check that the caller has the required permission as
2773 * well as the keystore is in the unlocked state if checkUnlocked is true.
2774 *
2775 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2776 * otherwise the state of keystore when not unlocked and checkUnlocked is
2777 * true.
2778 */
2779 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2780 bool checkUnlocked = true) {
2781 if (!checkBinderPermission(permission, targetUid)) {
2782 return ::PERMISSION_DENIED;
2783 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002784 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002785 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2786 return state;
2787 }
2788
2789 return ::NO_ERROR;
2790
2791 }
2792
Kenny Root9d45d1c2013-02-14 10:32:30 -08002793 inline bool isKeystoreUnlocked(State state) {
2794 switch (state) {
2795 case ::STATE_NO_ERROR:
2796 return true;
2797 case ::STATE_UNINITIALIZED:
2798 case ::STATE_LOCKED:
2799 return false;
2800 }
2801 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002802 }
2803
Chad Brubaker67d2a502015-03-11 17:21:18 +00002804 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002805 const int32_t device_api = device->common.module->module_api_version;
2806 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2807 switch (keyType) {
2808 case TYPE_RSA:
2809 case TYPE_DSA:
2810 case TYPE_EC:
2811 return true;
2812 default:
2813 return false;
2814 }
2815 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2816 switch (keyType) {
2817 case TYPE_RSA:
2818 return true;
2819 case TYPE_DSA:
2820 return device->flags & KEYMASTER_SUPPORTS_DSA;
2821 case TYPE_EC:
2822 return device->flags & KEYMASTER_SUPPORTS_EC;
2823 default:
2824 return false;
2825 }
2826 } else {
2827 return keyType == TYPE_RSA;
2828 }
2829 }
2830
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002831 /**
2832 * Check that all keymaster_key_param_t's provided by the application are
2833 * allowed. Any parameter that keystore adds itself should be disallowed here.
2834 */
2835 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2836 for (auto param: params) {
2837 switch (param.tag) {
2838 case KM_TAG_AUTH_TOKEN:
2839 return false;
2840 default:
2841 break;
2842 }
2843 }
2844 return true;
2845 }
2846
2847 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2848 const keymaster1_device_t* dev,
2849 const std::vector<keymaster_key_param_t>& params,
2850 keymaster_key_characteristics_t* out) {
2851 UniquePtr<keymaster_blob_t> appId;
2852 UniquePtr<keymaster_blob_t> appData;
2853 for (auto param : params) {
2854 if (param.tag == KM_TAG_APPLICATION_ID) {
2855 appId.reset(new keymaster_blob_t);
2856 appId->data = param.blob.data;
2857 appId->data_length = param.blob.data_length;
2858 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2859 appData.reset(new keymaster_blob_t);
2860 appData->data = param.blob.data;
2861 appData->data_length = param.blob.data_length;
2862 }
2863 }
2864 keymaster_key_characteristics_t* result = NULL;
2865 if (!dev->get_key_characteristics) {
2866 return KM_ERROR_UNIMPLEMENTED;
2867 }
2868 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2869 appData.get(), &result);
2870 if (result) {
2871 *out = *result;
2872 free(result);
2873 }
2874 return error;
2875 }
2876
2877 /**
2878 * Get the auth token for this operation from the auth token table.
2879 *
2880 * Returns ::NO_ERROR if the auth token was set or none was required.
2881 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2882 * authorization token exists for that operation and
2883 * failOnTokenMissing is false.
2884 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2885 * token for the operation
2886 */
2887 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2888 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002889 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002890 const hw_auth_token_t** authToken,
2891 bool failOnTokenMissing = true) {
2892
2893 std::vector<keymaster_key_param_t> allCharacteristics;
2894 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2895 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2896 }
2897 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2898 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2899 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002900 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
2901 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002902 switch (err) {
2903 case keymaster::AuthTokenTable::OK:
2904 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2905 return ::NO_ERROR;
2906 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2907 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2908 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2909 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2910 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2911 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2912 (int32_t) ::OP_AUTH_NEEDED;
2913 default:
2914 ALOGE("Unexpected FindAuthorization return value %d", err);
2915 return KM_ERROR_INVALID_ARGUMENT;
2916 }
2917 }
2918
2919 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2920 const hw_auth_token_t* token) {
2921 if (token) {
2922 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2923 reinterpret_cast<const uint8_t*>(token),
2924 sizeof(hw_auth_token_t)));
2925 }
2926 }
2927
2928 /**
2929 * Add the auth token for the operation to the param list if the operation
2930 * requires authorization. Uses the cached result in the OperationMap if available
2931 * otherwise gets the token from the AuthTokenTable and caches the result.
2932 *
2933 * Returns ::NO_ERROR if the auth token was added or not needed.
2934 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2935 * authenticated.
2936 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2937 * operation token.
2938 */
2939 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2940 std::vector<keymaster_key_param_t>* params) {
2941 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002942 mOperationMap.getOperationAuthToken(token, &authToken);
2943 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002944 const keymaster1_device_t* dev;
2945 keymaster_operation_handle_t handle;
2946 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002947 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002948 keymaster::km_id_t keyid;
2949 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
2950 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002951 return KM_ERROR_INVALID_OPERATION_HANDLE;
2952 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002953 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002954 if (result != ::NO_ERROR) {
2955 return result;
2956 }
2957 if (authToken) {
2958 mOperationMap.setOperationAuthToken(token, authToken);
2959 }
2960 }
2961 addAuthToParams(params, authToken);
2962 return ::NO_ERROR;
2963 }
2964
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002965 /**
2966 * Translate a result value to a legacy return value. All keystore errors are
2967 * preserved and keymaster errors become SYSTEM_ERRORs
2968 */
2969 inline int32_t translateResultToLegacyResult(int32_t result) {
2970 if (result > 0) {
2971 return result;
2972 }
2973 return ::SYSTEM_ERROR;
2974 }
2975
2976 void addLegacyKeyAuthorizations(std::vector<keymaster_key_param_t>& params) {
2977 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
2978 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
2979 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
2980 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
2981 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
2982 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
2983 params.push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
2984 params.push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
2985 params.push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
2986 params.push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
2987 params.push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
2988 uint64_t now = keymaster::java_time(time(NULL));
2989 params.push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
2990 }
2991
2992 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
2993 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2994 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
2995 return &characteristics->hw_enforced.params[i];
2996 }
2997 }
2998 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2999 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3000 return &characteristics->sw_enforced.params[i];
3001 }
3002 }
3003 return NULL;
3004 }
3005
3006 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3007 // All legacy keys are DIGEST_NONE/PAD_NONE.
3008 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3009 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3010
3011 // Look up the algorithm of the key.
3012 KeyCharacteristics characteristics;
3013 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3014 if (rc != ::NO_ERROR) {
3015 ALOGE("Failed to get key characteristics");
3016 return;
3017 }
3018 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3019 if (!algorithm) {
3020 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3021 return;
3022 }
3023 params.push_back(*algorithm);
3024 }
3025
3026 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3027 uint8_t** out, size_t* outLength, const uint8_t* signature,
3028 size_t signatureLength, keymaster_purpose_t purpose) {
3029
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003030 std::basic_stringstream<uint8_t> outBuffer;
3031 OperationResult result;
3032 KeymasterArguments inArgs;
3033 addLegacyBeginParams(name, inArgs.params);
3034 sp<IBinder> appToken(new BBinder);
3035 sp<IBinder> token;
3036
3037 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3038 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003039 if (result.resultCode == ::KEY_NOT_FOUND) {
3040 ALOGW("Key not found");
3041 } else {
3042 ALOGW("Error in begin: %d", result.resultCode);
3043 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003044 return translateResultToLegacyResult(result.resultCode);
3045 }
3046 inArgs.params.clear();
3047 token = result.token;
3048 size_t consumed = 0;
3049 size_t lastConsumed = 0;
3050 do {
3051 update(token, inArgs, data + consumed, length - consumed, &result);
3052 if (result.resultCode != ResponseCode::NO_ERROR) {
3053 ALOGW("Error in update: %d", result.resultCode);
3054 return translateResultToLegacyResult(result.resultCode);
3055 }
3056 if (out) {
3057 outBuffer.write(result.data.get(), result.dataLength);
3058 }
3059 lastConsumed = result.inputConsumed;
3060 consumed += lastConsumed;
3061 } while (consumed < length && lastConsumed > 0);
3062
3063 if (consumed != length) {
3064 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3065 return ::SYSTEM_ERROR;
3066 }
3067
3068 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3069 if (result.resultCode != ResponseCode::NO_ERROR) {
3070 ALOGW("Error in finish: %d", result.resultCode);
3071 return translateResultToLegacyResult(result.resultCode);
3072 }
3073 if (out) {
3074 outBuffer.write(result.data.get(), result.dataLength);
3075 }
3076
3077 if (out) {
3078 auto buf = outBuffer.str();
3079 *out = new uint8_t[buf.size()];
3080 memcpy(*out, buf.c_str(), buf.size());
3081 *outLength = buf.size();
3082 }
3083
3084 return ::NO_ERROR;
3085 }
3086
Kenny Root07438c82012-11-02 15:41:02 -07003087 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003088 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003089 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003090 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003091};
3092
3093}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003094
3095int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003096 if (argc < 2) {
3097 ALOGE("A directory must be specified!");
3098 return 1;
3099 }
3100 if (chdir(argv[1]) == -1) {
3101 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3102 return 1;
3103 }
3104
3105 Entropy entropy;
3106 if (!entropy.open()) {
3107 return 1;
3108 }
Kenny Root70e3a862012-02-15 17:20:23 -08003109
Chad Brubakerbd07a232015-06-01 10:44:27 -07003110 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003111 if (keymaster_device_initialize(&dev)) {
3112 ALOGE("keystore keymaster could not be initialized; exiting");
3113 return 1;
3114 }
3115
Chad Brubaker67d2a502015-03-11 17:21:18 +00003116 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003117 if (fallback_keymaster_device_initialize(&fallback)) {
3118 ALOGE("software keymaster could not be initialized; exiting");
3119 return 1;
3120 }
3121
Riley Spahneaabae92014-06-30 12:39:52 -07003122 ks_is_selinux_enabled = is_selinux_enabled();
3123 if (ks_is_selinux_enabled) {
3124 union selinux_callback cb;
3125 cb.func_log = selinux_log_callback;
3126 selinux_set_callback(SELINUX_CB_LOG, cb);
3127 if (getcon(&tctx) != 0) {
3128 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3129 return -1;
3130 }
3131 } else {
3132 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3133 }
3134
Chad Brubakerbd07a232015-06-01 10:44:27 -07003135 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003136 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003137 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3138 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3139 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3140 if (ret != android::OK) {
3141 ALOGE("Couldn't register binder service!");
3142 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003143 }
Kenny Root07438c82012-11-02 15:41:02 -07003144
3145 /*
3146 * We're the only thread in existence, so we're just going to process
3147 * Binder transaction as a single-threaded program.
3148 */
3149 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003150
3151 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003152 return 1;
3153}