blob: 609a578c210afbcc0fd50ca2216574e6f80e992e [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:
Chad Brubaker803f37f2015-07-29 13:53:36 -0700508 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700509 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800510 memset(&mBlob, 0, sizeof(mBlob));
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700511 if (valueLength > VALUE_SIZE) {
512 valueLength = VALUE_SIZE;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700513 ALOGW("Provided blob length too large");
514 }
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700515 if (infoLength + valueLength > VALUE_SIZE) {
516 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700517 ALOGW("Provided info length too large");
518 }
Kenny Roota91203b2012-02-15 15:00:46 -0800519 mBlob.length = valueLength;
520 memcpy(mBlob.value, value, valueLength);
521
522 mBlob.info = infoLength;
523 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700524
Kenny Root07438c82012-11-02 15:41:02 -0700525 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700526 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700527
Kenny Rootee8068b2013-10-07 09:49:15 -0700528 if (type == TYPE_MASTER_KEY) {
529 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
530 } else {
531 mBlob.flags = KEYSTORE_FLAG_NONE;
532 }
Kenny Roota91203b2012-02-15 15:00:46 -0800533 }
534
535 Blob(blob b) {
536 mBlob = b;
537 }
538
Alex Klyubin1773b442015-02-20 12:33:33 -0800539 Blob() {
540 memset(&mBlob, 0, sizeof(mBlob));
541 }
Kenny Roota91203b2012-02-15 15:00:46 -0800542
Kenny Root51878182012-03-13 12:53:19 -0700543 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800544 return mBlob.value;
545 }
546
Kenny Root51878182012-03-13 12:53:19 -0700547 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800548 return mBlob.length;
549 }
550
Kenny Root51878182012-03-13 12:53:19 -0700551 const uint8_t* getInfo() const {
552 return mBlob.value + mBlob.length;
553 }
554
555 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800556 return mBlob.info;
557 }
558
Kenny Root822c3a92012-03-23 16:34:39 -0700559 uint8_t getVersion() const {
560 return mBlob.version;
561 }
562
Kenny Rootf9119d62013-04-03 09:22:15 -0700563 bool isEncrypted() const {
564 if (mBlob.version < 2) {
565 return true;
566 }
567
568 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
569 }
570
571 void setEncrypted(bool encrypted) {
572 if (encrypted) {
573 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
574 } else {
575 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
576 }
577 }
578
Kenny Root17208e02013-09-04 13:56:03 -0700579 bool isFallback() const {
580 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
581 }
582
583 void setFallback(bool fallback) {
584 if (fallback) {
585 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
586 } else {
587 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
588 }
589 }
590
Kenny Root822c3a92012-03-23 16:34:39 -0700591 void setVersion(uint8_t version) {
592 mBlob.version = version;
593 }
594
595 BlobType getType() const {
596 return BlobType(mBlob.type);
597 }
598
599 void setType(BlobType type) {
600 mBlob.type = uint8_t(type);
601 }
602
Kenny Rootf9119d62013-04-03 09:22:15 -0700603 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
604 ALOGV("writing blob %s", filename);
605 if (isEncrypted()) {
606 if (state != STATE_NO_ERROR) {
607 ALOGD("couldn't insert encrypted blob while not unlocked");
608 return LOCKED;
609 }
610
611 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
612 ALOGW("Could not read random data for: %s", filename);
613 return SYSTEM_ERROR;
614 }
Kenny Roota91203b2012-02-15 15:00:46 -0800615 }
616
617 // data includes the value and the value's length
618 size_t dataLength = mBlob.length + sizeof(mBlob.length);
619 // pad data to the AES_BLOCK_SIZE
620 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
621 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
622 // encrypted data includes the digest value
623 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
624 // move info after space for padding
625 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
626 // zero padding area
627 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
628
629 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800630
Kenny Rootf9119d62013-04-03 09:22:15 -0700631 if (isEncrypted()) {
632 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800633
Kenny Rootf9119d62013-04-03 09:22:15 -0700634 uint8_t vector[AES_BLOCK_SIZE];
635 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
636 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
637 aes_key, vector, AES_ENCRYPT);
638 }
639
Kenny Roota91203b2012-02-15 15:00:46 -0800640 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
641 size_t fileLength = encryptedLength + headerLength + mBlob.info;
642
643 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800644 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
645 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
646 if (out < 0) {
647 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800648 return SYSTEM_ERROR;
649 }
650 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
651 if (close(out) != 0) {
652 return SYSTEM_ERROR;
653 }
654 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800655 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800656 unlink(tmpFileName);
657 return SYSTEM_ERROR;
658 }
Kenny Root150ca932012-11-14 14:29:02 -0800659 if (rename(tmpFileName, filename) == -1) {
660 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
661 return SYSTEM_ERROR;
662 }
663 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800664 }
665
Kenny Rootf9119d62013-04-03 09:22:15 -0700666 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
667 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800668 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
669 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800670 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
671 }
672 // fileLength may be less than sizeof(mBlob) since the in
673 // memory version has extra padding to tolerate rounding up to
674 // the AES_BLOCK_SIZE
675 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
676 if (close(in) != 0) {
677 return SYSTEM_ERROR;
678 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700679
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700680 if (fileLength == 0) {
681 return VALUE_CORRUPTED;
682 }
683
Kenny Rootf9119d62013-04-03 09:22:15 -0700684 if (isEncrypted() && (state != STATE_NO_ERROR)) {
685 return LOCKED;
686 }
687
Kenny Roota91203b2012-02-15 15:00:46 -0800688 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
689 if (fileLength < headerLength) {
690 return VALUE_CORRUPTED;
691 }
692
693 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700694 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800695 return VALUE_CORRUPTED;
696 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700697
698 ssize_t digestedLength;
699 if (isEncrypted()) {
700 if (encryptedLength % AES_BLOCK_SIZE != 0) {
701 return VALUE_CORRUPTED;
702 }
703
704 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
705 mBlob.vector, AES_DECRYPT);
706 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
707 uint8_t computedDigest[MD5_DIGEST_LENGTH];
708 MD5(mBlob.digested, digestedLength, computedDigest);
709 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
710 return VALUE_CORRUPTED;
711 }
712 } else {
713 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800714 }
715
716 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
717 mBlob.length = ntohl(mBlob.length);
718 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
719 return VALUE_CORRUPTED;
720 }
721 if (mBlob.info != 0) {
722 // move info from after padding to after data
723 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
724 }
Kenny Root07438c82012-11-02 15:41:02 -0700725 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800726 }
727
728private:
729 struct blob mBlob;
730};
731
Kenny Root655b9582013-04-04 08:37:42 -0700732class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800733public:
Kenny Root655b9582013-04-04 08:37:42 -0700734 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
735 asprintf(&mUserDir, "user_%u", mUserId);
736 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
737 }
738
739 ~UserState() {
740 free(mUserDir);
741 free(mMasterKeyFile);
742 }
743
744 bool initialize() {
745 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
746 ALOGE("Could not create directory '%s'", mUserDir);
747 return false;
748 }
749
750 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800751 setState(STATE_LOCKED);
752 } else {
753 setState(STATE_UNINITIALIZED);
754 }
Kenny Root70e3a862012-02-15 17:20:23 -0800755
Kenny Root655b9582013-04-04 08:37:42 -0700756 return true;
757 }
758
759 uid_t getUserId() const {
760 return mUserId;
761 }
762
763 const char* getUserDirName() const {
764 return mUserDir;
765 }
766
767 const char* getMasterKeyFileName() const {
768 return mMasterKeyFile;
769 }
770
771 void setState(State state) {
772 mState = state;
773 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
774 mRetry = MAX_RETRY;
775 }
Kenny Roota91203b2012-02-15 15:00:46 -0800776 }
777
Kenny Root51878182012-03-13 12:53:19 -0700778 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800779 return mState;
780 }
781
Kenny Root51878182012-03-13 12:53:19 -0700782 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800783 return mRetry;
784 }
785
Kenny Root655b9582013-04-04 08:37:42 -0700786 void zeroizeMasterKeysInMemory() {
787 memset(mMasterKey, 0, sizeof(mMasterKey));
788 memset(mSalt, 0, sizeof(mSalt));
789 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
790 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800791 }
792
Chad Brubaker96d6d782015-05-07 10:19:40 -0700793 bool deleteMasterKey() {
794 setState(STATE_UNINITIALIZED);
795 zeroizeMasterKeysInMemory();
796 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
797 }
798
Kenny Root655b9582013-04-04 08:37:42 -0700799 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
800 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800801 return SYSTEM_ERROR;
802 }
Kenny Root655b9582013-04-04 08:37:42 -0700803 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800804 if (response != NO_ERROR) {
805 return response;
806 }
807 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700808 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800809 }
810
Robin Lee4e865752014-08-19 17:37:55 +0100811 ResponseCode copyMasterKey(UserState* src) {
812 if (mState != STATE_UNINITIALIZED) {
813 return ::SYSTEM_ERROR;
814 }
815 if (src->getState() != STATE_NO_ERROR) {
816 return ::SYSTEM_ERROR;
817 }
818 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
819 setupMasterKeys();
820 return ::NO_ERROR;
821 }
822
Kenny Root655b9582013-04-04 08:37:42 -0700823 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800824 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
825 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
826 AES_KEY passwordAesKey;
827 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700828 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700829 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800830 }
831
Kenny Root655b9582013-04-04 08:37:42 -0700832 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
833 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800834 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800835 return SYSTEM_ERROR;
836 }
837
838 // we read the raw blob to just to get the salt to generate
839 // the AES key, then we create the Blob to use with decryptBlob
840 blob rawBlob;
841 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
842 if (close(in) != 0) {
843 return SYSTEM_ERROR;
844 }
845 // find salt at EOF if present, otherwise we have an old file
846 uint8_t* salt;
847 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
848 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
849 } else {
850 salt = NULL;
851 }
852 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
853 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
854 AES_KEY passwordAesKey;
855 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
856 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700857 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
858 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800859 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700860 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800861 }
862 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
863 // if salt was missing, generate one and write a new master key file with the salt.
864 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700865 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800866 return SYSTEM_ERROR;
867 }
Kenny Root655b9582013-04-04 08:37:42 -0700868 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800869 }
870 if (response == NO_ERROR) {
871 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
872 setupMasterKeys();
873 }
874 return response;
875 }
876 if (mRetry <= 0) {
877 reset();
878 return UNINITIALIZED;
879 }
880 --mRetry;
881 switch (mRetry) {
882 case 0: return WRONG_PASSWORD_0;
883 case 1: return WRONG_PASSWORD_1;
884 case 2: return WRONG_PASSWORD_2;
885 case 3: return WRONG_PASSWORD_3;
886 default: return WRONG_PASSWORD_3;
887 }
888 }
889
Kenny Root655b9582013-04-04 08:37:42 -0700890 AES_KEY* getEncryptionKey() {
891 return &mMasterKeyEncryption;
892 }
893
894 AES_KEY* getDecryptionKey() {
895 return &mMasterKeyDecryption;
896 }
897
Kenny Roota91203b2012-02-15 15:00:46 -0800898 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700899 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800900 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700901 // If the directory doesn't exist then nothing to do.
902 if (errno == ENOENT) {
903 return true;
904 }
Kenny Root655b9582013-04-04 08:37:42 -0700905 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800906 return false;
907 }
Kenny Root655b9582013-04-04 08:37:42 -0700908
909 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800910 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700911 // skip . and ..
912 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700913 continue;
914 }
915
916 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800917 }
918 closedir(dir);
919 return true;
920 }
921
Kenny Root655b9582013-04-04 08:37:42 -0700922private:
923 static const int MASTER_KEY_SIZE_BYTES = 16;
924 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
925
926 static const int MAX_RETRY = 4;
927 static const size_t SALT_SIZE = 16;
928
929 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
930 uint8_t* salt) {
931 size_t saltSize;
932 if (salt != NULL) {
933 saltSize = SALT_SIZE;
934 } else {
935 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
936 salt = (uint8_t*) "keystore";
937 // sizeof = 9, not strlen = 8
938 saltSize = sizeof("keystore");
939 }
940
941 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
942 saltSize, 8192, keySize, key);
943 }
944
945 bool generateSalt(Entropy* entropy) {
946 return entropy->generate_random_data(mSalt, sizeof(mSalt));
947 }
948
949 bool generateMasterKey(Entropy* entropy) {
950 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
951 return false;
952 }
953 if (!generateSalt(entropy)) {
954 return false;
955 }
956 return true;
957 }
958
959 void setupMasterKeys() {
960 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
961 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
962 setState(STATE_NO_ERROR);
963 }
964
965 uid_t mUserId;
966
967 char* mUserDir;
968 char* mMasterKeyFile;
969
970 State mState;
971 int8_t mRetry;
972
973 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
974 uint8_t mSalt[SALT_SIZE];
975
976 AES_KEY mMasterKeyEncryption;
977 AES_KEY mMasterKeyDecryption;
978};
979
980typedef struct {
981 uint32_t uid;
982 const uint8_t* filename;
983} grant_t;
984
985class KeyStore {
986public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000987 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700988 : mEntropy(entropy)
989 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800990 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700991 {
992 memset(&mMetaData, '\0', sizeof(mMetaData));
993 }
994
995 ~KeyStore() {
996 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
997 it != mGrants.end(); it++) {
998 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700999 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001000 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001001
1002 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1003 it != mMasterKeys.end(); it++) {
1004 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001005 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001006 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001007 }
1008
Chad Brubaker67d2a502015-03-11 17:21:18 +00001009 /**
1010 * Depending on the hardware keymaster version is this may return a
1011 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1012 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1013 * be guarded by a check on the device's version.
1014 */
1015 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001016 return mDevice;
1017 }
1018
Chad Brubaker67d2a502015-03-11 17:21:18 +00001019 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001020 return mFallbackDevice;
1021 }
1022
Chad Brubaker67d2a502015-03-11 17:21:18 +00001023 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001024 return blob.isFallback() ? mFallbackDevice: mDevice;
1025 }
1026
Kenny Root655b9582013-04-04 08:37:42 -07001027 ResponseCode initialize() {
1028 readMetaData();
1029 if (upgradeKeystore()) {
1030 writeMetaData();
1031 }
1032
1033 return ::NO_ERROR;
1034 }
1035
Chad Brubaker72593ee2015-05-12 10:42:00 -07001036 State getState(uid_t userId) {
1037 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001038 }
1039
Chad Brubaker72593ee2015-05-12 10:42:00 -07001040 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1041 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001042 return userState->initialize(pw, mEntropy);
1043 }
1044
Chad Brubaker72593ee2015-05-12 10:42:00 -07001045 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1046 UserState *userState = getUserState(dstUser);
1047 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001048 return userState->copyMasterKey(initState);
1049 }
1050
Chad Brubaker72593ee2015-05-12 10:42:00 -07001051 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1052 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001053 return userState->writeMasterKey(pw, mEntropy);
1054 }
1055
Chad Brubaker72593ee2015-05-12 10:42:00 -07001056 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1057 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001058 return userState->readMasterKey(pw, mEntropy);
1059 }
1060
1061 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001062 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001063 encode_key(encoded, keyName);
1064 return android::String8(encoded);
1065 }
1066
1067 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001068 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001069 encode_key(encoded, keyName);
1070 return android::String8::format("%u_%s", uid, encoded);
1071 }
1072
1073 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001074 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001075 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001076 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001077 encoded);
1078 }
1079
Chad Brubaker96d6d782015-05-07 10:19:40 -07001080 /*
1081 * Delete entries owned by userId. If keepUnencryptedEntries is true
1082 * then only encrypted entries will be removed, otherwise all entries will
1083 * be removed.
1084 */
1085 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001086 android::String8 prefix("");
1087 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001088 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001089 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001090 return;
1091 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001092 for (uint32_t i = 0; i < aliases.size(); i++) {
1093 android::String8 filename(aliases[i]);
1094 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001095 getKeyName(filename).string());
1096 bool shouldDelete = true;
1097 if (keepUnenryptedEntries) {
1098 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001099 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001100
Chad Brubaker96d6d782015-05-07 10:19:40 -07001101 /* get can fail if the blob is encrypted and the state is
1102 * not unlocked, only skip deleting blobs that were loaded and
1103 * who are not encrypted. If there are blobs we fail to read for
1104 * other reasons err on the safe side and delete them since we
1105 * can't tell if they're encrypted.
1106 */
1107 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1108 }
1109 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001110 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001111 }
1112 }
1113 if (!userState->deleteMasterKey()) {
1114 ALOGE("Failed to delete user %d's master key", userId);
1115 }
1116 if (!keepUnenryptedEntries) {
1117 if(!userState->reset()) {
1118 ALOGE("Failed to remove user %d's directory", userId);
1119 }
1120 }
Kenny Root655b9582013-04-04 08:37:42 -07001121 }
1122
Chad Brubaker72593ee2015-05-12 10:42:00 -07001123 bool isEmpty(uid_t userId) const {
1124 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001125 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001126 return true;
1127 }
1128
1129 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001130 if (!dir) {
1131 return true;
1132 }
Kenny Root31e27462014-09-10 11:28:03 -07001133
Kenny Roota91203b2012-02-15 15:00:46 -08001134 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001135 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001136 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001137 // We only care about files.
1138 if (file->d_type != DT_REG) {
1139 continue;
1140 }
1141
1142 // Skip anything that starts with a "."
1143 if (file->d_name[0] == '.') {
1144 continue;
1145 }
1146
Kenny Root31e27462014-09-10 11:28:03 -07001147 result = false;
1148 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001149 }
1150 closedir(dir);
1151 return result;
1152 }
1153
Chad Brubaker72593ee2015-05-12 10:42:00 -07001154 void lock(uid_t userId) {
1155 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001156 userState->zeroizeMasterKeysInMemory();
1157 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001158 }
1159
Chad Brubaker72593ee2015-05-12 10:42:00 -07001160 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1161 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001162 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1163 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001164 if (rc != NO_ERROR) {
1165 return rc;
1166 }
1167
1168 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001169 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001170 /* If we upgrade the key, we need to write it to disk again. Then
1171 * it must be read it again since the blob is encrypted each time
1172 * it's written.
1173 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001174 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1175 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001176 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1177 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001178 return rc;
1179 }
1180 }
Kenny Root822c3a92012-03-23 16:34:39 -07001181 }
1182
Kenny Root17208e02013-09-04 13:56:03 -07001183 /*
1184 * This will upgrade software-backed keys to hardware-backed keys when
1185 * the HAL for the device supports the newer key types.
1186 */
1187 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1188 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1189 && keyBlob->isFallback()) {
1190 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001191 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001192
1193 // The HAL allowed the import, reget the key to have the "fresh"
1194 // version.
1195 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001196 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001197 }
1198 }
1199
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001200 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1201 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001202 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001203 rc = this->put(filename, keyBlob, userId);
Zhen Kong52415c52015-09-30 18:42:58 -07001204 if (rc != NO_ERROR) {
1205 return rc;
1206 }
1207
1208 rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1209 userState->getState());
1210 if (rc != NO_ERROR) {
1211 return rc;
1212 }
Chad Brubaker3cc40122015-06-04 13:49:44 -07001213 }
1214
Kenny Rootd53bc922013-03-21 14:10:15 -07001215 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001216 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1217 return KEY_NOT_FOUND;
1218 }
1219
1220 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001221 }
1222
Chad Brubaker72593ee2015-05-12 10:42:00 -07001223 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1224 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001225 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1226 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001227 }
1228
Chad Brubaker72593ee2015-05-12 10:42:00 -07001229 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001230 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001231 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001232 if (rc == ::VALUE_CORRUPTED) {
1233 // The file is corrupt, the best we can do is rm it.
1234 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1235 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001236 if (rc != ::NO_ERROR) {
1237 return rc;
1238 }
1239
1240 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1241 // A device doesn't have to implement delete_keypair.
1242 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1243 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1244 rc = ::SYSTEM_ERROR;
1245 }
1246 }
1247 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001248 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1249 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1250 if (dev->delete_key) {
1251 keymaster_key_blob_t blob;
1252 blob.key_material = keyBlob.getValue();
1253 blob.key_material_size = keyBlob.getLength();
1254 dev->delete_key(dev, &blob);
1255 }
1256 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001257 if (rc != ::NO_ERROR) {
1258 return rc;
1259 }
1260
1261 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1262 }
1263
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001264 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001265 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001266
Chad Brubaker72593ee2015-05-12 10:42:00 -07001267 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001268 size_t n = prefix.length();
1269
1270 DIR* dir = opendir(userState->getUserDirName());
1271 if (!dir) {
1272 ALOGW("can't open directory for user: %s", strerror(errno));
1273 return ::SYSTEM_ERROR;
1274 }
1275
1276 struct dirent* file;
1277 while ((file = readdir(dir)) != NULL) {
1278 // We only care about files.
1279 if (file->d_type != DT_REG) {
1280 continue;
1281 }
1282
1283 // Skip anything that starts with a "."
1284 if (file->d_name[0] == '.') {
1285 continue;
1286 }
1287
1288 if (!strncmp(prefix.string(), file->d_name, n)) {
1289 const char* p = &file->d_name[n];
1290 size_t plen = strlen(p);
1291
1292 size_t extra = decode_key_length(p, plen);
1293 char *match = (char*) malloc(extra + 1);
1294 if (match != NULL) {
1295 decode_key(match, p, plen);
1296 matches->push(android::String16(match, extra));
1297 free(match);
1298 } else {
1299 ALOGW("could not allocate match of size %zd", extra);
1300 }
1301 }
1302 }
1303 closedir(dir);
1304 return ::NO_ERROR;
1305 }
1306
Kenny Root07438c82012-11-02 15:41:02 -07001307 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001308 const grant_t* existing = getGrant(filename, granteeUid);
1309 if (existing == NULL) {
1310 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001311 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001312 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001313 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001314 }
1315 }
1316
Kenny Root07438c82012-11-02 15:41:02 -07001317 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001318 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1319 it != mGrants.end(); it++) {
1320 grant_t* grant = *it;
1321 if (grant->uid == granteeUid
1322 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1323 mGrants.erase(it);
1324 return true;
1325 }
Kenny Root70e3a862012-02-15 17:20:23 -08001326 }
Kenny Root70e3a862012-02-15 17:20:23 -08001327 return false;
1328 }
1329
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001330 bool hasGrant(const char* filename, const uid_t uid) const {
1331 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001332 }
1333
Chad Brubaker72593ee2015-05-12 10:42:00 -07001334 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001335 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001336 uint8_t* data;
1337 size_t dataLength;
1338 int rc;
1339
1340 if (mDevice->import_keypair == NULL) {
1341 ALOGE("Keymaster doesn't support import!");
1342 return SYSTEM_ERROR;
1343 }
1344
Kenny Root17208e02013-09-04 13:56:03 -07001345 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001346 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001347 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001348 /*
1349 * Maybe the device doesn't support this type of key. Try to use the
1350 * software fallback keymaster implementation. This is a little bit
1351 * lazier than checking the PKCS#8 key type, but the software
1352 * implementation will do that anyway.
1353 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001354 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001355 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001356
1357 if (rc) {
1358 ALOGE("Error while importing keypair: %d", rc);
1359 return SYSTEM_ERROR;
1360 }
Kenny Root822c3a92012-03-23 16:34:39 -07001361 }
1362
1363 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1364 free(data);
1365
Kenny Rootf9119d62013-04-03 09:22:15 -07001366 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001367 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001368
Chad Brubaker72593ee2015-05-12 10:42:00 -07001369 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001370 }
1371
Kenny Root1b0e3932013-09-05 13:06:32 -07001372 bool isHardwareBacked(const android::String16& keyType) const {
1373 if (mDevice == NULL) {
1374 ALOGW("can't get keymaster device");
1375 return false;
1376 }
1377
1378 if (sRSAKeyType == keyType) {
1379 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1380 } else {
1381 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1382 && (mDevice->common.module->module_api_version
1383 >= KEYMASTER_MODULE_API_VERSION_0_2);
1384 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001385 }
1386
Kenny Root655b9582013-04-04 08:37:42 -07001387 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1388 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001389 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001390 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001391
Chad Brubaker72593ee2015-05-12 10:42:00 -07001392 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001393 if (responseCode == NO_ERROR) {
1394 return responseCode;
1395 }
1396
1397 // If this is one of the legacy UID->UID mappings, use it.
1398 uid_t euid = get_keystore_euid(uid);
1399 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001400 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001401 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001402 if (responseCode == NO_ERROR) {
1403 return responseCode;
1404 }
1405 }
1406
1407 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001408 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001409 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001410 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001411 if (end[0] != '_' || end[1] == 0) {
1412 return KEY_NOT_FOUND;
1413 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001414 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001415 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001416 if (!hasGrant(filepath8.string(), uid)) {
1417 return responseCode;
1418 }
1419
1420 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001421 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001422 }
1423
1424 /**
1425 * Returns any existing UserState or creates it if it doesn't exist.
1426 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001427 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001428 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1429 it != mMasterKeys.end(); it++) {
1430 UserState* state = *it;
1431 if (state->getUserId() == userId) {
1432 return state;
1433 }
1434 }
1435
1436 UserState* userState = new UserState(userId);
1437 if (!userState->initialize()) {
1438 /* There's not much we can do if initialization fails. Trying to
1439 * unlock the keystore for that user will fail as well, so any
1440 * subsequent request for this user will just return SYSTEM_ERROR.
1441 */
1442 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1443 }
1444 mMasterKeys.add(userState);
1445 return userState;
1446 }
1447
1448 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001449 * Returns any existing UserState or creates it if it doesn't exist.
1450 */
1451 UserState* getUserStateByUid(uid_t uid) {
1452 uid_t userId = get_user_id(uid);
1453 return getUserState(userId);
1454 }
1455
1456 /**
Kenny Root655b9582013-04-04 08:37:42 -07001457 * Returns NULL if the UserState doesn't already exist.
1458 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001459 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001460 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1461 it != mMasterKeys.end(); it++) {
1462 UserState* state = *it;
1463 if (state->getUserId() == userId) {
1464 return state;
1465 }
1466 }
1467
1468 return NULL;
1469 }
1470
Chad Brubaker72593ee2015-05-12 10:42:00 -07001471 /**
1472 * Returns NULL if the UserState doesn't already exist.
1473 */
1474 const UserState* getUserStateByUid(uid_t uid) const {
1475 uid_t userId = get_user_id(uid);
1476 return getUserState(userId);
1477 }
1478
Kenny Roota91203b2012-02-15 15:00:46 -08001479private:
Kenny Root655b9582013-04-04 08:37:42 -07001480 static const char* sOldMasterKey;
1481 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001482 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001483 Entropy* mEntropy;
1484
Chad Brubaker67d2a502015-03-11 17:21:18 +00001485 keymaster1_device_t* mDevice;
1486 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001487
Kenny Root655b9582013-04-04 08:37:42 -07001488 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001489
Kenny Root655b9582013-04-04 08:37:42 -07001490 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001491
Kenny Root655b9582013-04-04 08:37:42 -07001492 typedef struct {
1493 uint32_t version;
1494 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001495
Kenny Root655b9582013-04-04 08:37:42 -07001496 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001497
Kenny Root655b9582013-04-04 08:37:42 -07001498 const grant_t* getGrant(const char* filename, uid_t uid) const {
1499 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1500 it != mGrants.end(); it++) {
1501 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001502 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001503 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001504 return grant;
1505 }
1506 }
Kenny Root70e3a862012-02-15 17:20:23 -08001507 return NULL;
1508 }
1509
Kenny Root822c3a92012-03-23 16:34:39 -07001510 /**
1511 * Upgrade code. This will upgrade the key from the current version
1512 * to whatever is newest.
1513 */
Kenny Root655b9582013-04-04 08:37:42 -07001514 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1515 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001516 bool updated = false;
1517 uint8_t version = oldVersion;
1518
1519 /* From V0 -> V1: All old types were unknown */
1520 if (version == 0) {
1521 ALOGV("upgrading to version 1 and setting type %d", type);
1522
1523 blob->setType(type);
1524 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001525 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001526 }
1527 version = 1;
1528 updated = true;
1529 }
1530
Kenny Rootf9119d62013-04-03 09:22:15 -07001531 /* From V1 -> V2: All old keys were encrypted */
1532 if (version == 1) {
1533 ALOGV("upgrading to version 2");
1534
1535 blob->setEncrypted(true);
1536 version = 2;
1537 updated = true;
1538 }
1539
Kenny Root822c3a92012-03-23 16:34:39 -07001540 /*
1541 * If we've updated, set the key blob to the right version
1542 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001543 */
Kenny Root822c3a92012-03-23 16:34:39 -07001544 if (updated) {
1545 ALOGV("updated and writing file %s", filename);
1546 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001547 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001548
1549 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001550 }
1551
1552 /**
1553 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1554 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1555 * Then it overwrites the original blob with the new blob
1556 * format that is returned from the keymaster.
1557 */
Kenny Root655b9582013-04-04 08:37:42 -07001558 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001559 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1560 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1561 if (b.get() == NULL) {
1562 ALOGE("Problem instantiating BIO");
1563 return SYSTEM_ERROR;
1564 }
1565
1566 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1567 if (pkey.get() == NULL) {
1568 ALOGE("Couldn't read old PEM file");
1569 return SYSTEM_ERROR;
1570 }
1571
1572 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1573 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1574 if (len < 0) {
1575 ALOGE("Couldn't measure PKCS#8 length");
1576 return SYSTEM_ERROR;
1577 }
1578
Kenny Root70c98892013-02-07 09:10:36 -08001579 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1580 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001581 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1582 ALOGE("Couldn't convert to PKCS#8");
1583 return SYSTEM_ERROR;
1584 }
1585
Chad Brubaker72593ee2015-05-12 10:42:00 -07001586 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001587 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001588 if (rc != NO_ERROR) {
1589 return rc;
1590 }
1591
Kenny Root655b9582013-04-04 08:37:42 -07001592 return get(filename, blob, TYPE_KEY_PAIR, uid);
1593 }
1594
1595 void readMetaData() {
1596 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1597 if (in < 0) {
1598 return;
1599 }
1600 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1601 if (fileLength != sizeof(mMetaData)) {
1602 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1603 sizeof(mMetaData));
1604 }
1605 close(in);
1606 }
1607
1608 void writeMetaData() {
1609 const char* tmpFileName = ".metadata.tmp";
1610 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1611 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1612 if (out < 0) {
1613 ALOGE("couldn't write metadata file: %s", strerror(errno));
1614 return;
1615 }
1616 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1617 if (fileLength != sizeof(mMetaData)) {
1618 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1619 sizeof(mMetaData));
1620 }
1621 close(out);
1622 rename(tmpFileName, sMetaDataFile);
1623 }
1624
1625 bool upgradeKeystore() {
1626 bool upgraded = false;
1627
1628 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001629 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001630
1631 // Initialize first so the directory is made.
1632 userState->initialize();
1633
1634 // Migrate the old .masterkey file to user 0.
1635 if (access(sOldMasterKey, R_OK) == 0) {
1636 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1637 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1638 return false;
1639 }
1640 }
1641
1642 // Initialize again in case we had a key.
1643 userState->initialize();
1644
1645 // Try to migrate existing keys.
1646 DIR* dir = opendir(".");
1647 if (!dir) {
1648 // Give up now; maybe we can upgrade later.
1649 ALOGE("couldn't open keystore's directory; something is wrong");
1650 return false;
1651 }
1652
1653 struct dirent* file;
1654 while ((file = readdir(dir)) != NULL) {
1655 // We only care about files.
1656 if (file->d_type != DT_REG) {
1657 continue;
1658 }
1659
1660 // Skip anything that starts with a "."
1661 if (file->d_name[0] == '.') {
1662 continue;
1663 }
1664
1665 // Find the current file's user.
1666 char* end;
1667 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1668 if (end[0] != '_' || end[1] == 0) {
1669 continue;
1670 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001671 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001672 if (otherUser->getUserId() != 0) {
1673 unlinkat(dirfd(dir), file->d_name, 0);
1674 }
1675
1676 // Rename the file into user directory.
1677 DIR* otherdir = opendir(otherUser->getUserDirName());
1678 if (otherdir == NULL) {
1679 ALOGW("couldn't open user directory for rename");
1680 continue;
1681 }
1682 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1683 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1684 }
1685 closedir(otherdir);
1686 }
1687 closedir(dir);
1688
1689 mMetaData.version = 1;
1690 upgraded = true;
1691 }
1692
1693 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001694 }
Kenny Roota91203b2012-02-15 15:00:46 -08001695};
1696
Kenny Root655b9582013-04-04 08:37:42 -07001697const char* KeyStore::sOldMasterKey = ".masterkey";
1698const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001699
Kenny Root1b0e3932013-09-05 13:06:32 -07001700const android::String16 KeyStore::sRSAKeyType("RSA");
1701
Kenny Root07438c82012-11-02 15:41:02 -07001702namespace android {
1703class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1704public:
1705 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001706 : mKeyStore(keyStore),
1707 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001708 {
Kenny Roota91203b2012-02-15 15:00:46 -08001709 }
Kenny Roota91203b2012-02-15 15:00:46 -08001710
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001711 void binderDied(const wp<IBinder>& who) {
1712 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1713 for (auto token: operations) {
1714 abort(token);
1715 }
Kenny Root822c3a92012-03-23 16:34:39 -07001716 }
Kenny Roota91203b2012-02-15 15:00:46 -08001717
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001718 int32_t getState(int32_t userId) {
1719 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001720 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001721 }
Kenny Roota91203b2012-02-15 15:00:46 -08001722
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001723 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001724 }
1725
Kenny Root07438c82012-11-02 15:41:02 -07001726 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001727 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001728 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001729 }
Kenny Root07438c82012-11-02 15:41:02 -07001730
Chad Brubaker9489b792015-04-14 11:01:45 -07001731 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001732 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001733 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001734
Kenny Root655b9582013-04-04 08:37:42 -07001735 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001736 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001737 if (responseCode != ::NO_ERROR) {
1738 *item = NULL;
1739 *itemLength = 0;
1740 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001741 }
Kenny Roota91203b2012-02-15 15:00:46 -08001742
Kenny Root07438c82012-11-02 15:41:02 -07001743 *item = (uint8_t*) malloc(keyBlob.getLength());
1744 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1745 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001746
Kenny Root07438c82012-11-02 15:41:02 -07001747 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001748 }
1749
Kenny Rootf9119d62013-04-03 09:22:15 -07001750 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1751 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001752 targetUid = getEffectiveUid(targetUid);
1753 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1754 flags & KEYSTORE_FLAG_ENCRYPTED);
1755 if (result != ::NO_ERROR) {
1756 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001757 }
1758
Kenny Root07438c82012-11-02 15:41:02 -07001759 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001760 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001761
1762 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001763 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1764
Chad Brubaker72593ee2015-05-12 10:42:00 -07001765 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001766 }
1767
Kenny Root49468902013-03-19 13:41:33 -07001768 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001769 targetUid = getEffectiveUid(targetUid);
1770 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001771 return ::PERMISSION_DENIED;
1772 }
Kenny Root07438c82012-11-02 15:41:02 -07001773 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001774 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001775 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001776 }
1777
Kenny Root49468902013-03-19 13:41:33 -07001778 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001779 targetUid = getEffectiveUid(targetUid);
1780 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001781 return ::PERMISSION_DENIED;
1782 }
1783
Kenny Root07438c82012-11-02 15:41:02 -07001784 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001785 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001786
Kenny Root655b9582013-04-04 08:37:42 -07001787 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001788 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1789 }
1790 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001791 }
1792
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001793 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001794 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001795 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001796 return ::PERMISSION_DENIED;
1797 }
Kenny Root07438c82012-11-02 15:41:02 -07001798 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001799 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001800
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001801 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001802 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001803 }
Kenny Root07438c82012-11-02 15:41:02 -07001804 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001805 }
1806
Kenny Root07438c82012-11-02 15:41:02 -07001807 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001808 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001809 return ::PERMISSION_DENIED;
1810 }
1811
Chad Brubaker9489b792015-04-14 11:01:45 -07001812 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001813 mKeyStore->resetUser(get_user_id(callingUid), false);
1814 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001815 }
1816
Chad Brubaker96d6d782015-05-07 10:19:40 -07001817 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001818 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001819 return ::PERMISSION_DENIED;
1820 }
Kenny Root70e3a862012-02-15 17:20:23 -08001821
Kenny Root07438c82012-11-02 15:41:02 -07001822 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001823 // Flush the auth token table to prevent stale tokens from sticking
1824 // around.
1825 mAuthTokenTable.Clear();
1826
1827 if (password.size() == 0) {
1828 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001829 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001830 return ::NO_ERROR;
1831 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001832 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001833 case ::STATE_UNINITIALIZED: {
1834 // generate master key, encrypt with password, write to file,
1835 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001836 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001837 }
1838 case ::STATE_NO_ERROR: {
1839 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001840 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001841 }
1842 case ::STATE_LOCKED: {
1843 ALOGE("Changing user %d's password while locked, clearing old encryption",
1844 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001845 mKeyStore->resetUser(userId, true);
1846 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001847 }
Kenny Root07438c82012-11-02 15:41:02 -07001848 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001849 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001850 }
Kenny Root70e3a862012-02-15 17:20:23 -08001851 }
1852
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001853 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1854 if (!checkBinderPermission(P_USER_CHANGED)) {
1855 return ::PERMISSION_DENIED;
1856 }
1857
1858 // Sanity check that the new user has an empty keystore.
1859 if (!mKeyStore->isEmpty(userId)) {
1860 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1861 }
1862 // Unconditionally clear the keystore, just to be safe.
1863 mKeyStore->resetUser(userId, false);
1864
1865 // If the user has a parent user then use the parent's
1866 // masterkey/password, otherwise there's nothing to do.
1867 if (parentId != -1) {
1868 return mKeyStore->copyMasterKey(parentId, userId);
1869 } else {
1870 return ::NO_ERROR;
1871 }
1872 }
1873
1874 int32_t onUserRemoved(int32_t userId) {
1875 if (!checkBinderPermission(P_USER_CHANGED)) {
1876 return ::PERMISSION_DENIED;
1877 }
1878
1879 mKeyStore->resetUser(userId, false);
1880 return ::NO_ERROR;
1881 }
1882
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001883 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001884 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001885 return ::PERMISSION_DENIED;
1886 }
Kenny Root70e3a862012-02-15 17:20:23 -08001887
Chad Brubaker72593ee2015-05-12 10:42:00 -07001888 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001889 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001890 ALOGD("calling lock in state: %d", state);
1891 return state;
1892 }
1893
Chad Brubaker72593ee2015-05-12 10:42:00 -07001894 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001895 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001896 }
1897
Chad Brubaker96d6d782015-05-07 10:19:40 -07001898 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001899 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001900 return ::PERMISSION_DENIED;
1901 }
1902
Chad Brubaker72593ee2015-05-12 10:42:00 -07001903 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001904 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001905 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001906 return state;
1907 }
1908
1909 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001910 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001911 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001912 }
1913
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001914 bool isEmpty(int32_t userId) {
1915 if (!checkBinderPermission(P_IS_EMPTY)) {
1916 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001917 }
Kenny Root70e3a862012-02-15 17:20:23 -08001918
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001919 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001920 }
1921
Kenny Root96427ba2013-08-16 14:02:41 -07001922 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1923 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001924 targetUid = getEffectiveUid(targetUid);
1925 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1926 flags & KEYSTORE_FLAG_ENCRYPTED);
1927 if (result != ::NO_ERROR) {
1928 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001929 }
Kenny Root07438c82012-11-02 15:41:02 -07001930
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001931 KeymasterArguments params;
Shawn Willden2de8b752015-07-23 05:54:31 -06001932 addLegacyKeyAuthorizations(params.params, keyType);
Kenny Root07438c82012-11-02 15:41:02 -07001933
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001934 switch (keyType) {
1935 case EVP_PKEY_EC: {
1936 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
1937 if (keySize == -1) {
1938 keySize = EC_DEFAULT_KEY_SIZE;
1939 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1940 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07001941 return ::SYSTEM_ERROR;
1942 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001943 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1944 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001945 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001946 case EVP_PKEY_RSA: {
1947 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1948 if (keySize == -1) {
1949 keySize = RSA_DEFAULT_KEY_SIZE;
1950 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1951 ALOGI("invalid key size %d", keySize);
1952 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07001953 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001954 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1955 unsigned long exponent = RSA_DEFAULT_EXPONENT;
1956 if (args->size() > 1) {
1957 ALOGI("invalid number of arguments: %zu", args->size());
1958 return ::SYSTEM_ERROR;
1959 } else if (args->size() == 1) {
1960 sp<KeystoreArg> expArg = args->itemAt(0);
1961 if (expArg != NULL) {
1962 Unique_BIGNUM pubExpBn(
1963 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
1964 expArg->size(), NULL));
1965 if (pubExpBn.get() == NULL) {
1966 ALOGI("Could not convert public exponent to BN");
1967 return ::SYSTEM_ERROR;
1968 }
1969 exponent = BN_get_word(pubExpBn.get());
1970 if (exponent == 0xFFFFFFFFL) {
1971 ALOGW("cannot represent public exponent as a long value");
1972 return ::SYSTEM_ERROR;
1973 }
1974 } else {
1975 ALOGW("public exponent not read");
1976 return ::SYSTEM_ERROR;
1977 }
1978 }
1979 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
1980 exponent));
1981 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001982 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001983 default: {
1984 ALOGW("Unsupported key type %d", keyType);
1985 return ::SYSTEM_ERROR;
1986 }
Kenny Root96427ba2013-08-16 14:02:41 -07001987 }
1988
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001989 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
1990 /*outCharacteristics*/ NULL);
1991 if (rc != ::NO_ERROR) {
1992 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07001993 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001994 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08001995 }
1996
Kenny Rootf9119d62013-04-03 09:22:15 -07001997 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1998 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001999 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002000
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002001 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2002 if (!pkcs8.get()) {
2003 return ::SYSTEM_ERROR;
2004 }
2005 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2006 if (!pkey.get()) {
2007 return ::SYSTEM_ERROR;
2008 }
2009 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002010 KeymasterArguments params;
2011 addLegacyKeyAuthorizations(params.params, type);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002012 switch (type) {
2013 case EVP_PKEY_RSA:
2014 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2015 break;
2016 case EVP_PKEY_EC:
2017 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2018 KM_ALGORITHM_EC));
2019 break;
2020 default:
2021 ALOGW("Unsupported key type %d", type);
2022 return ::SYSTEM_ERROR;
2023 }
2024 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2025 /*outCharacteristics*/ NULL);
2026 if (rc != ::NO_ERROR) {
2027 ALOGW("importKey failed: %d", rc);
2028 }
2029 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002030 }
2031
Kenny Root07438c82012-11-02 15:41:02 -07002032 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002033 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002034 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002035 return ::PERMISSION_DENIED;
2036 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002037 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002038 }
2039
Kenny Root07438c82012-11-02 15:41:02 -07002040 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2041 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002042 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002043 return ::PERMISSION_DENIED;
2044 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002045 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2046 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002047 }
Kenny Root07438c82012-11-02 15:41:02 -07002048
2049 /*
2050 * TODO: The abstraction between things stored in hardware and regular blobs
2051 * of data stored on the filesystem should be moved down to keystore itself.
2052 * Unfortunately the Java code that calls this has naming conventions that it
2053 * knows about. Ideally keystore shouldn't be used to store random blobs of
2054 * data.
2055 *
2056 * Until that happens, it's necessary to have a separate "get_pubkey" and
2057 * "del_key" since the Java code doesn't really communicate what it's
2058 * intentions are.
2059 */
2060 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002061 ExportResult result;
2062 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2063 if (result.resultCode != ::NO_ERROR) {
2064 ALOGW("export failed: %d", result.resultCode);
2065 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002066 }
Kenny Root07438c82012-11-02 15:41:02 -07002067
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002068 *pubkey = result.exportData.release();
2069 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002070 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002071 }
Kenny Root07438c82012-11-02 15:41:02 -07002072
Kenny Root07438c82012-11-02 15:41:02 -07002073 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002074 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002075 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2076 if (result != ::NO_ERROR) {
2077 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002078 }
2079
2080 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002081 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002082
Kenny Root655b9582013-04-04 08:37:42 -07002083 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002084 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2085 }
2086
Kenny Root655b9582013-04-04 08:37:42 -07002087 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002088 return ::NO_ERROR;
2089 }
2090
2091 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002092 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002093 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2094 if (result != ::NO_ERROR) {
2095 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002096 }
2097
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) {
Kenny Root07438c82012-11-02 15:41:02 -07002102 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2103 }
2104
Kenny Root655b9582013-04-04 08:37:42 -07002105 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002106 }
2107
2108 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002109 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002110 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002111 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002112 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002113 }
Kenny Root07438c82012-11-02 15:41:02 -07002114
2115 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002116 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002117
Kenny Root655b9582013-04-04 08:37:42 -07002118 if (access(filename.string(), R_OK) == -1) {
2119 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002120 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002121 }
2122
Kenny Root655b9582013-04-04 08:37:42 -07002123 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002124 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002125 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002126 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002127 }
2128
2129 struct stat s;
2130 int ret = fstat(fd, &s);
2131 close(fd);
2132 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002133 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002134 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002135 }
2136
Kenny Root36a9e232013-02-04 14:24:15 -08002137 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002138 }
2139
Kenny Rootd53bc922013-03-21 14:10:15 -07002140 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2141 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002142 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002143 pid_t spid = IPCThreadState::self()->getCallingPid();
2144 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002145 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002146 return -1L;
2147 }
2148
Chad Brubaker72593ee2015-05-12 10:42:00 -07002149 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002150 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002151 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002152 return state;
2153 }
2154
Kenny Rootd53bc922013-03-21 14:10:15 -07002155 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2156 srcUid = callingUid;
2157 } else if (!is_granted_to(callingUid, srcUid)) {
2158 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002159 return ::PERMISSION_DENIED;
2160 }
2161
Kenny Rootd53bc922013-03-21 14:10:15 -07002162 if (destUid == -1) {
2163 destUid = callingUid;
2164 }
2165
2166 if (srcUid != destUid) {
2167 if (static_cast<uid_t>(srcUid) != callingUid) {
2168 ALOGD("can only duplicate from caller to other or to same uid: "
2169 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2170 return ::PERMISSION_DENIED;
2171 }
2172
2173 if (!is_granted_to(callingUid, destUid)) {
2174 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2175 return ::PERMISSION_DENIED;
2176 }
2177 }
2178
2179 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002180 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002181
Kenny Rootd53bc922013-03-21 14:10:15 -07002182 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002183 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002184
Kenny Root655b9582013-04-04 08:37:42 -07002185 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2186 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002187 return ::SYSTEM_ERROR;
2188 }
2189
Kenny Rootd53bc922013-03-21 14:10:15 -07002190 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002191 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002192 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002193 if (responseCode != ::NO_ERROR) {
2194 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002195 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002196
Chad Brubaker72593ee2015-05-12 10:42:00 -07002197 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002198 }
2199
Kenny Root1b0e3932013-09-05 13:06:32 -07002200 int32_t is_hardware_backed(const String16& keyType) {
2201 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002202 }
2203
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002204 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002205 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002206 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002207 return ::PERMISSION_DENIED;
2208 }
2209
Robin Lee4b84fdc2014-09-24 11:56:57 +01002210 String8 prefix = String8::format("%u_", targetUid);
2211 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002212 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002213 return ::SYSTEM_ERROR;
2214 }
2215
Robin Lee4b84fdc2014-09-24 11:56:57 +01002216 for (uint32_t i = 0; i < aliases.size(); i++) {
2217 String8 name8(aliases[i]);
2218 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002219 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002220 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002221 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002222 }
2223
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002224 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2225 const keymaster1_device_t* device = mKeyStore->getDevice();
2226 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2227 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2228 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2229 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2230 device->add_rng_entropy != NULL) {
2231 devResult = device->add_rng_entropy(device, data, dataLength);
2232 }
2233 if (fallback->add_rng_entropy) {
2234 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2235 }
2236 if (devResult) {
2237 return devResult;
2238 }
2239 if (fallbackResult) {
2240 return fallbackResult;
2241 }
2242 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002243 }
2244
Chad Brubaker17d68b92015-02-05 22:04:16 -08002245 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002246 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2247 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002248 uid = getEffectiveUid(uid);
2249 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2250 flags & KEYSTORE_FLAG_ENCRYPTED);
2251 if (rc != ::NO_ERROR) {
2252 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002253 }
2254
Chad Brubaker9489b792015-04-14 11:01:45 -07002255 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002256 bool isFallback = false;
2257 keymaster_key_blob_t blob;
2258 keymaster_key_characteristics_t *out = NULL;
2259
2260 const keymaster1_device_t* device = mKeyStore->getDevice();
2261 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002262 std::vector<keymaster_key_param_t> opParams(params.params);
2263 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002264 if (device == NULL) {
2265 return ::SYSTEM_ERROR;
2266 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002267 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002268 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2269 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002270 if (!entropy) {
2271 rc = KM_ERROR_OK;
2272 } else if (device->add_rng_entropy) {
2273 rc = device->add_rng_entropy(device, entropy, entropyLength);
2274 } else {
2275 rc = KM_ERROR_UNIMPLEMENTED;
2276 }
2277 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002278 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002279 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002280 }
2281 // If the HW device didn't support generate_key or generate_key failed
2282 // fall back to the software implementation.
2283 if (rc && fallback->generate_key != NULL) {
2284 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002285 if (!entropy) {
2286 rc = KM_ERROR_OK;
2287 } else if (fallback->add_rng_entropy) {
2288 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2289 } else {
2290 rc = KM_ERROR_UNIMPLEMENTED;
2291 }
2292 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002293 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002294 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002295 }
2296
2297 if (out) {
2298 if (outCharacteristics) {
2299 outCharacteristics->characteristics = *out;
2300 } else {
2301 keymaster_free_characteristics(out);
2302 }
2303 free(out);
2304 }
2305
2306 if (rc) {
2307 return rc;
2308 }
2309
2310 String8 name8(name);
2311 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2312
2313 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2314 keyBlob.setFallback(isFallback);
2315 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2316
2317 free(const_cast<uint8_t*>(blob.key_material));
2318
Chad Brubaker72593ee2015-05-12 10:42:00 -07002319 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002320 }
2321
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002322 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002323 const keymaster_blob_t* clientId,
2324 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002325 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002326 if (!outCharacteristics) {
2327 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2328 }
2329
2330 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2331
2332 Blob keyBlob;
2333 String8 name8(name);
2334 int rc;
2335
2336 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2337 TYPE_KEYMASTER_10);
2338 if (responseCode != ::NO_ERROR) {
2339 return responseCode;
2340 }
2341 keymaster_key_blob_t key;
2342 key.key_material_size = keyBlob.getLength();
2343 key.key_material = keyBlob.getValue();
2344 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2345 keymaster_key_characteristics_t *out = NULL;
2346 if (!dev->get_key_characteristics) {
2347 ALOGW("device does not implement get_key_characteristics");
2348 return KM_ERROR_UNIMPLEMENTED;
2349 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002350 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002351 if (out) {
2352 outCharacteristics->characteristics = *out;
2353 free(out);
2354 }
2355 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002356 }
2357
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002358 int32_t importKey(const String16& name, const KeymasterArguments& params,
2359 keymaster_key_format_t format, const uint8_t *keyData,
2360 size_t keyLength, int uid, int flags,
2361 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002362 uid = getEffectiveUid(uid);
2363 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2364 flags & KEYSTORE_FLAG_ENCRYPTED);
2365 if (rc != ::NO_ERROR) {
2366 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002367 }
2368
Chad Brubaker9489b792015-04-14 11:01:45 -07002369 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002370 bool isFallback = false;
2371 keymaster_key_blob_t blob;
2372 keymaster_key_characteristics_t *out = NULL;
2373
2374 const keymaster1_device_t* device = mKeyStore->getDevice();
2375 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002376 std::vector<keymaster_key_param_t> opParams(params.params);
2377 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2378 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002379 if (device == NULL) {
2380 return ::SYSTEM_ERROR;
2381 }
2382 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2383 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002384 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002385 }
2386 if (rc && fallback->import_key != NULL) {
2387 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002388 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002389 }
2390 if (out) {
2391 if (outCharacteristics) {
2392 outCharacteristics->characteristics = *out;
2393 } else {
2394 keymaster_free_characteristics(out);
2395 }
2396 free(out);
2397 }
2398 if (rc) {
2399 return rc;
2400 }
2401
2402 String8 name8(name);
2403 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2404
2405 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2406 keyBlob.setFallback(isFallback);
2407 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2408
2409 free((void*) blob.key_material);
2410
Chad Brubaker72593ee2015-05-12 10:42:00 -07002411 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002412 }
2413
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002414 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002415 const keymaster_blob_t* clientId,
2416 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002417
2418 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2419
2420 Blob keyBlob;
2421 String8 name8(name);
2422 int rc;
2423
2424 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2425 TYPE_KEYMASTER_10);
2426 if (responseCode != ::NO_ERROR) {
2427 result->resultCode = responseCode;
2428 return;
2429 }
2430 keymaster_key_blob_t key;
2431 key.key_material_size = keyBlob.getLength();
2432 key.key_material = keyBlob.getValue();
2433 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2434 if (!dev->export_key) {
2435 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2436 return;
2437 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002438 keymaster_blob_t output = {NULL, 0};
2439 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2440 result->exportData.reset(const_cast<uint8_t*>(output.data));
2441 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002442 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002443 }
2444
Chad Brubakerad6514a2015-04-09 14:00:26 -07002445
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002446 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002447 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002448 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002449 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2450 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2451 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2452 result->resultCode = ::PERMISSION_DENIED;
2453 return;
2454 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002455 if (!checkAllowedOperationParams(params.params)) {
2456 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2457 return;
2458 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002459 Blob keyBlob;
2460 String8 name8(name);
2461 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2462 TYPE_KEYMASTER_10);
2463 if (responseCode != ::NO_ERROR) {
2464 result->resultCode = responseCode;
2465 return;
2466 }
2467 keymaster_key_blob_t key;
2468 key.key_material_size = keyBlob.getLength();
2469 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002470 keymaster_operation_handle_t handle;
2471 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002472 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002473 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002474 Unique_keymaster_key_characteristics characteristics;
2475 characteristics.reset(new keymaster_key_characteristics_t);
2476 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2477 if (err) {
2478 result->resultCode = err;
2479 return;
2480 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002481 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002482 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002483 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002484 // If per-operation auth is needed we need to begin the operation and
2485 // the client will need to authorize that operation before calling
2486 // update. Any other auth issues stop here.
2487 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2488 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002489 return;
2490 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002491 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002492 // Add entropy to the device first.
2493 if (entropy) {
2494 if (dev->add_rng_entropy) {
2495 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2496 } else {
2497 err = KM_ERROR_UNIMPLEMENTED;
2498 }
2499 if (err) {
2500 result->resultCode = err;
2501 return;
2502 }
2503 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002504 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002505
Shawn Willden9221bff2015-06-18 18:23:54 -06002506 // Create a keyid for this key.
2507 keymaster::km_id_t keyid;
2508 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2509 ALOGE("Failed to create a key ID for authorization checking.");
2510 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2511 return;
2512 }
2513
2514 // Check that all key authorization policy requirements are met.
2515 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2516 key_auths.push_back(characteristics->sw_enforced);
2517 keymaster::AuthorizationSet operation_params(inParams);
2518 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2519 0 /* op_handle */,
2520 true /* is_begin_operation */);
2521 if (err) {
2522 result->resultCode = err;
2523 return;
2524 }
2525
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002526 keymaster_key_param_set_t outParams = {NULL, 0};
2527 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2528
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002529 // If there are too many operations abort the oldest operation that was
2530 // started as pruneable and try again.
2531 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2532 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2533 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002534
2535 // We mostly ignore errors from abort() below because all we care about is whether at
2536 // least one pruneable operation has been removed.
2537 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2538 int abort_error = abort(oldest);
2539 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2540 if (op_count_after >= op_count_before) {
2541 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2542 ALOGE("Failed to remove pruneable operation %p, error: %d",
2543 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002544 break;
2545 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002546 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002547 }
2548 if (err) {
2549 result->resultCode = err;
2550 return;
2551 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002552
Shawn Willden9221bff2015-06-18 18:23:54 -06002553 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2554 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002555 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002556 if (authToken) {
2557 mOperationMap.setOperationAuthToken(operationToken, authToken);
2558 }
2559 // Return the authentication lookup result. If this is a per operation
2560 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2561 // application should get an auth token using the handle before the
2562 // first call to update, which will fail if keystore hasn't received the
2563 // auth token.
2564 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002565 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002566 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002567 if (outParams.params) {
2568 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2569 free(outParams.params);
2570 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002571 }
2572
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002573 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2574 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002575 if (!checkAllowedOperationParams(params.params)) {
2576 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2577 return;
2578 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002579 const keymaster1_device_t* dev;
2580 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002581 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002582 keymaster::km_id_t keyid;
2583 const keymaster_key_characteristics_t* characteristics;
2584 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002585 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2586 return;
2587 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002588 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002589 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2590 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002591 result->resultCode = authResult;
2592 return;
2593 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002594 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2595 keymaster_blob_t input = {data, dataLength};
2596 size_t consumed = 0;
2597 keymaster_blob_t output = {NULL, 0};
2598 keymaster_key_param_set_t outParams = {NULL, 0};
2599
Shawn Willden9221bff2015-06-18 18:23:54 -06002600 // Check that all key authorization policy requirements are met.
2601 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2602 key_auths.push_back(characteristics->sw_enforced);
2603 keymaster::AuthorizationSet operation_params(inParams);
2604 result->resultCode =
2605 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2606 operation_params, handle,
2607 false /* is_begin_operation */);
2608 if (result->resultCode) {
2609 return;
2610 }
2611
Chad Brubaker57e106d2015-06-01 12:59:00 -07002612 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2613 &output);
2614 result->data.reset(const_cast<uint8_t*>(output.data));
2615 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002616 result->inputConsumed = consumed;
2617 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002618 if (outParams.params) {
2619 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2620 free(outParams.params);
2621 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002622 }
2623
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002624 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002625 const uint8_t* signature, size_t signatureLength,
2626 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002627 if (!checkAllowedOperationParams(params.params)) {
2628 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2629 return;
2630 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002631 const keymaster1_device_t* dev;
2632 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002633 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002634 keymaster::km_id_t keyid;
2635 const keymaster_key_characteristics_t* characteristics;
2636 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002637 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2638 return;
2639 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002640 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002641 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2642 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002643 result->resultCode = authResult;
2644 return;
2645 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002646 keymaster_error_t err;
2647 if (entropy) {
2648 if (dev->add_rng_entropy) {
2649 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2650 } else {
2651 err = KM_ERROR_UNIMPLEMENTED;
2652 }
2653 if (err) {
2654 result->resultCode = err;
2655 return;
2656 }
2657 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002658
Chad Brubaker57e106d2015-06-01 12:59:00 -07002659 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2660 keymaster_blob_t input = {signature, signatureLength};
2661 keymaster_blob_t output = {NULL, 0};
2662 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002663
2664 // Check that all key authorization policy requirements are met.
2665 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2666 key_auths.push_back(characteristics->sw_enforced);
2667 keymaster::AuthorizationSet operation_params(inParams);
2668 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2669 handle, false /* is_begin_operation */);
2670 if (err) {
2671 result->resultCode = err;
2672 return;
2673 }
2674
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002675 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002676 // Remove the operation regardless of the result
2677 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002678 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002679
2680 result->data.reset(const_cast<uint8_t*>(output.data));
2681 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002682 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002683 if (outParams.params) {
2684 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2685 free(outParams.params);
2686 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002687 }
2688
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002689 int32_t abort(const sp<IBinder>& token) {
2690 const keymaster1_device_t* dev;
2691 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002692 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002693 keymaster::km_id_t keyid;
2694 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002695 return KM_ERROR_INVALID_OPERATION_HANDLE;
2696 }
2697 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002698 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002699 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002700 rc = KM_ERROR_UNIMPLEMENTED;
2701 } else {
2702 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002703 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002704 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002705 if (rc) {
2706 return rc;
2707 }
2708 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002709 }
2710
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002711 bool isOperationAuthorized(const sp<IBinder>& token) {
2712 const keymaster1_device_t* dev;
2713 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002714 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002715 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002716 keymaster::km_id_t keyid;
2717 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002718 return false;
2719 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002720 const hw_auth_token_t* authToken = NULL;
2721 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002722 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002723 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2724 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002725 }
2726
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002727 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002728 if (!checkBinderPermission(P_ADD_AUTH)) {
2729 ALOGW("addAuthToken: permission denied for %d",
2730 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002731 return ::PERMISSION_DENIED;
2732 }
2733 if (length != sizeof(hw_auth_token_t)) {
2734 return KM_ERROR_INVALID_ARGUMENT;
2735 }
2736 hw_auth_token_t* authToken = new hw_auth_token_t;
2737 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2738 // The table takes ownership of authToken.
2739 mAuthTokenTable.AddAuthenticationToken(authToken);
2740 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002741 }
2742
Kenny Root07438c82012-11-02 15:41:02 -07002743private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002744 static const int32_t UID_SELF = -1;
2745
2746 /**
2747 * Get the effective target uid for a binder operation that takes an
2748 * optional uid as the target.
2749 */
2750 inline uid_t getEffectiveUid(int32_t targetUid) {
2751 if (targetUid == UID_SELF) {
2752 return IPCThreadState::self()->getCallingUid();
2753 }
2754 return static_cast<uid_t>(targetUid);
2755 }
2756
2757 /**
2758 * Check if the caller of the current binder method has the required
2759 * permission and if acting on other uids the grants to do so.
2760 */
2761 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2762 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2763 pid_t spid = IPCThreadState::self()->getCallingPid();
2764 if (!has_permission(callingUid, permission, spid)) {
2765 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2766 return false;
2767 }
2768 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2769 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2770 return false;
2771 }
2772 return true;
2773 }
2774
2775 /**
2776 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002777 * permission and the target uid is the caller or the caller is system.
2778 */
2779 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2780 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2781 pid_t spid = IPCThreadState::self()->getCallingPid();
2782 if (!has_permission(callingUid, permission, spid)) {
2783 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2784 return false;
2785 }
2786 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2787 }
2788
2789 /**
2790 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002791 * permission or the target of the operation is the caller's uid. This is
2792 * for operation where the permission is only for cross-uid activity and all
2793 * uids are allowed to act on their own (ie: clearing all entries for a
2794 * given uid).
2795 */
2796 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2797 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2798 if (getEffectiveUid(targetUid) == callingUid) {
2799 return true;
2800 } else {
2801 return checkBinderPermission(permission, targetUid);
2802 }
2803 }
2804
2805 /**
2806 * Helper method to check that the caller has the required permission as
2807 * well as the keystore is in the unlocked state if checkUnlocked is true.
2808 *
2809 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2810 * otherwise the state of keystore when not unlocked and checkUnlocked is
2811 * true.
2812 */
2813 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2814 bool checkUnlocked = true) {
2815 if (!checkBinderPermission(permission, targetUid)) {
2816 return ::PERMISSION_DENIED;
2817 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002818 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002819 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2820 return state;
2821 }
2822
2823 return ::NO_ERROR;
2824
2825 }
2826
Kenny Root9d45d1c2013-02-14 10:32:30 -08002827 inline bool isKeystoreUnlocked(State state) {
2828 switch (state) {
2829 case ::STATE_NO_ERROR:
2830 return true;
2831 case ::STATE_UNINITIALIZED:
2832 case ::STATE_LOCKED:
2833 return false;
2834 }
2835 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002836 }
2837
Chad Brubaker67d2a502015-03-11 17:21:18 +00002838 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002839 const int32_t device_api = device->common.module->module_api_version;
2840 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2841 switch (keyType) {
2842 case TYPE_RSA:
2843 case TYPE_DSA:
2844 case TYPE_EC:
2845 return true;
2846 default:
2847 return false;
2848 }
2849 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2850 switch (keyType) {
2851 case TYPE_RSA:
2852 return true;
2853 case TYPE_DSA:
2854 return device->flags & KEYMASTER_SUPPORTS_DSA;
2855 case TYPE_EC:
2856 return device->flags & KEYMASTER_SUPPORTS_EC;
2857 default:
2858 return false;
2859 }
2860 } else {
2861 return keyType == TYPE_RSA;
2862 }
2863 }
2864
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002865 /**
2866 * Check that all keymaster_key_param_t's provided by the application are
2867 * allowed. Any parameter that keystore adds itself should be disallowed here.
2868 */
2869 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2870 for (auto param: params) {
2871 switch (param.tag) {
2872 case KM_TAG_AUTH_TOKEN:
2873 return false;
2874 default:
2875 break;
2876 }
2877 }
2878 return true;
2879 }
2880
2881 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2882 const keymaster1_device_t* dev,
2883 const std::vector<keymaster_key_param_t>& params,
2884 keymaster_key_characteristics_t* out) {
2885 UniquePtr<keymaster_blob_t> appId;
2886 UniquePtr<keymaster_blob_t> appData;
2887 for (auto param : params) {
2888 if (param.tag == KM_TAG_APPLICATION_ID) {
2889 appId.reset(new keymaster_blob_t);
2890 appId->data = param.blob.data;
2891 appId->data_length = param.blob.data_length;
2892 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2893 appData.reset(new keymaster_blob_t);
2894 appData->data = param.blob.data;
2895 appData->data_length = param.blob.data_length;
2896 }
2897 }
2898 keymaster_key_characteristics_t* result = NULL;
2899 if (!dev->get_key_characteristics) {
2900 return KM_ERROR_UNIMPLEMENTED;
2901 }
2902 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2903 appData.get(), &result);
2904 if (result) {
2905 *out = *result;
2906 free(result);
2907 }
2908 return error;
2909 }
2910
2911 /**
2912 * Get the auth token for this operation from the auth token table.
2913 *
2914 * Returns ::NO_ERROR if the auth token was set or none was required.
2915 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2916 * authorization token exists for that operation and
2917 * failOnTokenMissing is false.
2918 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2919 * token for the operation
2920 */
2921 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2922 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002923 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002924 const hw_auth_token_t** authToken,
2925 bool failOnTokenMissing = true) {
2926
2927 std::vector<keymaster_key_param_t> allCharacteristics;
2928 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2929 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2930 }
2931 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2932 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2933 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002934 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
2935 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002936 switch (err) {
2937 case keymaster::AuthTokenTable::OK:
2938 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2939 return ::NO_ERROR;
2940 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2941 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2942 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2943 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2944 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2945 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2946 (int32_t) ::OP_AUTH_NEEDED;
2947 default:
2948 ALOGE("Unexpected FindAuthorization return value %d", err);
2949 return KM_ERROR_INVALID_ARGUMENT;
2950 }
2951 }
2952
2953 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2954 const hw_auth_token_t* token) {
2955 if (token) {
2956 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2957 reinterpret_cast<const uint8_t*>(token),
2958 sizeof(hw_auth_token_t)));
2959 }
2960 }
2961
2962 /**
2963 * Add the auth token for the operation to the param list if the operation
2964 * requires authorization. Uses the cached result in the OperationMap if available
2965 * otherwise gets the token from the AuthTokenTable and caches the result.
2966 *
2967 * Returns ::NO_ERROR if the auth token was added or not needed.
2968 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2969 * authenticated.
2970 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2971 * operation token.
2972 */
2973 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2974 std::vector<keymaster_key_param_t>* params) {
2975 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002976 mOperationMap.getOperationAuthToken(token, &authToken);
2977 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002978 const keymaster1_device_t* dev;
2979 keymaster_operation_handle_t handle;
2980 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002981 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002982 keymaster::km_id_t keyid;
2983 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
2984 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002985 return KM_ERROR_INVALID_OPERATION_HANDLE;
2986 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002987 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002988 if (result != ::NO_ERROR) {
2989 return result;
2990 }
2991 if (authToken) {
2992 mOperationMap.setOperationAuthToken(token, authToken);
2993 }
2994 }
2995 addAuthToParams(params, authToken);
2996 return ::NO_ERROR;
2997 }
2998
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002999 /**
3000 * Translate a result value to a legacy return value. All keystore errors are
3001 * preserved and keymaster errors become SYSTEM_ERRORs
3002 */
3003 inline int32_t translateResultToLegacyResult(int32_t result) {
3004 if (result > 0) {
3005 return result;
3006 }
3007 return ::SYSTEM_ERROR;
3008 }
3009
Shawn Willden2de8b752015-07-23 05:54:31 -06003010 void addLegacyKeyAuthorizations(std::vector<keymaster_key_param_t>& params, int keyType) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003011 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
3012 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
3013 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
3014 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
3015 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
Shawn Willden2de8b752015-07-23 05:54:31 -06003016 if (keyType == EVP_PKEY_RSA) {
3017 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
3018 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
3019 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PSS));
3020 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_OAEP));
3021 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003022 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
Shawn Willden2de8b752015-07-23 05:54:31 -06003023 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_MD5));
3024 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA1));
3025 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_224));
3026 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_256));
3027 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_384));
3028 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_512));
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003029 params.push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
3030 params.push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
3031 params.push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
3032 params.push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
3033 params.push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
3034 uint64_t now = keymaster::java_time(time(NULL));
3035 params.push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
3036 }
3037
3038 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3039 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3040 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3041 return &characteristics->hw_enforced.params[i];
3042 }
3043 }
3044 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3045 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3046 return &characteristics->sw_enforced.params[i];
3047 }
3048 }
3049 return NULL;
3050 }
3051
3052 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3053 // All legacy keys are DIGEST_NONE/PAD_NONE.
3054 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3055 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3056
3057 // Look up the algorithm of the key.
3058 KeyCharacteristics characteristics;
3059 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3060 if (rc != ::NO_ERROR) {
3061 ALOGE("Failed to get key characteristics");
3062 return;
3063 }
3064 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3065 if (!algorithm) {
3066 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3067 return;
3068 }
3069 params.push_back(*algorithm);
3070 }
3071
3072 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3073 uint8_t** out, size_t* outLength, const uint8_t* signature,
3074 size_t signatureLength, keymaster_purpose_t purpose) {
3075
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003076 std::basic_stringstream<uint8_t> outBuffer;
3077 OperationResult result;
3078 KeymasterArguments inArgs;
3079 addLegacyBeginParams(name, inArgs.params);
3080 sp<IBinder> appToken(new BBinder);
3081 sp<IBinder> token;
3082
3083 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3084 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003085 if (result.resultCode == ::KEY_NOT_FOUND) {
3086 ALOGW("Key not found");
3087 } else {
3088 ALOGW("Error in begin: %d", result.resultCode);
3089 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003090 return translateResultToLegacyResult(result.resultCode);
3091 }
3092 inArgs.params.clear();
3093 token = result.token;
3094 size_t consumed = 0;
3095 size_t lastConsumed = 0;
3096 do {
3097 update(token, inArgs, data + consumed, length - consumed, &result);
3098 if (result.resultCode != ResponseCode::NO_ERROR) {
3099 ALOGW("Error in update: %d", result.resultCode);
3100 return translateResultToLegacyResult(result.resultCode);
3101 }
3102 if (out) {
3103 outBuffer.write(result.data.get(), result.dataLength);
3104 }
3105 lastConsumed = result.inputConsumed;
3106 consumed += lastConsumed;
3107 } while (consumed < length && lastConsumed > 0);
3108
3109 if (consumed != length) {
3110 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3111 return ::SYSTEM_ERROR;
3112 }
3113
3114 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3115 if (result.resultCode != ResponseCode::NO_ERROR) {
3116 ALOGW("Error in finish: %d", result.resultCode);
3117 return translateResultToLegacyResult(result.resultCode);
3118 }
3119 if (out) {
3120 outBuffer.write(result.data.get(), result.dataLength);
3121 }
3122
3123 if (out) {
3124 auto buf = outBuffer.str();
3125 *out = new uint8_t[buf.size()];
3126 memcpy(*out, buf.c_str(), buf.size());
3127 *outLength = buf.size();
3128 }
3129
3130 return ::NO_ERROR;
3131 }
3132
Kenny Root07438c82012-11-02 15:41:02 -07003133 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003134 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003135 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003136 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003137};
3138
3139}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003140
3141int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003142 if (argc < 2) {
3143 ALOGE("A directory must be specified!");
3144 return 1;
3145 }
3146 if (chdir(argv[1]) == -1) {
3147 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3148 return 1;
3149 }
3150
3151 Entropy entropy;
3152 if (!entropy.open()) {
3153 return 1;
3154 }
Kenny Root70e3a862012-02-15 17:20:23 -08003155
Chad Brubakerbd07a232015-06-01 10:44:27 -07003156 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003157 if (keymaster_device_initialize(&dev)) {
3158 ALOGE("keystore keymaster could not be initialized; exiting");
3159 return 1;
3160 }
3161
Chad Brubaker67d2a502015-03-11 17:21:18 +00003162 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003163 if (fallback_keymaster_device_initialize(&fallback)) {
3164 ALOGE("software keymaster could not be initialized; exiting");
3165 return 1;
3166 }
3167
Riley Spahneaabae92014-06-30 12:39:52 -07003168 ks_is_selinux_enabled = is_selinux_enabled();
3169 if (ks_is_selinux_enabled) {
3170 union selinux_callback cb;
3171 cb.func_log = selinux_log_callback;
3172 selinux_set_callback(SELINUX_CB_LOG, cb);
3173 if (getcon(&tctx) != 0) {
3174 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3175 return -1;
3176 }
3177 } else {
3178 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3179 }
3180
Chad Brubakerbd07a232015-06-01 10:44:27 -07003181 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003182 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003183 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3184 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3185 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3186 if (ret != android::OK) {
3187 ALOGE("Couldn't register binder service!");
3188 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003189 }
Kenny Root07438c82012-11-02 15:41:02 -07003190
3191 /*
3192 * We're the only thread in existence, so we're just going to process
3193 * Binder transaction as a single-threaded program.
3194 */
3195 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003196
3197 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003198 return 1;
3199}