blob: af2d301b9aaef879358bc9abab8193d0dee939cb [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
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700672 if (fileLength == 0) {
673 return VALUE_CORRUPTED;
674 }
675
Kenny Rootf9119d62013-04-03 09:22:15 -0700676 if (isEncrypted() && (state != STATE_NO_ERROR)) {
677 return LOCKED;
678 }
679
Kenny Roota91203b2012-02-15 15:00:46 -0800680 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
681 if (fileLength < headerLength) {
682 return VALUE_CORRUPTED;
683 }
684
685 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700686 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800687 return VALUE_CORRUPTED;
688 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700689
690 ssize_t digestedLength;
691 if (isEncrypted()) {
692 if (encryptedLength % AES_BLOCK_SIZE != 0) {
693 return VALUE_CORRUPTED;
694 }
695
696 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
697 mBlob.vector, AES_DECRYPT);
698 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
699 uint8_t computedDigest[MD5_DIGEST_LENGTH];
700 MD5(mBlob.digested, digestedLength, computedDigest);
701 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
702 return VALUE_CORRUPTED;
703 }
704 } else {
705 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800706 }
707
708 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
709 mBlob.length = ntohl(mBlob.length);
710 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
711 return VALUE_CORRUPTED;
712 }
713 if (mBlob.info != 0) {
714 // move info from after padding to after data
715 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
716 }
Kenny Root07438c82012-11-02 15:41:02 -0700717 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800718 }
719
720private:
721 struct blob mBlob;
722};
723
Kenny Root655b9582013-04-04 08:37:42 -0700724class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800725public:
Kenny Root655b9582013-04-04 08:37:42 -0700726 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
727 asprintf(&mUserDir, "user_%u", mUserId);
728 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
729 }
730
731 ~UserState() {
732 free(mUserDir);
733 free(mMasterKeyFile);
734 }
735
736 bool initialize() {
737 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
738 ALOGE("Could not create directory '%s'", mUserDir);
739 return false;
740 }
741
742 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800743 setState(STATE_LOCKED);
744 } else {
745 setState(STATE_UNINITIALIZED);
746 }
Kenny Root70e3a862012-02-15 17:20:23 -0800747
Kenny Root655b9582013-04-04 08:37:42 -0700748 return true;
749 }
750
751 uid_t getUserId() const {
752 return mUserId;
753 }
754
755 const char* getUserDirName() const {
756 return mUserDir;
757 }
758
759 const char* getMasterKeyFileName() const {
760 return mMasterKeyFile;
761 }
762
763 void setState(State state) {
764 mState = state;
765 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
766 mRetry = MAX_RETRY;
767 }
Kenny Roota91203b2012-02-15 15:00:46 -0800768 }
769
Kenny Root51878182012-03-13 12:53:19 -0700770 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800771 return mState;
772 }
773
Kenny Root51878182012-03-13 12:53:19 -0700774 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800775 return mRetry;
776 }
777
Kenny Root655b9582013-04-04 08:37:42 -0700778 void zeroizeMasterKeysInMemory() {
779 memset(mMasterKey, 0, sizeof(mMasterKey));
780 memset(mSalt, 0, sizeof(mSalt));
781 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
782 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800783 }
784
Chad Brubaker96d6d782015-05-07 10:19:40 -0700785 bool deleteMasterKey() {
786 setState(STATE_UNINITIALIZED);
787 zeroizeMasterKeysInMemory();
788 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
789 }
790
Kenny Root655b9582013-04-04 08:37:42 -0700791 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
792 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800793 return SYSTEM_ERROR;
794 }
Kenny Root655b9582013-04-04 08:37:42 -0700795 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800796 if (response != NO_ERROR) {
797 return response;
798 }
799 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700800 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800801 }
802
Robin Lee4e865752014-08-19 17:37:55 +0100803 ResponseCode copyMasterKey(UserState* src) {
804 if (mState != STATE_UNINITIALIZED) {
805 return ::SYSTEM_ERROR;
806 }
807 if (src->getState() != STATE_NO_ERROR) {
808 return ::SYSTEM_ERROR;
809 }
810 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
811 setupMasterKeys();
812 return ::NO_ERROR;
813 }
814
Kenny Root655b9582013-04-04 08:37:42 -0700815 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800816 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
817 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
818 AES_KEY passwordAesKey;
819 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700820 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700821 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800822 }
823
Kenny Root655b9582013-04-04 08:37:42 -0700824 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
825 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800826 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800827 return SYSTEM_ERROR;
828 }
829
830 // we read the raw blob to just to get the salt to generate
831 // the AES key, then we create the Blob to use with decryptBlob
832 blob rawBlob;
833 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
834 if (close(in) != 0) {
835 return SYSTEM_ERROR;
836 }
837 // find salt at EOF if present, otherwise we have an old file
838 uint8_t* salt;
839 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
840 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
841 } else {
842 salt = NULL;
843 }
844 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
845 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
846 AES_KEY passwordAesKey;
847 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
848 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700849 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
850 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800851 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700852 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800853 }
854 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
855 // if salt was missing, generate one and write a new master key file with the salt.
856 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700857 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800858 return SYSTEM_ERROR;
859 }
Kenny Root655b9582013-04-04 08:37:42 -0700860 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800861 }
862 if (response == NO_ERROR) {
863 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
864 setupMasterKeys();
865 }
866 return response;
867 }
868 if (mRetry <= 0) {
869 reset();
870 return UNINITIALIZED;
871 }
872 --mRetry;
873 switch (mRetry) {
874 case 0: return WRONG_PASSWORD_0;
875 case 1: return WRONG_PASSWORD_1;
876 case 2: return WRONG_PASSWORD_2;
877 case 3: return WRONG_PASSWORD_3;
878 default: return WRONG_PASSWORD_3;
879 }
880 }
881
Kenny Root655b9582013-04-04 08:37:42 -0700882 AES_KEY* getEncryptionKey() {
883 return &mMasterKeyEncryption;
884 }
885
886 AES_KEY* getDecryptionKey() {
887 return &mMasterKeyDecryption;
888 }
889
Kenny Roota91203b2012-02-15 15:00:46 -0800890 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700891 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800892 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700893 // If the directory doesn't exist then nothing to do.
894 if (errno == ENOENT) {
895 return true;
896 }
Kenny Root655b9582013-04-04 08:37:42 -0700897 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800898 return false;
899 }
Kenny Root655b9582013-04-04 08:37:42 -0700900
901 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800902 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700903 // skip . and ..
904 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700905 continue;
906 }
907
908 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800909 }
910 closedir(dir);
911 return true;
912 }
913
Kenny Root655b9582013-04-04 08:37:42 -0700914private:
915 static const int MASTER_KEY_SIZE_BYTES = 16;
916 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
917
918 static const int MAX_RETRY = 4;
919 static const size_t SALT_SIZE = 16;
920
921 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
922 uint8_t* salt) {
923 size_t saltSize;
924 if (salt != NULL) {
925 saltSize = SALT_SIZE;
926 } else {
927 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
928 salt = (uint8_t*) "keystore";
929 // sizeof = 9, not strlen = 8
930 saltSize = sizeof("keystore");
931 }
932
933 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
934 saltSize, 8192, keySize, key);
935 }
936
937 bool generateSalt(Entropy* entropy) {
938 return entropy->generate_random_data(mSalt, sizeof(mSalt));
939 }
940
941 bool generateMasterKey(Entropy* entropy) {
942 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
943 return false;
944 }
945 if (!generateSalt(entropy)) {
946 return false;
947 }
948 return true;
949 }
950
951 void setupMasterKeys() {
952 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
953 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
954 setState(STATE_NO_ERROR);
955 }
956
957 uid_t mUserId;
958
959 char* mUserDir;
960 char* mMasterKeyFile;
961
962 State mState;
963 int8_t mRetry;
964
965 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
966 uint8_t mSalt[SALT_SIZE];
967
968 AES_KEY mMasterKeyEncryption;
969 AES_KEY mMasterKeyDecryption;
970};
971
972typedef struct {
973 uint32_t uid;
974 const uint8_t* filename;
975} grant_t;
976
977class KeyStore {
978public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000979 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700980 : mEntropy(entropy)
981 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800982 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700983 {
984 memset(&mMetaData, '\0', sizeof(mMetaData));
985 }
986
987 ~KeyStore() {
988 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
989 it != mGrants.end(); it++) {
990 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700991 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800992 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700993
994 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
995 it != mMasterKeys.end(); it++) {
996 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700997 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800998 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700999 }
1000
Chad Brubaker67d2a502015-03-11 17:21:18 +00001001 /**
1002 * Depending on the hardware keymaster version is this may return a
1003 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1004 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1005 * be guarded by a check on the device's version.
1006 */
1007 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001008 return mDevice;
1009 }
1010
Chad Brubaker67d2a502015-03-11 17:21:18 +00001011 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001012 return mFallbackDevice;
1013 }
1014
Chad Brubaker67d2a502015-03-11 17:21:18 +00001015 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001016 return blob.isFallback() ? mFallbackDevice: mDevice;
1017 }
1018
Kenny Root655b9582013-04-04 08:37:42 -07001019 ResponseCode initialize() {
1020 readMetaData();
1021 if (upgradeKeystore()) {
1022 writeMetaData();
1023 }
1024
1025 return ::NO_ERROR;
1026 }
1027
Chad Brubaker72593ee2015-05-12 10:42:00 -07001028 State getState(uid_t userId) {
1029 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001030 }
1031
Chad Brubaker72593ee2015-05-12 10:42:00 -07001032 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1033 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001034 return userState->initialize(pw, mEntropy);
1035 }
1036
Chad Brubaker72593ee2015-05-12 10:42:00 -07001037 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1038 UserState *userState = getUserState(dstUser);
1039 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001040 return userState->copyMasterKey(initState);
1041 }
1042
Chad Brubaker72593ee2015-05-12 10:42:00 -07001043 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1044 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001045 return userState->writeMasterKey(pw, mEntropy);
1046 }
1047
Chad Brubaker72593ee2015-05-12 10:42:00 -07001048 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1049 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001050 return userState->readMasterKey(pw, mEntropy);
1051 }
1052
1053 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001054 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001055 encode_key(encoded, keyName);
1056 return android::String8(encoded);
1057 }
1058
1059 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001060 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001061 encode_key(encoded, keyName);
1062 return android::String8::format("%u_%s", uid, encoded);
1063 }
1064
1065 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001066 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001067 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001068 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001069 encoded);
1070 }
1071
Chad Brubaker96d6d782015-05-07 10:19:40 -07001072 /*
1073 * Delete entries owned by userId. If keepUnencryptedEntries is true
1074 * then only encrypted entries will be removed, otherwise all entries will
1075 * be removed.
1076 */
1077 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001078 android::String8 prefix("");
1079 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001080 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001081 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001082 return;
1083 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001084 for (uint32_t i = 0; i < aliases.size(); i++) {
1085 android::String8 filename(aliases[i]);
1086 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001087 getKeyName(filename).string());
1088 bool shouldDelete = true;
1089 if (keepUnenryptedEntries) {
1090 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001091 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001092
Chad Brubaker96d6d782015-05-07 10:19:40 -07001093 /* get can fail if the blob is encrypted and the state is
1094 * not unlocked, only skip deleting blobs that were loaded and
1095 * who are not encrypted. If there are blobs we fail to read for
1096 * other reasons err on the safe side and delete them since we
1097 * can't tell if they're encrypted.
1098 */
1099 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1100 }
1101 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001102 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001103 }
1104 }
1105 if (!userState->deleteMasterKey()) {
1106 ALOGE("Failed to delete user %d's master key", userId);
1107 }
1108 if (!keepUnenryptedEntries) {
1109 if(!userState->reset()) {
1110 ALOGE("Failed to remove user %d's directory", userId);
1111 }
1112 }
Kenny Root655b9582013-04-04 08:37:42 -07001113 }
1114
Chad Brubaker72593ee2015-05-12 10:42:00 -07001115 bool isEmpty(uid_t userId) const {
1116 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001117 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001118 return true;
1119 }
1120
1121 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001122 if (!dir) {
1123 return true;
1124 }
Kenny Root31e27462014-09-10 11:28:03 -07001125
Kenny Roota91203b2012-02-15 15:00:46 -08001126 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001127 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001128 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001129 // We only care about files.
1130 if (file->d_type != DT_REG) {
1131 continue;
1132 }
1133
1134 // Skip anything that starts with a "."
1135 if (file->d_name[0] == '.') {
1136 continue;
1137 }
1138
Kenny Root31e27462014-09-10 11:28:03 -07001139 result = false;
1140 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001141 }
1142 closedir(dir);
1143 return result;
1144 }
1145
Chad Brubaker72593ee2015-05-12 10:42:00 -07001146 void lock(uid_t userId) {
1147 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001148 userState->zeroizeMasterKeysInMemory();
1149 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001150 }
1151
Chad Brubaker72593ee2015-05-12 10:42:00 -07001152 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1153 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001154 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1155 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001156 if (rc != NO_ERROR) {
1157 return rc;
1158 }
1159
1160 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001161 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001162 /* If we upgrade the key, we need to write it to disk again. Then
1163 * it must be read it again since the blob is encrypted each time
1164 * it's written.
1165 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001166 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1167 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001168 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1169 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001170 return rc;
1171 }
1172 }
Kenny Root822c3a92012-03-23 16:34:39 -07001173 }
1174
Kenny Root17208e02013-09-04 13:56:03 -07001175 /*
1176 * This will upgrade software-backed keys to hardware-backed keys when
1177 * the HAL for the device supports the newer key types.
1178 */
1179 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1180 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1181 && keyBlob->isFallback()) {
1182 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001183 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001184
1185 // The HAL allowed the import, reget the key to have the "fresh"
1186 // version.
1187 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001188 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001189 }
1190 }
1191
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001192 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1193 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001194 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001195 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001196 }
1197
Kenny Rootd53bc922013-03-21 14:10:15 -07001198 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001199 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1200 return KEY_NOT_FOUND;
1201 }
1202
1203 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001204 }
1205
Chad Brubaker72593ee2015-05-12 10:42:00 -07001206 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1207 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001208 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1209 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001210 }
1211
Chad Brubaker72593ee2015-05-12 10:42:00 -07001212 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001213 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001214 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001215 if (rc == ::VALUE_CORRUPTED) {
1216 // The file is corrupt, the best we can do is rm it.
1217 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1218 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001219 if (rc != ::NO_ERROR) {
1220 return rc;
1221 }
1222
1223 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1224 // A device doesn't have to implement delete_keypair.
1225 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1226 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1227 rc = ::SYSTEM_ERROR;
1228 }
1229 }
1230 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001231 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1232 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1233 if (dev->delete_key) {
1234 keymaster_key_blob_t blob;
1235 blob.key_material = keyBlob.getValue();
1236 blob.key_material_size = keyBlob.getLength();
1237 dev->delete_key(dev, &blob);
1238 }
1239 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001240 if (rc != ::NO_ERROR) {
1241 return rc;
1242 }
1243
1244 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1245 }
1246
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001247 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001248 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001249
Chad Brubaker72593ee2015-05-12 10:42:00 -07001250 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001251 size_t n = prefix.length();
1252
1253 DIR* dir = opendir(userState->getUserDirName());
1254 if (!dir) {
1255 ALOGW("can't open directory for user: %s", strerror(errno));
1256 return ::SYSTEM_ERROR;
1257 }
1258
1259 struct dirent* file;
1260 while ((file = readdir(dir)) != NULL) {
1261 // We only care about files.
1262 if (file->d_type != DT_REG) {
1263 continue;
1264 }
1265
1266 // Skip anything that starts with a "."
1267 if (file->d_name[0] == '.') {
1268 continue;
1269 }
1270
1271 if (!strncmp(prefix.string(), file->d_name, n)) {
1272 const char* p = &file->d_name[n];
1273 size_t plen = strlen(p);
1274
1275 size_t extra = decode_key_length(p, plen);
1276 char *match = (char*) malloc(extra + 1);
1277 if (match != NULL) {
1278 decode_key(match, p, plen);
1279 matches->push(android::String16(match, extra));
1280 free(match);
1281 } else {
1282 ALOGW("could not allocate match of size %zd", extra);
1283 }
1284 }
1285 }
1286 closedir(dir);
1287 return ::NO_ERROR;
1288 }
1289
Kenny Root07438c82012-11-02 15:41:02 -07001290 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001291 const grant_t* existing = getGrant(filename, granteeUid);
1292 if (existing == NULL) {
1293 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001294 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001295 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001296 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001297 }
1298 }
1299
Kenny Root07438c82012-11-02 15:41:02 -07001300 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001301 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1302 it != mGrants.end(); it++) {
1303 grant_t* grant = *it;
1304 if (grant->uid == granteeUid
1305 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1306 mGrants.erase(it);
1307 return true;
1308 }
Kenny Root70e3a862012-02-15 17:20:23 -08001309 }
Kenny Root70e3a862012-02-15 17:20:23 -08001310 return false;
1311 }
1312
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001313 bool hasGrant(const char* filename, const uid_t uid) const {
1314 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001315 }
1316
Chad Brubaker72593ee2015-05-12 10:42:00 -07001317 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001318 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001319 uint8_t* data;
1320 size_t dataLength;
1321 int rc;
1322
1323 if (mDevice->import_keypair == NULL) {
1324 ALOGE("Keymaster doesn't support import!");
1325 return SYSTEM_ERROR;
1326 }
1327
Kenny Root17208e02013-09-04 13:56:03 -07001328 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001329 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001330 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001331 /*
1332 * Maybe the device doesn't support this type of key. Try to use the
1333 * software fallback keymaster implementation. This is a little bit
1334 * lazier than checking the PKCS#8 key type, but the software
1335 * implementation will do that anyway.
1336 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001337 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001338 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001339
1340 if (rc) {
1341 ALOGE("Error while importing keypair: %d", rc);
1342 return SYSTEM_ERROR;
1343 }
Kenny Root822c3a92012-03-23 16:34:39 -07001344 }
1345
1346 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1347 free(data);
1348
Kenny Rootf9119d62013-04-03 09:22:15 -07001349 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001350 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001351
Chad Brubaker72593ee2015-05-12 10:42:00 -07001352 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001353 }
1354
Kenny Root1b0e3932013-09-05 13:06:32 -07001355 bool isHardwareBacked(const android::String16& keyType) const {
1356 if (mDevice == NULL) {
1357 ALOGW("can't get keymaster device");
1358 return false;
1359 }
1360
1361 if (sRSAKeyType == keyType) {
1362 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1363 } else {
1364 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1365 && (mDevice->common.module->module_api_version
1366 >= KEYMASTER_MODULE_API_VERSION_0_2);
1367 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001368 }
1369
Kenny Root655b9582013-04-04 08:37:42 -07001370 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1371 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001372 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001373 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001374
Chad Brubaker72593ee2015-05-12 10:42:00 -07001375 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001376 if (responseCode == NO_ERROR) {
1377 return responseCode;
1378 }
1379
1380 // If this is one of the legacy UID->UID mappings, use it.
1381 uid_t euid = get_keystore_euid(uid);
1382 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001383 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001384 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001385 if (responseCode == NO_ERROR) {
1386 return responseCode;
1387 }
1388 }
1389
1390 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001391 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001392 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001393 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001394 if (end[0] != '_' || end[1] == 0) {
1395 return KEY_NOT_FOUND;
1396 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001397 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001398 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001399 if (!hasGrant(filepath8.string(), uid)) {
1400 return responseCode;
1401 }
1402
1403 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001404 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001405 }
1406
1407 /**
1408 * Returns any existing UserState or creates it if it doesn't exist.
1409 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001410 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001411 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1412 it != mMasterKeys.end(); it++) {
1413 UserState* state = *it;
1414 if (state->getUserId() == userId) {
1415 return state;
1416 }
1417 }
1418
1419 UserState* userState = new UserState(userId);
1420 if (!userState->initialize()) {
1421 /* There's not much we can do if initialization fails. Trying to
1422 * unlock the keystore for that user will fail as well, so any
1423 * subsequent request for this user will just return SYSTEM_ERROR.
1424 */
1425 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1426 }
1427 mMasterKeys.add(userState);
1428 return userState;
1429 }
1430
1431 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001432 * Returns any existing UserState or creates it if it doesn't exist.
1433 */
1434 UserState* getUserStateByUid(uid_t uid) {
1435 uid_t userId = get_user_id(uid);
1436 return getUserState(userId);
1437 }
1438
1439 /**
Kenny Root655b9582013-04-04 08:37:42 -07001440 * Returns NULL if the UserState doesn't already exist.
1441 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001442 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001443 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1444 it != mMasterKeys.end(); it++) {
1445 UserState* state = *it;
1446 if (state->getUserId() == userId) {
1447 return state;
1448 }
1449 }
1450
1451 return NULL;
1452 }
1453
Chad Brubaker72593ee2015-05-12 10:42:00 -07001454 /**
1455 * Returns NULL if the UserState doesn't already exist.
1456 */
1457 const UserState* getUserStateByUid(uid_t uid) const {
1458 uid_t userId = get_user_id(uid);
1459 return getUserState(userId);
1460 }
1461
Kenny Roota91203b2012-02-15 15:00:46 -08001462private:
Kenny Root655b9582013-04-04 08:37:42 -07001463 static const char* sOldMasterKey;
1464 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001465 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001466 Entropy* mEntropy;
1467
Chad Brubaker67d2a502015-03-11 17:21:18 +00001468 keymaster1_device_t* mDevice;
1469 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001470
Kenny Root655b9582013-04-04 08:37:42 -07001471 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001472
Kenny Root655b9582013-04-04 08:37:42 -07001473 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001474
Kenny Root655b9582013-04-04 08:37:42 -07001475 typedef struct {
1476 uint32_t version;
1477 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001478
Kenny Root655b9582013-04-04 08:37:42 -07001479 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001480
Kenny Root655b9582013-04-04 08:37:42 -07001481 const grant_t* getGrant(const char* filename, uid_t uid) const {
1482 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1483 it != mGrants.end(); it++) {
1484 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001485 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001486 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001487 return grant;
1488 }
1489 }
Kenny Root70e3a862012-02-15 17:20:23 -08001490 return NULL;
1491 }
1492
Kenny Root822c3a92012-03-23 16:34:39 -07001493 /**
1494 * Upgrade code. This will upgrade the key from the current version
1495 * to whatever is newest.
1496 */
Kenny Root655b9582013-04-04 08:37:42 -07001497 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1498 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001499 bool updated = false;
1500 uint8_t version = oldVersion;
1501
1502 /* From V0 -> V1: All old types were unknown */
1503 if (version == 0) {
1504 ALOGV("upgrading to version 1 and setting type %d", type);
1505
1506 blob->setType(type);
1507 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001508 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001509 }
1510 version = 1;
1511 updated = true;
1512 }
1513
Kenny Rootf9119d62013-04-03 09:22:15 -07001514 /* From V1 -> V2: All old keys were encrypted */
1515 if (version == 1) {
1516 ALOGV("upgrading to version 2");
1517
1518 blob->setEncrypted(true);
1519 version = 2;
1520 updated = true;
1521 }
1522
Kenny Root822c3a92012-03-23 16:34:39 -07001523 /*
1524 * If we've updated, set the key blob to the right version
1525 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001526 */
Kenny Root822c3a92012-03-23 16:34:39 -07001527 if (updated) {
1528 ALOGV("updated and writing file %s", filename);
1529 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001530 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001531
1532 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001533 }
1534
1535 /**
1536 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1537 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1538 * Then it overwrites the original blob with the new blob
1539 * format that is returned from the keymaster.
1540 */
Kenny Root655b9582013-04-04 08:37:42 -07001541 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001542 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1543 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1544 if (b.get() == NULL) {
1545 ALOGE("Problem instantiating BIO");
1546 return SYSTEM_ERROR;
1547 }
1548
1549 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1550 if (pkey.get() == NULL) {
1551 ALOGE("Couldn't read old PEM file");
1552 return SYSTEM_ERROR;
1553 }
1554
1555 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1556 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1557 if (len < 0) {
1558 ALOGE("Couldn't measure PKCS#8 length");
1559 return SYSTEM_ERROR;
1560 }
1561
Kenny Root70c98892013-02-07 09:10:36 -08001562 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1563 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001564 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1565 ALOGE("Couldn't convert to PKCS#8");
1566 return SYSTEM_ERROR;
1567 }
1568
Chad Brubaker72593ee2015-05-12 10:42:00 -07001569 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001570 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001571 if (rc != NO_ERROR) {
1572 return rc;
1573 }
1574
Kenny Root655b9582013-04-04 08:37:42 -07001575 return get(filename, blob, TYPE_KEY_PAIR, uid);
1576 }
1577
1578 void readMetaData() {
1579 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1580 if (in < 0) {
1581 return;
1582 }
1583 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1584 if (fileLength != sizeof(mMetaData)) {
1585 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1586 sizeof(mMetaData));
1587 }
1588 close(in);
1589 }
1590
1591 void writeMetaData() {
1592 const char* tmpFileName = ".metadata.tmp";
1593 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1594 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1595 if (out < 0) {
1596 ALOGE("couldn't write metadata file: %s", strerror(errno));
1597 return;
1598 }
1599 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1600 if (fileLength != sizeof(mMetaData)) {
1601 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1602 sizeof(mMetaData));
1603 }
1604 close(out);
1605 rename(tmpFileName, sMetaDataFile);
1606 }
1607
1608 bool upgradeKeystore() {
1609 bool upgraded = false;
1610
1611 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001612 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001613
1614 // Initialize first so the directory is made.
1615 userState->initialize();
1616
1617 // Migrate the old .masterkey file to user 0.
1618 if (access(sOldMasterKey, R_OK) == 0) {
1619 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1620 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1621 return false;
1622 }
1623 }
1624
1625 // Initialize again in case we had a key.
1626 userState->initialize();
1627
1628 // Try to migrate existing keys.
1629 DIR* dir = opendir(".");
1630 if (!dir) {
1631 // Give up now; maybe we can upgrade later.
1632 ALOGE("couldn't open keystore's directory; something is wrong");
1633 return false;
1634 }
1635
1636 struct dirent* file;
1637 while ((file = readdir(dir)) != NULL) {
1638 // We only care about files.
1639 if (file->d_type != DT_REG) {
1640 continue;
1641 }
1642
1643 // Skip anything that starts with a "."
1644 if (file->d_name[0] == '.') {
1645 continue;
1646 }
1647
1648 // Find the current file's user.
1649 char* end;
1650 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1651 if (end[0] != '_' || end[1] == 0) {
1652 continue;
1653 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001654 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001655 if (otherUser->getUserId() != 0) {
1656 unlinkat(dirfd(dir), file->d_name, 0);
1657 }
1658
1659 // Rename the file into user directory.
1660 DIR* otherdir = opendir(otherUser->getUserDirName());
1661 if (otherdir == NULL) {
1662 ALOGW("couldn't open user directory for rename");
1663 continue;
1664 }
1665 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1666 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1667 }
1668 closedir(otherdir);
1669 }
1670 closedir(dir);
1671
1672 mMetaData.version = 1;
1673 upgraded = true;
1674 }
1675
1676 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001677 }
Kenny Roota91203b2012-02-15 15:00:46 -08001678};
1679
Kenny Root655b9582013-04-04 08:37:42 -07001680const char* KeyStore::sOldMasterKey = ".masterkey";
1681const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001682
Kenny Root1b0e3932013-09-05 13:06:32 -07001683const android::String16 KeyStore::sRSAKeyType("RSA");
1684
Kenny Root07438c82012-11-02 15:41:02 -07001685namespace android {
1686class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1687public:
1688 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001689 : mKeyStore(keyStore),
1690 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001691 {
Kenny Roota91203b2012-02-15 15:00:46 -08001692 }
Kenny Roota91203b2012-02-15 15:00:46 -08001693
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001694 void binderDied(const wp<IBinder>& who) {
1695 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1696 for (auto token: operations) {
1697 abort(token);
1698 }
Kenny Root822c3a92012-03-23 16:34:39 -07001699 }
Kenny Roota91203b2012-02-15 15:00:46 -08001700
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001701 int32_t getState(int32_t userId) {
1702 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001703 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001704 }
Kenny Roota91203b2012-02-15 15:00:46 -08001705
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001706 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001707 }
1708
Kenny Root07438c82012-11-02 15:41:02 -07001709 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001710 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001711 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001712 }
Kenny Root07438c82012-11-02 15:41:02 -07001713
Chad Brubaker9489b792015-04-14 11:01:45 -07001714 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001715 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001716 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001717
Kenny Root655b9582013-04-04 08:37:42 -07001718 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001719 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001720 if (responseCode != ::NO_ERROR) {
1721 *item = NULL;
1722 *itemLength = 0;
1723 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001724 }
Kenny Roota91203b2012-02-15 15:00:46 -08001725
Kenny Root07438c82012-11-02 15:41:02 -07001726 *item = (uint8_t*) malloc(keyBlob.getLength());
1727 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1728 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001729
Kenny Root07438c82012-11-02 15:41:02 -07001730 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001731 }
1732
Kenny Rootf9119d62013-04-03 09:22:15 -07001733 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1734 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001735 targetUid = getEffectiveUid(targetUid);
1736 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1737 flags & KEYSTORE_FLAG_ENCRYPTED);
1738 if (result != ::NO_ERROR) {
1739 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001740 }
1741
Kenny Root07438c82012-11-02 15:41:02 -07001742 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001743 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001744
1745 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001746 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1747
Chad Brubaker72593ee2015-05-12 10:42:00 -07001748 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001749 }
1750
Kenny Root49468902013-03-19 13:41:33 -07001751 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001752 targetUid = getEffectiveUid(targetUid);
1753 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001754 return ::PERMISSION_DENIED;
1755 }
Kenny Root07438c82012-11-02 15:41:02 -07001756 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001757 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001758 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001759 }
1760
Kenny Root49468902013-03-19 13:41:33 -07001761 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001762 targetUid = getEffectiveUid(targetUid);
1763 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001764 return ::PERMISSION_DENIED;
1765 }
1766
Kenny Root07438c82012-11-02 15:41:02 -07001767 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001768 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001769
Kenny Root655b9582013-04-04 08:37:42 -07001770 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001771 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1772 }
1773 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001774 }
1775
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001776 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001777 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001778 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001779 return ::PERMISSION_DENIED;
1780 }
Kenny Root07438c82012-11-02 15:41:02 -07001781 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001782 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001783
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001784 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001785 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001786 }
Kenny Root07438c82012-11-02 15:41:02 -07001787 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001788 }
1789
Kenny Root07438c82012-11-02 15:41:02 -07001790 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001791 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001792 return ::PERMISSION_DENIED;
1793 }
1794
Chad Brubaker9489b792015-04-14 11:01:45 -07001795 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001796 mKeyStore->resetUser(get_user_id(callingUid), false);
1797 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001798 }
1799
Chad Brubaker96d6d782015-05-07 10:19:40 -07001800 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001801 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001802 return ::PERMISSION_DENIED;
1803 }
Kenny Root70e3a862012-02-15 17:20:23 -08001804
Kenny Root07438c82012-11-02 15:41:02 -07001805 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001806 // Flush the auth token table to prevent stale tokens from sticking
1807 // around.
1808 mAuthTokenTable.Clear();
1809
1810 if (password.size() == 0) {
1811 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001812 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001813 return ::NO_ERROR;
1814 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001815 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001816 case ::STATE_UNINITIALIZED: {
1817 // generate master key, encrypt with password, write to file,
1818 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001819 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001820 }
1821 case ::STATE_NO_ERROR: {
1822 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001823 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001824 }
1825 case ::STATE_LOCKED: {
1826 ALOGE("Changing user %d's password while locked, clearing old encryption",
1827 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001828 mKeyStore->resetUser(userId, true);
1829 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001830 }
Kenny Root07438c82012-11-02 15:41:02 -07001831 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001832 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001833 }
Kenny Root70e3a862012-02-15 17:20:23 -08001834 }
1835
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001836 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1837 if (!checkBinderPermission(P_USER_CHANGED)) {
1838 return ::PERMISSION_DENIED;
1839 }
1840
1841 // Sanity check that the new user has an empty keystore.
1842 if (!mKeyStore->isEmpty(userId)) {
1843 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1844 }
1845 // Unconditionally clear the keystore, just to be safe.
1846 mKeyStore->resetUser(userId, false);
1847
1848 // If the user has a parent user then use the parent's
1849 // masterkey/password, otherwise there's nothing to do.
1850 if (parentId != -1) {
1851 return mKeyStore->copyMasterKey(parentId, userId);
1852 } else {
1853 return ::NO_ERROR;
1854 }
1855 }
1856
1857 int32_t onUserRemoved(int32_t userId) {
1858 if (!checkBinderPermission(P_USER_CHANGED)) {
1859 return ::PERMISSION_DENIED;
1860 }
1861
1862 mKeyStore->resetUser(userId, false);
1863 return ::NO_ERROR;
1864 }
1865
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001866 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001867 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001868 return ::PERMISSION_DENIED;
1869 }
Kenny Root70e3a862012-02-15 17:20:23 -08001870
Chad Brubaker72593ee2015-05-12 10:42:00 -07001871 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001872 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001873 ALOGD("calling lock in state: %d", state);
1874 return state;
1875 }
1876
Chad Brubaker72593ee2015-05-12 10:42:00 -07001877 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001878 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001879 }
1880
Chad Brubaker96d6d782015-05-07 10:19:40 -07001881 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001882 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001883 return ::PERMISSION_DENIED;
1884 }
1885
Chad Brubaker72593ee2015-05-12 10:42:00 -07001886 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001887 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001888 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001889 return state;
1890 }
1891
1892 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001893 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001894 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001895 }
1896
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001897 bool isEmpty(int32_t userId) {
1898 if (!checkBinderPermission(P_IS_EMPTY)) {
1899 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001900 }
Kenny Root70e3a862012-02-15 17:20:23 -08001901
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001902 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001903 }
1904
Kenny Root96427ba2013-08-16 14:02:41 -07001905 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1906 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001907 targetUid = getEffectiveUid(targetUid);
1908 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1909 flags & KEYSTORE_FLAG_ENCRYPTED);
1910 if (result != ::NO_ERROR) {
1911 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001912 }
Kenny Root07438c82012-11-02 15:41:02 -07001913
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001914 KeymasterArguments params;
1915 addLegacyKeyAuthorizations(params.params);
Kenny Root07438c82012-11-02 15:41:02 -07001916
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001917 switch (keyType) {
1918 case EVP_PKEY_EC: {
1919 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
1920 if (keySize == -1) {
1921 keySize = EC_DEFAULT_KEY_SIZE;
1922 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1923 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07001924 return ::SYSTEM_ERROR;
1925 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001926 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1927 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001928 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001929 case EVP_PKEY_RSA: {
1930 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1931 if (keySize == -1) {
1932 keySize = RSA_DEFAULT_KEY_SIZE;
1933 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1934 ALOGI("invalid key size %d", keySize);
1935 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07001936 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001937 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1938 unsigned long exponent = RSA_DEFAULT_EXPONENT;
1939 if (args->size() > 1) {
1940 ALOGI("invalid number of arguments: %zu", args->size());
1941 return ::SYSTEM_ERROR;
1942 } else if (args->size() == 1) {
1943 sp<KeystoreArg> expArg = args->itemAt(0);
1944 if (expArg != NULL) {
1945 Unique_BIGNUM pubExpBn(
1946 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
1947 expArg->size(), NULL));
1948 if (pubExpBn.get() == NULL) {
1949 ALOGI("Could not convert public exponent to BN");
1950 return ::SYSTEM_ERROR;
1951 }
1952 exponent = BN_get_word(pubExpBn.get());
1953 if (exponent == 0xFFFFFFFFL) {
1954 ALOGW("cannot represent public exponent as a long value");
1955 return ::SYSTEM_ERROR;
1956 }
1957 } else {
1958 ALOGW("public exponent not read");
1959 return ::SYSTEM_ERROR;
1960 }
1961 }
1962 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
1963 exponent));
1964 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001965 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001966 default: {
1967 ALOGW("Unsupported key type %d", keyType);
1968 return ::SYSTEM_ERROR;
1969 }
Kenny Root96427ba2013-08-16 14:02:41 -07001970 }
1971
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001972 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
1973 /*outCharacteristics*/ NULL);
1974 if (rc != ::NO_ERROR) {
1975 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07001976 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001977 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08001978 }
1979
Kenny Rootf9119d62013-04-03 09:22:15 -07001980 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1981 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001982 KeymasterArguments params;
1983 addLegacyKeyAuthorizations(params.params);
1984 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07001985
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001986 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
1987 if (!pkcs8.get()) {
1988 return ::SYSTEM_ERROR;
1989 }
1990 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1991 if (!pkey.get()) {
1992 return ::SYSTEM_ERROR;
1993 }
1994 int type = EVP_PKEY_type(pkey->type);
1995 switch (type) {
1996 case EVP_PKEY_RSA:
1997 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1998 break;
1999 case EVP_PKEY_EC:
2000 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2001 KM_ALGORITHM_EC));
2002 break;
2003 default:
2004 ALOGW("Unsupported key type %d", type);
2005 return ::SYSTEM_ERROR;
2006 }
2007 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2008 /*outCharacteristics*/ NULL);
2009 if (rc != ::NO_ERROR) {
2010 ALOGW("importKey failed: %d", rc);
2011 }
2012 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002013 }
2014
Kenny Root07438c82012-11-02 15:41:02 -07002015 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002016 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002017 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002018 return ::PERMISSION_DENIED;
2019 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002020 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002021 }
2022
Kenny Root07438c82012-11-02 15:41:02 -07002023 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2024 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002025 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002026 return ::PERMISSION_DENIED;
2027 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002028 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2029 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002030 }
Kenny Root07438c82012-11-02 15:41:02 -07002031
2032 /*
2033 * TODO: The abstraction between things stored in hardware and regular blobs
2034 * of data stored on the filesystem should be moved down to keystore itself.
2035 * Unfortunately the Java code that calls this has naming conventions that it
2036 * knows about. Ideally keystore shouldn't be used to store random blobs of
2037 * data.
2038 *
2039 * Until that happens, it's necessary to have a separate "get_pubkey" and
2040 * "del_key" since the Java code doesn't really communicate what it's
2041 * intentions are.
2042 */
2043 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002044 ExportResult result;
2045 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2046 if (result.resultCode != ::NO_ERROR) {
2047 ALOGW("export failed: %d", result.resultCode);
2048 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002049 }
Kenny Root07438c82012-11-02 15:41:02 -07002050
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002051 *pubkey = result.exportData.release();
2052 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002053 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002054 }
Kenny Root07438c82012-11-02 15:41:02 -07002055
Kenny Root07438c82012-11-02 15:41:02 -07002056 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002057 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002058 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2059 if (result != ::NO_ERROR) {
2060 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002061 }
2062
2063 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002064 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002065
Kenny Root655b9582013-04-04 08:37:42 -07002066 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002067 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2068 }
2069
Kenny Root655b9582013-04-04 08:37:42 -07002070 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002071 return ::NO_ERROR;
2072 }
2073
2074 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002075 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002076 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2077 if (result != ::NO_ERROR) {
2078 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002079 }
2080
2081 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002082 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002083
Kenny Root655b9582013-04-04 08:37:42 -07002084 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002085 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2086 }
2087
Kenny Root655b9582013-04-04 08:37:42 -07002088 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002089 }
2090
2091 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002092 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002093 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002094 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002095 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002096 }
Kenny Root07438c82012-11-02 15:41:02 -07002097
2098 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002099 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002100
Kenny Root655b9582013-04-04 08:37:42 -07002101 if (access(filename.string(), R_OK) == -1) {
2102 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002103 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002104 }
2105
Kenny Root655b9582013-04-04 08:37:42 -07002106 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002107 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002108 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002109 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002110 }
2111
2112 struct stat s;
2113 int ret = fstat(fd, &s);
2114 close(fd);
2115 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002116 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002117 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002118 }
2119
Kenny Root36a9e232013-02-04 14:24:15 -08002120 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002121 }
2122
Kenny Rootd53bc922013-03-21 14:10:15 -07002123 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2124 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002125 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002126 pid_t spid = IPCThreadState::self()->getCallingPid();
2127 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002128 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002129 return -1L;
2130 }
2131
Chad Brubaker72593ee2015-05-12 10:42:00 -07002132 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002133 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002134 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002135 return state;
2136 }
2137
Kenny Rootd53bc922013-03-21 14:10:15 -07002138 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2139 srcUid = callingUid;
2140 } else if (!is_granted_to(callingUid, srcUid)) {
2141 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002142 return ::PERMISSION_DENIED;
2143 }
2144
Kenny Rootd53bc922013-03-21 14:10:15 -07002145 if (destUid == -1) {
2146 destUid = callingUid;
2147 }
2148
2149 if (srcUid != destUid) {
2150 if (static_cast<uid_t>(srcUid) != callingUid) {
2151 ALOGD("can only duplicate from caller to other or to same uid: "
2152 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2153 return ::PERMISSION_DENIED;
2154 }
2155
2156 if (!is_granted_to(callingUid, destUid)) {
2157 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2158 return ::PERMISSION_DENIED;
2159 }
2160 }
2161
2162 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002163 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002164
Kenny Rootd53bc922013-03-21 14:10:15 -07002165 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002166 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002167
Kenny Root655b9582013-04-04 08:37:42 -07002168 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2169 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002170 return ::SYSTEM_ERROR;
2171 }
2172
Kenny Rootd53bc922013-03-21 14:10:15 -07002173 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002174 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002175 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002176 if (responseCode != ::NO_ERROR) {
2177 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002178 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002179
Chad Brubaker72593ee2015-05-12 10:42:00 -07002180 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002181 }
2182
Kenny Root1b0e3932013-09-05 13:06:32 -07002183 int32_t is_hardware_backed(const String16& keyType) {
2184 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002185 }
2186
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002187 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002188 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002189 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002190 return ::PERMISSION_DENIED;
2191 }
2192
Robin Lee4b84fdc2014-09-24 11:56:57 +01002193 String8 prefix = String8::format("%u_", targetUid);
2194 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002195 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002196 return ::SYSTEM_ERROR;
2197 }
2198
Robin Lee4b84fdc2014-09-24 11:56:57 +01002199 for (uint32_t i = 0; i < aliases.size(); i++) {
2200 String8 name8(aliases[i]);
2201 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002202 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002203 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002204 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002205 }
2206
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002207 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2208 const keymaster1_device_t* device = mKeyStore->getDevice();
2209 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2210 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2211 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2212 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2213 device->add_rng_entropy != NULL) {
2214 devResult = device->add_rng_entropy(device, data, dataLength);
2215 }
2216 if (fallback->add_rng_entropy) {
2217 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2218 }
2219 if (devResult) {
2220 return devResult;
2221 }
2222 if (fallbackResult) {
2223 return fallbackResult;
2224 }
2225 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002226 }
2227
Chad Brubaker17d68b92015-02-05 22:04:16 -08002228 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002229 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2230 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002231 uid = getEffectiveUid(uid);
2232 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2233 flags & KEYSTORE_FLAG_ENCRYPTED);
2234 if (rc != ::NO_ERROR) {
2235 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002236 }
2237
Chad Brubaker9489b792015-04-14 11:01:45 -07002238 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002239 bool isFallback = false;
2240 keymaster_key_blob_t blob;
2241 keymaster_key_characteristics_t *out = NULL;
2242
2243 const keymaster1_device_t* device = mKeyStore->getDevice();
2244 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002245 std::vector<keymaster_key_param_t> opParams(params.params);
2246 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002247 if (device == NULL) {
2248 return ::SYSTEM_ERROR;
2249 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002250 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002251 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2252 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002253 if (!entropy) {
2254 rc = KM_ERROR_OK;
2255 } else if (device->add_rng_entropy) {
2256 rc = device->add_rng_entropy(device, entropy, entropyLength);
2257 } else {
2258 rc = KM_ERROR_UNIMPLEMENTED;
2259 }
2260 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002261 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002262 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002263 }
2264 // If the HW device didn't support generate_key or generate_key failed
2265 // fall back to the software implementation.
2266 if (rc && fallback->generate_key != NULL) {
2267 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002268 if (!entropy) {
2269 rc = KM_ERROR_OK;
2270 } else if (fallback->add_rng_entropy) {
2271 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2272 } else {
2273 rc = KM_ERROR_UNIMPLEMENTED;
2274 }
2275 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002276 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002277 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002278 }
2279
2280 if (out) {
2281 if (outCharacteristics) {
2282 outCharacteristics->characteristics = *out;
2283 } else {
2284 keymaster_free_characteristics(out);
2285 }
2286 free(out);
2287 }
2288
2289 if (rc) {
2290 return rc;
2291 }
2292
2293 String8 name8(name);
2294 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2295
2296 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2297 keyBlob.setFallback(isFallback);
2298 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2299
2300 free(const_cast<uint8_t*>(blob.key_material));
2301
Chad Brubaker72593ee2015-05-12 10:42:00 -07002302 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002303 }
2304
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002305 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002306 const keymaster_blob_t* clientId,
2307 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002308 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002309 if (!outCharacteristics) {
2310 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2311 }
2312
2313 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2314
2315 Blob keyBlob;
2316 String8 name8(name);
2317 int rc;
2318
2319 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2320 TYPE_KEYMASTER_10);
2321 if (responseCode != ::NO_ERROR) {
2322 return responseCode;
2323 }
2324 keymaster_key_blob_t key;
2325 key.key_material_size = keyBlob.getLength();
2326 key.key_material = keyBlob.getValue();
2327 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2328 keymaster_key_characteristics_t *out = NULL;
2329 if (!dev->get_key_characteristics) {
2330 ALOGW("device does not implement get_key_characteristics");
2331 return KM_ERROR_UNIMPLEMENTED;
2332 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002333 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002334 if (out) {
2335 outCharacteristics->characteristics = *out;
2336 free(out);
2337 }
2338 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002339 }
2340
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002341 int32_t importKey(const String16& name, const KeymasterArguments& params,
2342 keymaster_key_format_t format, const uint8_t *keyData,
2343 size_t keyLength, int uid, int flags,
2344 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002345 uid = getEffectiveUid(uid);
2346 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2347 flags & KEYSTORE_FLAG_ENCRYPTED);
2348 if (rc != ::NO_ERROR) {
2349 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002350 }
2351
Chad Brubaker9489b792015-04-14 11:01:45 -07002352 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002353 bool isFallback = false;
2354 keymaster_key_blob_t blob;
2355 keymaster_key_characteristics_t *out = NULL;
2356
2357 const keymaster1_device_t* device = mKeyStore->getDevice();
2358 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002359 std::vector<keymaster_key_param_t> opParams(params.params);
2360 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2361 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002362 if (device == NULL) {
2363 return ::SYSTEM_ERROR;
2364 }
2365 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2366 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002367 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002368 }
2369 if (rc && fallback->import_key != NULL) {
2370 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002371 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002372 }
2373 if (out) {
2374 if (outCharacteristics) {
2375 outCharacteristics->characteristics = *out;
2376 } else {
2377 keymaster_free_characteristics(out);
2378 }
2379 free(out);
2380 }
2381 if (rc) {
2382 return rc;
2383 }
2384
2385 String8 name8(name);
2386 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2387
2388 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2389 keyBlob.setFallback(isFallback);
2390 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2391
2392 free((void*) blob.key_material);
2393
Chad Brubaker72593ee2015-05-12 10:42:00 -07002394 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002395 }
2396
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002397 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002398 const keymaster_blob_t* clientId,
2399 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002400
2401 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2402
2403 Blob keyBlob;
2404 String8 name8(name);
2405 int rc;
2406
2407 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2408 TYPE_KEYMASTER_10);
2409 if (responseCode != ::NO_ERROR) {
2410 result->resultCode = responseCode;
2411 return;
2412 }
2413 keymaster_key_blob_t key;
2414 key.key_material_size = keyBlob.getLength();
2415 key.key_material = keyBlob.getValue();
2416 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2417 if (!dev->export_key) {
2418 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2419 return;
2420 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002421 keymaster_blob_t output = {NULL, 0};
2422 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2423 result->exportData.reset(const_cast<uint8_t*>(output.data));
2424 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002425 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002426 }
2427
Chad Brubakerad6514a2015-04-09 14:00:26 -07002428
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002429 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002430 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002431 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002432 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2433 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2434 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2435 result->resultCode = ::PERMISSION_DENIED;
2436 return;
2437 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002438 if (!checkAllowedOperationParams(params.params)) {
2439 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2440 return;
2441 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002442 Blob keyBlob;
2443 String8 name8(name);
2444 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2445 TYPE_KEYMASTER_10);
2446 if (responseCode != ::NO_ERROR) {
2447 result->resultCode = responseCode;
2448 return;
2449 }
2450 keymaster_key_blob_t key;
2451 key.key_material_size = keyBlob.getLength();
2452 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002453 keymaster_operation_handle_t handle;
2454 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002455 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002456 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002457 Unique_keymaster_key_characteristics characteristics;
2458 characteristics.reset(new keymaster_key_characteristics_t);
2459 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2460 if (err) {
2461 result->resultCode = err;
2462 return;
2463 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002464 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002465 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002466 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002467 // If per-operation auth is needed we need to begin the operation and
2468 // the client will need to authorize that operation before calling
2469 // update. Any other auth issues stop here.
2470 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2471 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002472 return;
2473 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002474 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002475 // Add entropy to the device first.
2476 if (entropy) {
2477 if (dev->add_rng_entropy) {
2478 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2479 } else {
2480 err = KM_ERROR_UNIMPLEMENTED;
2481 }
2482 if (err) {
2483 result->resultCode = err;
2484 return;
2485 }
2486 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002487 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002488
Shawn Willden9221bff2015-06-18 18:23:54 -06002489 // Create a keyid for this key.
2490 keymaster::km_id_t keyid;
2491 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2492 ALOGE("Failed to create a key ID for authorization checking.");
2493 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2494 return;
2495 }
2496
2497 // Check that all key authorization policy requirements are met.
2498 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2499 key_auths.push_back(characteristics->sw_enforced);
2500 keymaster::AuthorizationSet operation_params(inParams);
2501 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2502 0 /* op_handle */,
2503 true /* is_begin_operation */);
2504 if (err) {
2505 result->resultCode = err;
2506 return;
2507 }
2508
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002509 keymaster_key_param_set_t outParams = {NULL, 0};
2510 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2511
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002512 // If there are too many operations abort the oldest operation that was
2513 // started as pruneable and try again.
2514 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2515 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2516 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002517
2518 // We mostly ignore errors from abort() below because all we care about is whether at
2519 // least one pruneable operation has been removed.
2520 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2521 int abort_error = abort(oldest);
2522 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2523 if (op_count_after >= op_count_before) {
2524 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2525 ALOGE("Failed to remove pruneable operation %p, error: %d",
2526 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002527 break;
2528 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002529 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002530 }
2531 if (err) {
2532 result->resultCode = err;
2533 return;
2534 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002535
Shawn Willden9221bff2015-06-18 18:23:54 -06002536 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2537 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002538 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002539 if (authToken) {
2540 mOperationMap.setOperationAuthToken(operationToken, authToken);
2541 }
2542 // Return the authentication lookup result. If this is a per operation
2543 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2544 // application should get an auth token using the handle before the
2545 // first call to update, which will fail if keystore hasn't received the
2546 // auth token.
2547 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002548 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002549 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002550 if (outParams.params) {
2551 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2552 free(outParams.params);
2553 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002554 }
2555
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002556 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2557 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002558 if (!checkAllowedOperationParams(params.params)) {
2559 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2560 return;
2561 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002562 const keymaster1_device_t* dev;
2563 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002564 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002565 keymaster::km_id_t keyid;
2566 const keymaster_key_characteristics_t* characteristics;
2567 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002568 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2569 return;
2570 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002571 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002572 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2573 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002574 result->resultCode = authResult;
2575 return;
2576 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002577 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2578 keymaster_blob_t input = {data, dataLength};
2579 size_t consumed = 0;
2580 keymaster_blob_t output = {NULL, 0};
2581 keymaster_key_param_set_t outParams = {NULL, 0};
2582
Shawn Willden9221bff2015-06-18 18:23:54 -06002583 // Check that all key authorization policy requirements are met.
2584 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2585 key_auths.push_back(characteristics->sw_enforced);
2586 keymaster::AuthorizationSet operation_params(inParams);
2587 result->resultCode =
2588 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2589 operation_params, handle,
2590 false /* is_begin_operation */);
2591 if (result->resultCode) {
2592 return;
2593 }
2594
Chad Brubaker57e106d2015-06-01 12:59:00 -07002595 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2596 &output);
2597 result->data.reset(const_cast<uint8_t*>(output.data));
2598 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002599 result->inputConsumed = consumed;
2600 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002601 if (outParams.params) {
2602 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2603 free(outParams.params);
2604 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002605 }
2606
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002607 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002608 const uint8_t* signature, size_t signatureLength,
2609 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002610 if (!checkAllowedOperationParams(params.params)) {
2611 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2612 return;
2613 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002614 const keymaster1_device_t* dev;
2615 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002616 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002617 keymaster::km_id_t keyid;
2618 const keymaster_key_characteristics_t* characteristics;
2619 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002620 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2621 return;
2622 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002623 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002624 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2625 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002626 result->resultCode = authResult;
2627 return;
2628 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002629 keymaster_error_t err;
2630 if (entropy) {
2631 if (dev->add_rng_entropy) {
2632 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2633 } else {
2634 err = KM_ERROR_UNIMPLEMENTED;
2635 }
2636 if (err) {
2637 result->resultCode = err;
2638 return;
2639 }
2640 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002641
Chad Brubaker57e106d2015-06-01 12:59:00 -07002642 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2643 keymaster_blob_t input = {signature, signatureLength};
2644 keymaster_blob_t output = {NULL, 0};
2645 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002646
2647 // Check that all key authorization policy requirements are met.
2648 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2649 key_auths.push_back(characteristics->sw_enforced);
2650 keymaster::AuthorizationSet operation_params(inParams);
2651 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2652 handle, false /* is_begin_operation */);
2653 if (err) {
2654 result->resultCode = err;
2655 return;
2656 }
2657
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002658 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002659 // Remove the operation regardless of the result
2660 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002661 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002662
2663 result->data.reset(const_cast<uint8_t*>(output.data));
2664 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002665 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002666 if (outParams.params) {
2667 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2668 free(outParams.params);
2669 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002670 }
2671
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002672 int32_t abort(const sp<IBinder>& token) {
2673 const keymaster1_device_t* dev;
2674 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002675 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002676 keymaster::km_id_t keyid;
2677 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002678 return KM_ERROR_INVALID_OPERATION_HANDLE;
2679 }
2680 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002681 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002682 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002683 rc = KM_ERROR_UNIMPLEMENTED;
2684 } else {
2685 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002686 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002687 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002688 if (rc) {
2689 return rc;
2690 }
2691 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002692 }
2693
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002694 bool isOperationAuthorized(const sp<IBinder>& token) {
2695 const keymaster1_device_t* dev;
2696 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002697 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002698 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002699 keymaster::km_id_t keyid;
2700 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002701 return false;
2702 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002703 const hw_auth_token_t* authToken = NULL;
2704 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002705 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002706 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2707 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002708 }
2709
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002710 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002711 if (!checkBinderPermission(P_ADD_AUTH)) {
2712 ALOGW("addAuthToken: permission denied for %d",
2713 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002714 return ::PERMISSION_DENIED;
2715 }
2716 if (length != sizeof(hw_auth_token_t)) {
2717 return KM_ERROR_INVALID_ARGUMENT;
2718 }
2719 hw_auth_token_t* authToken = new hw_auth_token_t;
2720 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2721 // The table takes ownership of authToken.
2722 mAuthTokenTable.AddAuthenticationToken(authToken);
2723 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002724 }
2725
Kenny Root07438c82012-11-02 15:41:02 -07002726private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002727 static const int32_t UID_SELF = -1;
2728
2729 /**
2730 * Get the effective target uid for a binder operation that takes an
2731 * optional uid as the target.
2732 */
2733 inline uid_t getEffectiveUid(int32_t targetUid) {
2734 if (targetUid == UID_SELF) {
2735 return IPCThreadState::self()->getCallingUid();
2736 }
2737 return static_cast<uid_t>(targetUid);
2738 }
2739
2740 /**
2741 * Check if the caller of the current binder method has the required
2742 * permission and if acting on other uids the grants to do so.
2743 */
2744 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2745 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2746 pid_t spid = IPCThreadState::self()->getCallingPid();
2747 if (!has_permission(callingUid, permission, spid)) {
2748 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2749 return false;
2750 }
2751 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2752 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2753 return false;
2754 }
2755 return true;
2756 }
2757
2758 /**
2759 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002760 * permission and the target uid is the caller or the caller is system.
2761 */
2762 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2763 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2764 pid_t spid = IPCThreadState::self()->getCallingPid();
2765 if (!has_permission(callingUid, permission, spid)) {
2766 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2767 return false;
2768 }
2769 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2770 }
2771
2772 /**
2773 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002774 * permission or the target of the operation is the caller's uid. This is
2775 * for operation where the permission is only for cross-uid activity and all
2776 * uids are allowed to act on their own (ie: clearing all entries for a
2777 * given uid).
2778 */
2779 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2780 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2781 if (getEffectiveUid(targetUid) == callingUid) {
2782 return true;
2783 } else {
2784 return checkBinderPermission(permission, targetUid);
2785 }
2786 }
2787
2788 /**
2789 * Helper method to check that the caller has the required permission as
2790 * well as the keystore is in the unlocked state if checkUnlocked is true.
2791 *
2792 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2793 * otherwise the state of keystore when not unlocked and checkUnlocked is
2794 * true.
2795 */
2796 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2797 bool checkUnlocked = true) {
2798 if (!checkBinderPermission(permission, targetUid)) {
2799 return ::PERMISSION_DENIED;
2800 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002801 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002802 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2803 return state;
2804 }
2805
2806 return ::NO_ERROR;
2807
2808 }
2809
Kenny Root9d45d1c2013-02-14 10:32:30 -08002810 inline bool isKeystoreUnlocked(State state) {
2811 switch (state) {
2812 case ::STATE_NO_ERROR:
2813 return true;
2814 case ::STATE_UNINITIALIZED:
2815 case ::STATE_LOCKED:
2816 return false;
2817 }
2818 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002819 }
2820
Chad Brubaker67d2a502015-03-11 17:21:18 +00002821 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002822 const int32_t device_api = device->common.module->module_api_version;
2823 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2824 switch (keyType) {
2825 case TYPE_RSA:
2826 case TYPE_DSA:
2827 case TYPE_EC:
2828 return true;
2829 default:
2830 return false;
2831 }
2832 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2833 switch (keyType) {
2834 case TYPE_RSA:
2835 return true;
2836 case TYPE_DSA:
2837 return device->flags & KEYMASTER_SUPPORTS_DSA;
2838 case TYPE_EC:
2839 return device->flags & KEYMASTER_SUPPORTS_EC;
2840 default:
2841 return false;
2842 }
2843 } else {
2844 return keyType == TYPE_RSA;
2845 }
2846 }
2847
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002848 /**
2849 * Check that all keymaster_key_param_t's provided by the application are
2850 * allowed. Any parameter that keystore adds itself should be disallowed here.
2851 */
2852 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2853 for (auto param: params) {
2854 switch (param.tag) {
2855 case KM_TAG_AUTH_TOKEN:
2856 return false;
2857 default:
2858 break;
2859 }
2860 }
2861 return true;
2862 }
2863
2864 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2865 const keymaster1_device_t* dev,
2866 const std::vector<keymaster_key_param_t>& params,
2867 keymaster_key_characteristics_t* out) {
2868 UniquePtr<keymaster_blob_t> appId;
2869 UniquePtr<keymaster_blob_t> appData;
2870 for (auto param : params) {
2871 if (param.tag == KM_TAG_APPLICATION_ID) {
2872 appId.reset(new keymaster_blob_t);
2873 appId->data = param.blob.data;
2874 appId->data_length = param.blob.data_length;
2875 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2876 appData.reset(new keymaster_blob_t);
2877 appData->data = param.blob.data;
2878 appData->data_length = param.blob.data_length;
2879 }
2880 }
2881 keymaster_key_characteristics_t* result = NULL;
2882 if (!dev->get_key_characteristics) {
2883 return KM_ERROR_UNIMPLEMENTED;
2884 }
2885 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2886 appData.get(), &result);
2887 if (result) {
2888 *out = *result;
2889 free(result);
2890 }
2891 return error;
2892 }
2893
2894 /**
2895 * Get the auth token for this operation from the auth token table.
2896 *
2897 * Returns ::NO_ERROR if the auth token was set or none was required.
2898 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2899 * authorization token exists for that operation and
2900 * failOnTokenMissing is false.
2901 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2902 * token for the operation
2903 */
2904 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2905 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002906 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002907 const hw_auth_token_t** authToken,
2908 bool failOnTokenMissing = true) {
2909
2910 std::vector<keymaster_key_param_t> allCharacteristics;
2911 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2912 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2913 }
2914 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2915 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2916 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002917 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
2918 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002919 switch (err) {
2920 case keymaster::AuthTokenTable::OK:
2921 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2922 return ::NO_ERROR;
2923 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2924 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2925 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2926 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2927 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2928 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2929 (int32_t) ::OP_AUTH_NEEDED;
2930 default:
2931 ALOGE("Unexpected FindAuthorization return value %d", err);
2932 return KM_ERROR_INVALID_ARGUMENT;
2933 }
2934 }
2935
2936 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2937 const hw_auth_token_t* token) {
2938 if (token) {
2939 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2940 reinterpret_cast<const uint8_t*>(token),
2941 sizeof(hw_auth_token_t)));
2942 }
2943 }
2944
2945 /**
2946 * Add the auth token for the operation to the param list if the operation
2947 * requires authorization. Uses the cached result in the OperationMap if available
2948 * otherwise gets the token from the AuthTokenTable and caches the result.
2949 *
2950 * Returns ::NO_ERROR if the auth token was added or not needed.
2951 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2952 * authenticated.
2953 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2954 * operation token.
2955 */
2956 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2957 std::vector<keymaster_key_param_t>* params) {
2958 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002959 mOperationMap.getOperationAuthToken(token, &authToken);
2960 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002961 const keymaster1_device_t* dev;
2962 keymaster_operation_handle_t handle;
2963 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002964 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002965 keymaster::km_id_t keyid;
2966 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
2967 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002968 return KM_ERROR_INVALID_OPERATION_HANDLE;
2969 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002970 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002971 if (result != ::NO_ERROR) {
2972 return result;
2973 }
2974 if (authToken) {
2975 mOperationMap.setOperationAuthToken(token, authToken);
2976 }
2977 }
2978 addAuthToParams(params, authToken);
2979 return ::NO_ERROR;
2980 }
2981
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002982 /**
2983 * Translate a result value to a legacy return value. All keystore errors are
2984 * preserved and keymaster errors become SYSTEM_ERRORs
2985 */
2986 inline int32_t translateResultToLegacyResult(int32_t result) {
2987 if (result > 0) {
2988 return result;
2989 }
2990 return ::SYSTEM_ERROR;
2991 }
2992
2993 void addLegacyKeyAuthorizations(std::vector<keymaster_key_param_t>& params) {
2994 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
2995 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
2996 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
2997 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
2998 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
2999 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3000 params.push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
3001 params.push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
3002 params.push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
3003 params.push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
3004 params.push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
3005 uint64_t now = keymaster::java_time(time(NULL));
3006 params.push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
3007 }
3008
3009 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3010 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3011 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3012 return &characteristics->hw_enforced.params[i];
3013 }
3014 }
3015 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3016 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3017 return &characteristics->sw_enforced.params[i];
3018 }
3019 }
3020 return NULL;
3021 }
3022
3023 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3024 // All legacy keys are DIGEST_NONE/PAD_NONE.
3025 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3026 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3027
3028 // Look up the algorithm of the key.
3029 KeyCharacteristics characteristics;
3030 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3031 if (rc != ::NO_ERROR) {
3032 ALOGE("Failed to get key characteristics");
3033 return;
3034 }
3035 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3036 if (!algorithm) {
3037 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3038 return;
3039 }
3040 params.push_back(*algorithm);
3041 }
3042
3043 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3044 uint8_t** out, size_t* outLength, const uint8_t* signature,
3045 size_t signatureLength, keymaster_purpose_t purpose) {
3046
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003047 std::basic_stringstream<uint8_t> outBuffer;
3048 OperationResult result;
3049 KeymasterArguments inArgs;
3050 addLegacyBeginParams(name, inArgs.params);
3051 sp<IBinder> appToken(new BBinder);
3052 sp<IBinder> token;
3053
3054 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3055 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003056 if (result.resultCode == ::KEY_NOT_FOUND) {
3057 ALOGW("Key not found");
3058 } else {
3059 ALOGW("Error in begin: %d", result.resultCode);
3060 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003061 return translateResultToLegacyResult(result.resultCode);
3062 }
3063 inArgs.params.clear();
3064 token = result.token;
3065 size_t consumed = 0;
3066 size_t lastConsumed = 0;
3067 do {
3068 update(token, inArgs, data + consumed, length - consumed, &result);
3069 if (result.resultCode != ResponseCode::NO_ERROR) {
3070 ALOGW("Error in update: %d", result.resultCode);
3071 return translateResultToLegacyResult(result.resultCode);
3072 }
3073 if (out) {
3074 outBuffer.write(result.data.get(), result.dataLength);
3075 }
3076 lastConsumed = result.inputConsumed;
3077 consumed += lastConsumed;
3078 } while (consumed < length && lastConsumed > 0);
3079
3080 if (consumed != length) {
3081 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3082 return ::SYSTEM_ERROR;
3083 }
3084
3085 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3086 if (result.resultCode != ResponseCode::NO_ERROR) {
3087 ALOGW("Error in finish: %d", result.resultCode);
3088 return translateResultToLegacyResult(result.resultCode);
3089 }
3090 if (out) {
3091 outBuffer.write(result.data.get(), result.dataLength);
3092 }
3093
3094 if (out) {
3095 auto buf = outBuffer.str();
3096 *out = new uint8_t[buf.size()];
3097 memcpy(*out, buf.c_str(), buf.size());
3098 *outLength = buf.size();
3099 }
3100
3101 return ::NO_ERROR;
3102 }
3103
Kenny Root07438c82012-11-02 15:41:02 -07003104 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003105 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003106 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003107 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003108};
3109
3110}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003111
3112int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003113 if (argc < 2) {
3114 ALOGE("A directory must be specified!");
3115 return 1;
3116 }
3117 if (chdir(argv[1]) == -1) {
3118 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3119 return 1;
3120 }
3121
3122 Entropy entropy;
3123 if (!entropy.open()) {
3124 return 1;
3125 }
Kenny Root70e3a862012-02-15 17:20:23 -08003126
Chad Brubakerbd07a232015-06-01 10:44:27 -07003127 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003128 if (keymaster_device_initialize(&dev)) {
3129 ALOGE("keystore keymaster could not be initialized; exiting");
3130 return 1;
3131 }
3132
Chad Brubaker67d2a502015-03-11 17:21:18 +00003133 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003134 if (fallback_keymaster_device_initialize(&fallback)) {
3135 ALOGE("software keymaster could not be initialized; exiting");
3136 return 1;
3137 }
3138
Riley Spahneaabae92014-06-30 12:39:52 -07003139 ks_is_selinux_enabled = is_selinux_enabled();
3140 if (ks_is_selinux_enabled) {
3141 union selinux_callback cb;
3142 cb.func_log = selinux_log_callback;
3143 selinux_set_callback(SELINUX_CB_LOG, cb);
3144 if (getcon(&tctx) != 0) {
3145 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3146 return -1;
3147 }
3148 } else {
3149 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3150 }
3151
Chad Brubakerbd07a232015-06-01 10:44:27 -07003152 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003153 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003154 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3155 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3156 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3157 if (ret != android::OK) {
3158 ALOGE("Couldn't register binder service!");
3159 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003160 }
Kenny Root07438c82012-11-02 15:41:02 -07003161
3162 /*
3163 * We're the only thread in existence, so we're just going to process
3164 * Binder transaction as a single-threaded program.
3165 */
3166 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003167
3168 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003169 return 1;
3170}