blob: 8a43f02a6310293b26dd423ddf2b4ba6372b82e2 [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 Brubaker803f37f2015-07-29 13:53:36 -0700511 if (valueLength > sizeof(mBlob.value)) {
512 valueLength = sizeof(mBlob.value);
513 ALOGW("Provided blob length too large");
514 }
515 if (infoLength + valueLength > sizeof(mBlob.value)) {
516 infoLength = sizeof(mBlob.value) - valueLength;
517 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);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001204 }
1205
Kenny Rootd53bc922013-03-21 14:10:15 -07001206 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001207 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1208 return KEY_NOT_FOUND;
1209 }
1210
1211 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001212 }
1213
Chad Brubaker72593ee2015-05-12 10:42:00 -07001214 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1215 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001216 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1217 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001218 }
1219
Chad Brubaker72593ee2015-05-12 10:42:00 -07001220 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001221 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001222 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001223 if (rc == ::VALUE_CORRUPTED) {
1224 // The file is corrupt, the best we can do is rm it.
1225 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1226 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001227 if (rc != ::NO_ERROR) {
1228 return rc;
1229 }
1230
1231 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1232 // A device doesn't have to implement delete_keypair.
1233 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1234 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1235 rc = ::SYSTEM_ERROR;
1236 }
1237 }
1238 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001239 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1240 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1241 if (dev->delete_key) {
1242 keymaster_key_blob_t blob;
1243 blob.key_material = keyBlob.getValue();
1244 blob.key_material_size = keyBlob.getLength();
1245 dev->delete_key(dev, &blob);
1246 }
1247 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001248 if (rc != ::NO_ERROR) {
1249 return rc;
1250 }
1251
1252 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1253 }
1254
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001255 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001256 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001257
Chad Brubaker72593ee2015-05-12 10:42:00 -07001258 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001259 size_t n = prefix.length();
1260
1261 DIR* dir = opendir(userState->getUserDirName());
1262 if (!dir) {
1263 ALOGW("can't open directory for user: %s", strerror(errno));
1264 return ::SYSTEM_ERROR;
1265 }
1266
1267 struct dirent* file;
1268 while ((file = readdir(dir)) != NULL) {
1269 // We only care about files.
1270 if (file->d_type != DT_REG) {
1271 continue;
1272 }
1273
1274 // Skip anything that starts with a "."
1275 if (file->d_name[0] == '.') {
1276 continue;
1277 }
1278
1279 if (!strncmp(prefix.string(), file->d_name, n)) {
1280 const char* p = &file->d_name[n];
1281 size_t plen = strlen(p);
1282
1283 size_t extra = decode_key_length(p, plen);
1284 char *match = (char*) malloc(extra + 1);
1285 if (match != NULL) {
1286 decode_key(match, p, plen);
1287 matches->push(android::String16(match, extra));
1288 free(match);
1289 } else {
1290 ALOGW("could not allocate match of size %zd", extra);
1291 }
1292 }
1293 }
1294 closedir(dir);
1295 return ::NO_ERROR;
1296 }
1297
Kenny Root07438c82012-11-02 15:41:02 -07001298 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001299 const grant_t* existing = getGrant(filename, granteeUid);
1300 if (existing == NULL) {
1301 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001302 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001303 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001304 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001305 }
1306 }
1307
Kenny Root07438c82012-11-02 15:41:02 -07001308 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001309 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1310 it != mGrants.end(); it++) {
1311 grant_t* grant = *it;
1312 if (grant->uid == granteeUid
1313 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1314 mGrants.erase(it);
1315 return true;
1316 }
Kenny Root70e3a862012-02-15 17:20:23 -08001317 }
Kenny Root70e3a862012-02-15 17:20:23 -08001318 return false;
1319 }
1320
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001321 bool hasGrant(const char* filename, const uid_t uid) const {
1322 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001323 }
1324
Chad Brubaker72593ee2015-05-12 10:42:00 -07001325 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001326 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001327 uint8_t* data;
1328 size_t dataLength;
1329 int rc;
1330
1331 if (mDevice->import_keypair == NULL) {
1332 ALOGE("Keymaster doesn't support import!");
1333 return SYSTEM_ERROR;
1334 }
1335
Kenny Root17208e02013-09-04 13:56:03 -07001336 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001337 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001338 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001339 /*
1340 * Maybe the device doesn't support this type of key. Try to use the
1341 * software fallback keymaster implementation. This is a little bit
1342 * lazier than checking the PKCS#8 key type, but the software
1343 * implementation will do that anyway.
1344 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001345 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001346 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001347
1348 if (rc) {
1349 ALOGE("Error while importing keypair: %d", rc);
1350 return SYSTEM_ERROR;
1351 }
Kenny Root822c3a92012-03-23 16:34:39 -07001352 }
1353
1354 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1355 free(data);
1356
Kenny Rootf9119d62013-04-03 09:22:15 -07001357 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001358 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001359
Chad Brubaker72593ee2015-05-12 10:42:00 -07001360 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001361 }
1362
Kenny Root1b0e3932013-09-05 13:06:32 -07001363 bool isHardwareBacked(const android::String16& keyType) const {
1364 if (mDevice == NULL) {
1365 ALOGW("can't get keymaster device");
1366 return false;
1367 }
1368
1369 if (sRSAKeyType == keyType) {
1370 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1371 } else {
1372 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1373 && (mDevice->common.module->module_api_version
1374 >= KEYMASTER_MODULE_API_VERSION_0_2);
1375 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001376 }
1377
Kenny Root655b9582013-04-04 08:37:42 -07001378 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1379 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001380 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001381 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001382
Chad Brubaker72593ee2015-05-12 10:42:00 -07001383 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001384 if (responseCode == NO_ERROR) {
1385 return responseCode;
1386 }
1387
1388 // If this is one of the legacy UID->UID mappings, use it.
1389 uid_t euid = get_keystore_euid(uid);
1390 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001391 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001392 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
1398 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001399 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001400 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001401 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001402 if (end[0] != '_' || end[1] == 0) {
1403 return KEY_NOT_FOUND;
1404 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001405 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001406 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001407 if (!hasGrant(filepath8.string(), uid)) {
1408 return responseCode;
1409 }
1410
1411 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001412 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001413 }
1414
1415 /**
1416 * Returns any existing UserState or creates it if it doesn't exist.
1417 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001418 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001419 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1420 it != mMasterKeys.end(); it++) {
1421 UserState* state = *it;
1422 if (state->getUserId() == userId) {
1423 return state;
1424 }
1425 }
1426
1427 UserState* userState = new UserState(userId);
1428 if (!userState->initialize()) {
1429 /* There's not much we can do if initialization fails. Trying to
1430 * unlock the keystore for that user will fail as well, so any
1431 * subsequent request for this user will just return SYSTEM_ERROR.
1432 */
1433 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1434 }
1435 mMasterKeys.add(userState);
1436 return userState;
1437 }
1438
1439 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001440 * Returns any existing UserState or creates it if it doesn't exist.
1441 */
1442 UserState* getUserStateByUid(uid_t uid) {
1443 uid_t userId = get_user_id(uid);
1444 return getUserState(userId);
1445 }
1446
1447 /**
Kenny Root655b9582013-04-04 08:37:42 -07001448 * Returns NULL if the UserState doesn't already exist.
1449 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001450 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001451 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1452 it != mMasterKeys.end(); it++) {
1453 UserState* state = *it;
1454 if (state->getUserId() == userId) {
1455 return state;
1456 }
1457 }
1458
1459 return NULL;
1460 }
1461
Chad Brubaker72593ee2015-05-12 10:42:00 -07001462 /**
1463 * Returns NULL if the UserState doesn't already exist.
1464 */
1465 const UserState* getUserStateByUid(uid_t uid) const {
1466 uid_t userId = get_user_id(uid);
1467 return getUserState(userId);
1468 }
1469
Kenny Roota91203b2012-02-15 15:00:46 -08001470private:
Kenny Root655b9582013-04-04 08:37:42 -07001471 static const char* sOldMasterKey;
1472 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001473 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001474 Entropy* mEntropy;
1475
Chad Brubaker67d2a502015-03-11 17:21:18 +00001476 keymaster1_device_t* mDevice;
1477 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001478
Kenny Root655b9582013-04-04 08:37:42 -07001479 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001480
Kenny Root655b9582013-04-04 08:37:42 -07001481 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001482
Kenny Root655b9582013-04-04 08:37:42 -07001483 typedef struct {
1484 uint32_t version;
1485 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001486
Kenny Root655b9582013-04-04 08:37:42 -07001487 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001488
Kenny Root655b9582013-04-04 08:37:42 -07001489 const grant_t* getGrant(const char* filename, uid_t uid) const {
1490 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1491 it != mGrants.end(); it++) {
1492 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001493 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001494 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001495 return grant;
1496 }
1497 }
Kenny Root70e3a862012-02-15 17:20:23 -08001498 return NULL;
1499 }
1500
Kenny Root822c3a92012-03-23 16:34:39 -07001501 /**
1502 * Upgrade code. This will upgrade the key from the current version
1503 * to whatever is newest.
1504 */
Kenny Root655b9582013-04-04 08:37:42 -07001505 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1506 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001507 bool updated = false;
1508 uint8_t version = oldVersion;
1509
1510 /* From V0 -> V1: All old types were unknown */
1511 if (version == 0) {
1512 ALOGV("upgrading to version 1 and setting type %d", type);
1513
1514 blob->setType(type);
1515 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001516 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001517 }
1518 version = 1;
1519 updated = true;
1520 }
1521
Kenny Rootf9119d62013-04-03 09:22:15 -07001522 /* From V1 -> V2: All old keys were encrypted */
1523 if (version == 1) {
1524 ALOGV("upgrading to version 2");
1525
1526 blob->setEncrypted(true);
1527 version = 2;
1528 updated = true;
1529 }
1530
Kenny Root822c3a92012-03-23 16:34:39 -07001531 /*
1532 * If we've updated, set the key blob to the right version
1533 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001534 */
Kenny Root822c3a92012-03-23 16:34:39 -07001535 if (updated) {
1536 ALOGV("updated and writing file %s", filename);
1537 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001538 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001539
1540 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001541 }
1542
1543 /**
1544 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1545 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1546 * Then it overwrites the original blob with the new blob
1547 * format that is returned from the keymaster.
1548 */
Kenny Root655b9582013-04-04 08:37:42 -07001549 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001550 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1551 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1552 if (b.get() == NULL) {
1553 ALOGE("Problem instantiating BIO");
1554 return SYSTEM_ERROR;
1555 }
1556
1557 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1558 if (pkey.get() == NULL) {
1559 ALOGE("Couldn't read old PEM file");
1560 return SYSTEM_ERROR;
1561 }
1562
1563 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1564 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1565 if (len < 0) {
1566 ALOGE("Couldn't measure PKCS#8 length");
1567 return SYSTEM_ERROR;
1568 }
1569
Kenny Root70c98892013-02-07 09:10:36 -08001570 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1571 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001572 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1573 ALOGE("Couldn't convert to PKCS#8");
1574 return SYSTEM_ERROR;
1575 }
1576
Chad Brubaker72593ee2015-05-12 10:42:00 -07001577 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001578 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001579 if (rc != NO_ERROR) {
1580 return rc;
1581 }
1582
Kenny Root655b9582013-04-04 08:37:42 -07001583 return get(filename, blob, TYPE_KEY_PAIR, uid);
1584 }
1585
1586 void readMetaData() {
1587 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1588 if (in < 0) {
1589 return;
1590 }
1591 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1592 if (fileLength != sizeof(mMetaData)) {
1593 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1594 sizeof(mMetaData));
1595 }
1596 close(in);
1597 }
1598
1599 void writeMetaData() {
1600 const char* tmpFileName = ".metadata.tmp";
1601 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1602 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1603 if (out < 0) {
1604 ALOGE("couldn't write metadata file: %s", strerror(errno));
1605 return;
1606 }
1607 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1608 if (fileLength != sizeof(mMetaData)) {
1609 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1610 sizeof(mMetaData));
1611 }
1612 close(out);
1613 rename(tmpFileName, sMetaDataFile);
1614 }
1615
1616 bool upgradeKeystore() {
1617 bool upgraded = false;
1618
1619 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001620 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001621
1622 // Initialize first so the directory is made.
1623 userState->initialize();
1624
1625 // Migrate the old .masterkey file to user 0.
1626 if (access(sOldMasterKey, R_OK) == 0) {
1627 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1628 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1629 return false;
1630 }
1631 }
1632
1633 // Initialize again in case we had a key.
1634 userState->initialize();
1635
1636 // Try to migrate existing keys.
1637 DIR* dir = opendir(".");
1638 if (!dir) {
1639 // Give up now; maybe we can upgrade later.
1640 ALOGE("couldn't open keystore's directory; something is wrong");
1641 return false;
1642 }
1643
1644 struct dirent* file;
1645 while ((file = readdir(dir)) != NULL) {
1646 // We only care about files.
1647 if (file->d_type != DT_REG) {
1648 continue;
1649 }
1650
1651 // Skip anything that starts with a "."
1652 if (file->d_name[0] == '.') {
1653 continue;
1654 }
1655
1656 // Find the current file's user.
1657 char* end;
1658 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1659 if (end[0] != '_' || end[1] == 0) {
1660 continue;
1661 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001662 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001663 if (otherUser->getUserId() != 0) {
1664 unlinkat(dirfd(dir), file->d_name, 0);
1665 }
1666
1667 // Rename the file into user directory.
1668 DIR* otherdir = opendir(otherUser->getUserDirName());
1669 if (otherdir == NULL) {
1670 ALOGW("couldn't open user directory for rename");
1671 continue;
1672 }
1673 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1674 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1675 }
1676 closedir(otherdir);
1677 }
1678 closedir(dir);
1679
1680 mMetaData.version = 1;
1681 upgraded = true;
1682 }
1683
1684 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001685 }
Kenny Roota91203b2012-02-15 15:00:46 -08001686};
1687
Kenny Root655b9582013-04-04 08:37:42 -07001688const char* KeyStore::sOldMasterKey = ".masterkey";
1689const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001690
Kenny Root1b0e3932013-09-05 13:06:32 -07001691const android::String16 KeyStore::sRSAKeyType("RSA");
1692
Kenny Root07438c82012-11-02 15:41:02 -07001693namespace android {
1694class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1695public:
1696 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001697 : mKeyStore(keyStore),
1698 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001699 {
Kenny Roota91203b2012-02-15 15:00:46 -08001700 }
Kenny Roota91203b2012-02-15 15:00:46 -08001701
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001702 void binderDied(const wp<IBinder>& who) {
1703 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1704 for (auto token: operations) {
1705 abort(token);
1706 }
Kenny Root822c3a92012-03-23 16:34:39 -07001707 }
Kenny Roota91203b2012-02-15 15:00:46 -08001708
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001709 int32_t getState(int32_t userId) {
1710 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001711 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001712 }
Kenny Roota91203b2012-02-15 15:00:46 -08001713
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001714 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001715 }
1716
Kenny Root07438c82012-11-02 15:41:02 -07001717 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001718 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001719 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001720 }
Kenny Root07438c82012-11-02 15:41:02 -07001721
Chad Brubaker9489b792015-04-14 11:01:45 -07001722 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001723 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001724 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001725
Kenny Root655b9582013-04-04 08:37:42 -07001726 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001727 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001728 if (responseCode != ::NO_ERROR) {
1729 *item = NULL;
1730 *itemLength = 0;
1731 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001732 }
Kenny Roota91203b2012-02-15 15:00:46 -08001733
Kenny Root07438c82012-11-02 15:41:02 -07001734 *item = (uint8_t*) malloc(keyBlob.getLength());
1735 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1736 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001737
Kenny Root07438c82012-11-02 15:41:02 -07001738 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001739 }
1740
Kenny Rootf9119d62013-04-03 09:22:15 -07001741 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1742 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001743 targetUid = getEffectiveUid(targetUid);
1744 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1745 flags & KEYSTORE_FLAG_ENCRYPTED);
1746 if (result != ::NO_ERROR) {
1747 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001748 }
1749
Kenny Root07438c82012-11-02 15:41:02 -07001750 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001751 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001752
1753 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001754 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1755
Chad Brubaker72593ee2015-05-12 10:42:00 -07001756 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001757 }
1758
Kenny Root49468902013-03-19 13:41:33 -07001759 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001760 targetUid = getEffectiveUid(targetUid);
1761 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001762 return ::PERMISSION_DENIED;
1763 }
Kenny Root07438c82012-11-02 15:41:02 -07001764 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001765 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001766 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001767 }
1768
Kenny Root49468902013-03-19 13:41:33 -07001769 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001770 targetUid = getEffectiveUid(targetUid);
1771 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001772 return ::PERMISSION_DENIED;
1773 }
1774
Kenny Root07438c82012-11-02 15:41:02 -07001775 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001776 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001777
Kenny Root655b9582013-04-04 08:37:42 -07001778 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001779 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1780 }
1781 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001782 }
1783
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001784 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001785 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001786 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001787 return ::PERMISSION_DENIED;
1788 }
Kenny Root07438c82012-11-02 15:41:02 -07001789 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001790 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001791
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001792 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001793 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001794 }
Kenny Root07438c82012-11-02 15:41:02 -07001795 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001796 }
1797
Kenny Root07438c82012-11-02 15:41:02 -07001798 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001799 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001800 return ::PERMISSION_DENIED;
1801 }
1802
Chad Brubaker9489b792015-04-14 11:01:45 -07001803 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001804 mKeyStore->resetUser(get_user_id(callingUid), false);
1805 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001806 }
1807
Chad Brubaker96d6d782015-05-07 10:19:40 -07001808 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001809 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001810 return ::PERMISSION_DENIED;
1811 }
Kenny Root70e3a862012-02-15 17:20:23 -08001812
Kenny Root07438c82012-11-02 15:41:02 -07001813 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001814 // Flush the auth token table to prevent stale tokens from sticking
1815 // around.
1816 mAuthTokenTable.Clear();
1817
1818 if (password.size() == 0) {
1819 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001820 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001821 return ::NO_ERROR;
1822 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001823 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001824 case ::STATE_UNINITIALIZED: {
1825 // generate master key, encrypt with password, write to file,
1826 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001827 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001828 }
1829 case ::STATE_NO_ERROR: {
1830 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001831 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001832 }
1833 case ::STATE_LOCKED: {
1834 ALOGE("Changing user %d's password while locked, clearing old encryption",
1835 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001836 mKeyStore->resetUser(userId, true);
1837 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001838 }
Kenny Root07438c82012-11-02 15:41:02 -07001839 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001840 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001841 }
Kenny Root70e3a862012-02-15 17:20:23 -08001842 }
1843
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001844 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1845 if (!checkBinderPermission(P_USER_CHANGED)) {
1846 return ::PERMISSION_DENIED;
1847 }
1848
1849 // Sanity check that the new user has an empty keystore.
1850 if (!mKeyStore->isEmpty(userId)) {
1851 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1852 }
1853 // Unconditionally clear the keystore, just to be safe.
1854 mKeyStore->resetUser(userId, false);
1855
1856 // If the user has a parent user then use the parent's
1857 // masterkey/password, otherwise there's nothing to do.
1858 if (parentId != -1) {
1859 return mKeyStore->copyMasterKey(parentId, userId);
1860 } else {
1861 return ::NO_ERROR;
1862 }
1863 }
1864
1865 int32_t onUserRemoved(int32_t userId) {
1866 if (!checkBinderPermission(P_USER_CHANGED)) {
1867 return ::PERMISSION_DENIED;
1868 }
1869
1870 mKeyStore->resetUser(userId, false);
1871 return ::NO_ERROR;
1872 }
1873
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001874 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001875 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001876 return ::PERMISSION_DENIED;
1877 }
Kenny Root70e3a862012-02-15 17:20:23 -08001878
Chad Brubaker72593ee2015-05-12 10:42:00 -07001879 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001880 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001881 ALOGD("calling lock in state: %d", state);
1882 return state;
1883 }
1884
Chad Brubaker72593ee2015-05-12 10:42:00 -07001885 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001886 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001887 }
1888
Chad Brubaker96d6d782015-05-07 10:19:40 -07001889 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001890 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001891 return ::PERMISSION_DENIED;
1892 }
1893
Chad Brubaker72593ee2015-05-12 10:42:00 -07001894 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001895 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001896 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001897 return state;
1898 }
1899
1900 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001901 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001902 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001903 }
1904
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001905 bool isEmpty(int32_t userId) {
1906 if (!checkBinderPermission(P_IS_EMPTY)) {
1907 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001908 }
Kenny Root70e3a862012-02-15 17:20:23 -08001909
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001910 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001911 }
1912
Kenny Root96427ba2013-08-16 14:02:41 -07001913 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1914 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001915 targetUid = getEffectiveUid(targetUid);
1916 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1917 flags & KEYSTORE_FLAG_ENCRYPTED);
1918 if (result != ::NO_ERROR) {
1919 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001920 }
Kenny Root07438c82012-11-02 15:41:02 -07001921
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001922 KeymasterArguments params;
Shawn Willden2de8b752015-07-23 05:54:31 -06001923 addLegacyKeyAuthorizations(params.params, keyType);
Kenny Root07438c82012-11-02 15:41:02 -07001924
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001925 switch (keyType) {
1926 case EVP_PKEY_EC: {
1927 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
1928 if (keySize == -1) {
1929 keySize = EC_DEFAULT_KEY_SIZE;
1930 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1931 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07001932 return ::SYSTEM_ERROR;
1933 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001934 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1935 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001936 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001937 case EVP_PKEY_RSA: {
1938 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1939 if (keySize == -1) {
1940 keySize = RSA_DEFAULT_KEY_SIZE;
1941 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1942 ALOGI("invalid key size %d", keySize);
1943 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07001944 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001945 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1946 unsigned long exponent = RSA_DEFAULT_EXPONENT;
1947 if (args->size() > 1) {
1948 ALOGI("invalid number of arguments: %zu", args->size());
1949 return ::SYSTEM_ERROR;
1950 } else if (args->size() == 1) {
1951 sp<KeystoreArg> expArg = args->itemAt(0);
1952 if (expArg != NULL) {
1953 Unique_BIGNUM pubExpBn(
1954 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
1955 expArg->size(), NULL));
1956 if (pubExpBn.get() == NULL) {
1957 ALOGI("Could not convert public exponent to BN");
1958 return ::SYSTEM_ERROR;
1959 }
1960 exponent = BN_get_word(pubExpBn.get());
1961 if (exponent == 0xFFFFFFFFL) {
1962 ALOGW("cannot represent public exponent as a long value");
1963 return ::SYSTEM_ERROR;
1964 }
1965 } else {
1966 ALOGW("public exponent not read");
1967 return ::SYSTEM_ERROR;
1968 }
1969 }
1970 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
1971 exponent));
1972 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001973 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001974 default: {
1975 ALOGW("Unsupported key type %d", keyType);
1976 return ::SYSTEM_ERROR;
1977 }
Kenny Root96427ba2013-08-16 14:02:41 -07001978 }
1979
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001980 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
1981 /*outCharacteristics*/ NULL);
1982 if (rc != ::NO_ERROR) {
1983 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07001984 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001985 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08001986 }
1987
Kenny Rootf9119d62013-04-03 09:22:15 -07001988 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1989 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001990 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07001991
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001992 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
1993 if (!pkcs8.get()) {
1994 return ::SYSTEM_ERROR;
1995 }
1996 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1997 if (!pkey.get()) {
1998 return ::SYSTEM_ERROR;
1999 }
2000 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002001 KeymasterArguments params;
2002 addLegacyKeyAuthorizations(params.params, type);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002003 switch (type) {
2004 case EVP_PKEY_RSA:
2005 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2006 break;
2007 case EVP_PKEY_EC:
2008 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2009 KM_ALGORITHM_EC));
2010 break;
2011 default:
2012 ALOGW("Unsupported key type %d", type);
2013 return ::SYSTEM_ERROR;
2014 }
2015 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2016 /*outCharacteristics*/ NULL);
2017 if (rc != ::NO_ERROR) {
2018 ALOGW("importKey failed: %d", rc);
2019 }
2020 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002021 }
2022
Kenny Root07438c82012-11-02 15:41:02 -07002023 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002024 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002025 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002026 return ::PERMISSION_DENIED;
2027 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002028 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002029 }
2030
Kenny Root07438c82012-11-02 15:41:02 -07002031 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2032 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002033 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002034 return ::PERMISSION_DENIED;
2035 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002036 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2037 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002038 }
Kenny Root07438c82012-11-02 15:41:02 -07002039
2040 /*
2041 * TODO: The abstraction between things stored in hardware and regular blobs
2042 * of data stored on the filesystem should be moved down to keystore itself.
2043 * Unfortunately the Java code that calls this has naming conventions that it
2044 * knows about. Ideally keystore shouldn't be used to store random blobs of
2045 * data.
2046 *
2047 * Until that happens, it's necessary to have a separate "get_pubkey" and
2048 * "del_key" since the Java code doesn't really communicate what it's
2049 * intentions are.
2050 */
2051 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002052 ExportResult result;
2053 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2054 if (result.resultCode != ::NO_ERROR) {
2055 ALOGW("export failed: %d", result.resultCode);
2056 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002057 }
Kenny Root07438c82012-11-02 15:41:02 -07002058
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002059 *pubkey = result.exportData.release();
2060 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002061 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002062 }
Kenny Root07438c82012-11-02 15:41:02 -07002063
Kenny Root07438c82012-11-02 15:41:02 -07002064 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002065 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002066 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2067 if (result != ::NO_ERROR) {
2068 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002069 }
2070
2071 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002072 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002073
Kenny Root655b9582013-04-04 08:37:42 -07002074 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002075 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2076 }
2077
Kenny Root655b9582013-04-04 08:37:42 -07002078 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002079 return ::NO_ERROR;
2080 }
2081
2082 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002083 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002084 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2085 if (result != ::NO_ERROR) {
2086 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002087 }
2088
2089 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002090 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002091
Kenny Root655b9582013-04-04 08:37:42 -07002092 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002093 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2094 }
2095
Kenny Root655b9582013-04-04 08:37:42 -07002096 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002097 }
2098
2099 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002100 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002101 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002102 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002103 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002104 }
Kenny Root07438c82012-11-02 15:41:02 -07002105
2106 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002107 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002108
Kenny Root655b9582013-04-04 08:37:42 -07002109 if (access(filename.string(), R_OK) == -1) {
2110 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002111 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002112 }
2113
Kenny Root655b9582013-04-04 08:37:42 -07002114 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002115 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002116 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002117 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002118 }
2119
2120 struct stat s;
2121 int ret = fstat(fd, &s);
2122 close(fd);
2123 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002124 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002125 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002126 }
2127
Kenny Root36a9e232013-02-04 14:24:15 -08002128 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002129 }
2130
Kenny Rootd53bc922013-03-21 14:10:15 -07002131 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2132 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002133 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002134 pid_t spid = IPCThreadState::self()->getCallingPid();
2135 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002136 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002137 return -1L;
2138 }
2139
Chad Brubaker72593ee2015-05-12 10:42:00 -07002140 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002141 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002142 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002143 return state;
2144 }
2145
Kenny Rootd53bc922013-03-21 14:10:15 -07002146 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2147 srcUid = callingUid;
2148 } else if (!is_granted_to(callingUid, srcUid)) {
2149 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002150 return ::PERMISSION_DENIED;
2151 }
2152
Kenny Rootd53bc922013-03-21 14:10:15 -07002153 if (destUid == -1) {
2154 destUid = callingUid;
2155 }
2156
2157 if (srcUid != destUid) {
2158 if (static_cast<uid_t>(srcUid) != callingUid) {
2159 ALOGD("can only duplicate from caller to other or to same uid: "
2160 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2161 return ::PERMISSION_DENIED;
2162 }
2163
2164 if (!is_granted_to(callingUid, destUid)) {
2165 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2166 return ::PERMISSION_DENIED;
2167 }
2168 }
2169
2170 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002171 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002172
Kenny Rootd53bc922013-03-21 14:10:15 -07002173 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002174 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002175
Kenny Root655b9582013-04-04 08:37:42 -07002176 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2177 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002178 return ::SYSTEM_ERROR;
2179 }
2180
Kenny Rootd53bc922013-03-21 14:10:15 -07002181 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002182 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002183 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002184 if (responseCode != ::NO_ERROR) {
2185 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002186 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002187
Chad Brubaker72593ee2015-05-12 10:42:00 -07002188 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002189 }
2190
Kenny Root1b0e3932013-09-05 13:06:32 -07002191 int32_t is_hardware_backed(const String16& keyType) {
2192 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002193 }
2194
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002195 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002196 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002197 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002198 return ::PERMISSION_DENIED;
2199 }
2200
Robin Lee4b84fdc2014-09-24 11:56:57 +01002201 String8 prefix = String8::format("%u_", targetUid);
2202 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002203 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002204 return ::SYSTEM_ERROR;
2205 }
2206
Robin Lee4b84fdc2014-09-24 11:56:57 +01002207 for (uint32_t i = 0; i < aliases.size(); i++) {
2208 String8 name8(aliases[i]);
2209 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002210 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002211 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002212 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002213 }
2214
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002215 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2216 const keymaster1_device_t* device = mKeyStore->getDevice();
2217 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2218 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2219 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2220 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2221 device->add_rng_entropy != NULL) {
2222 devResult = device->add_rng_entropy(device, data, dataLength);
2223 }
2224 if (fallback->add_rng_entropy) {
2225 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2226 }
2227 if (devResult) {
2228 return devResult;
2229 }
2230 if (fallbackResult) {
2231 return fallbackResult;
2232 }
2233 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002234 }
2235
Chad Brubaker17d68b92015-02-05 22:04:16 -08002236 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002237 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2238 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002239 uid = getEffectiveUid(uid);
2240 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2241 flags & KEYSTORE_FLAG_ENCRYPTED);
2242 if (rc != ::NO_ERROR) {
2243 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002244 }
2245
Chad Brubaker9489b792015-04-14 11:01:45 -07002246 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002247 bool isFallback = false;
2248 keymaster_key_blob_t blob;
2249 keymaster_key_characteristics_t *out = NULL;
2250
2251 const keymaster1_device_t* device = mKeyStore->getDevice();
2252 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002253 std::vector<keymaster_key_param_t> opParams(params.params);
2254 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002255 if (device == NULL) {
2256 return ::SYSTEM_ERROR;
2257 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002258 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002259 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2260 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002261 if (!entropy) {
2262 rc = KM_ERROR_OK;
2263 } else if (device->add_rng_entropy) {
2264 rc = device->add_rng_entropy(device, entropy, entropyLength);
2265 } else {
2266 rc = KM_ERROR_UNIMPLEMENTED;
2267 }
2268 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002269 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002270 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002271 }
2272 // If the HW device didn't support generate_key or generate_key failed
2273 // fall back to the software implementation.
2274 if (rc && fallback->generate_key != NULL) {
2275 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002276 if (!entropy) {
2277 rc = KM_ERROR_OK;
2278 } else if (fallback->add_rng_entropy) {
2279 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2280 } else {
2281 rc = KM_ERROR_UNIMPLEMENTED;
2282 }
2283 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002284 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002285 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002286 }
2287
2288 if (out) {
2289 if (outCharacteristics) {
2290 outCharacteristics->characteristics = *out;
2291 } else {
2292 keymaster_free_characteristics(out);
2293 }
2294 free(out);
2295 }
2296
2297 if (rc) {
2298 return rc;
2299 }
2300
2301 String8 name8(name);
2302 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2303
2304 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2305 keyBlob.setFallback(isFallback);
2306 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2307
2308 free(const_cast<uint8_t*>(blob.key_material));
2309
Chad Brubaker72593ee2015-05-12 10:42:00 -07002310 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002311 }
2312
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002313 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002314 const keymaster_blob_t* clientId,
2315 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002316 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002317 if (!outCharacteristics) {
2318 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2319 }
2320
2321 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2322
2323 Blob keyBlob;
2324 String8 name8(name);
2325 int rc;
2326
2327 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2328 TYPE_KEYMASTER_10);
2329 if (responseCode != ::NO_ERROR) {
2330 return responseCode;
2331 }
2332 keymaster_key_blob_t key;
2333 key.key_material_size = keyBlob.getLength();
2334 key.key_material = keyBlob.getValue();
2335 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2336 keymaster_key_characteristics_t *out = NULL;
2337 if (!dev->get_key_characteristics) {
2338 ALOGW("device does not implement get_key_characteristics");
2339 return KM_ERROR_UNIMPLEMENTED;
2340 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002341 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002342 if (out) {
2343 outCharacteristics->characteristics = *out;
2344 free(out);
2345 }
2346 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002347 }
2348
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002349 int32_t importKey(const String16& name, const KeymasterArguments& params,
2350 keymaster_key_format_t format, const uint8_t *keyData,
2351 size_t keyLength, int uid, int flags,
2352 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002353 uid = getEffectiveUid(uid);
2354 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2355 flags & KEYSTORE_FLAG_ENCRYPTED);
2356 if (rc != ::NO_ERROR) {
2357 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002358 }
2359
Chad Brubaker9489b792015-04-14 11:01:45 -07002360 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002361 bool isFallback = false;
2362 keymaster_key_blob_t blob;
2363 keymaster_key_characteristics_t *out = NULL;
2364
2365 const keymaster1_device_t* device = mKeyStore->getDevice();
2366 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002367 std::vector<keymaster_key_param_t> opParams(params.params);
2368 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2369 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002370 if (device == NULL) {
2371 return ::SYSTEM_ERROR;
2372 }
2373 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2374 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002375 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002376 }
2377 if (rc && fallback->import_key != NULL) {
2378 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002379 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002380 }
2381 if (out) {
2382 if (outCharacteristics) {
2383 outCharacteristics->characteristics = *out;
2384 } else {
2385 keymaster_free_characteristics(out);
2386 }
2387 free(out);
2388 }
2389 if (rc) {
2390 return rc;
2391 }
2392
2393 String8 name8(name);
2394 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2395
2396 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2397 keyBlob.setFallback(isFallback);
2398 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2399
2400 free((void*) blob.key_material);
2401
Chad Brubaker72593ee2015-05-12 10:42:00 -07002402 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002403 }
2404
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002405 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002406 const keymaster_blob_t* clientId,
2407 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002408
2409 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2410
2411 Blob keyBlob;
2412 String8 name8(name);
2413 int rc;
2414
2415 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2416 TYPE_KEYMASTER_10);
2417 if (responseCode != ::NO_ERROR) {
2418 result->resultCode = responseCode;
2419 return;
2420 }
2421 keymaster_key_blob_t key;
2422 key.key_material_size = keyBlob.getLength();
2423 key.key_material = keyBlob.getValue();
2424 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2425 if (!dev->export_key) {
2426 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2427 return;
2428 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002429 keymaster_blob_t output = {NULL, 0};
2430 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2431 result->exportData.reset(const_cast<uint8_t*>(output.data));
2432 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002433 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002434 }
2435
Chad Brubakerad6514a2015-04-09 14:00:26 -07002436
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002437 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002438 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002439 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002440 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2441 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2442 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2443 result->resultCode = ::PERMISSION_DENIED;
2444 return;
2445 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002446 if (!checkAllowedOperationParams(params.params)) {
2447 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2448 return;
2449 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002450 Blob keyBlob;
2451 String8 name8(name);
2452 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2453 TYPE_KEYMASTER_10);
2454 if (responseCode != ::NO_ERROR) {
2455 result->resultCode = responseCode;
2456 return;
2457 }
2458 keymaster_key_blob_t key;
2459 key.key_material_size = keyBlob.getLength();
2460 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002461 keymaster_operation_handle_t handle;
2462 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002463 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002464 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002465 Unique_keymaster_key_characteristics characteristics;
2466 characteristics.reset(new keymaster_key_characteristics_t);
2467 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2468 if (err) {
2469 result->resultCode = err;
2470 return;
2471 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002472 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002473 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002474 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002475 // If per-operation auth is needed we need to begin the operation and
2476 // the client will need to authorize that operation before calling
2477 // update. Any other auth issues stop here.
2478 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2479 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002480 return;
2481 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002482 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002483 // Add entropy to the device first.
2484 if (entropy) {
2485 if (dev->add_rng_entropy) {
2486 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2487 } else {
2488 err = KM_ERROR_UNIMPLEMENTED;
2489 }
2490 if (err) {
2491 result->resultCode = err;
2492 return;
2493 }
2494 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002495 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002496
Shawn Willden9221bff2015-06-18 18:23:54 -06002497 // Create a keyid for this key.
2498 keymaster::km_id_t keyid;
2499 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2500 ALOGE("Failed to create a key ID for authorization checking.");
2501 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2502 return;
2503 }
2504
2505 // Check that all key authorization policy requirements are met.
2506 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2507 key_auths.push_back(characteristics->sw_enforced);
2508 keymaster::AuthorizationSet operation_params(inParams);
2509 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2510 0 /* op_handle */,
2511 true /* is_begin_operation */);
2512 if (err) {
2513 result->resultCode = err;
2514 return;
2515 }
2516
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002517 keymaster_key_param_set_t outParams = {NULL, 0};
2518 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2519
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002520 // If there are too many operations abort the oldest operation that was
2521 // started as pruneable and try again.
2522 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2523 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2524 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002525
2526 // We mostly ignore errors from abort() below because all we care about is whether at
2527 // least one pruneable operation has been removed.
2528 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2529 int abort_error = abort(oldest);
2530 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2531 if (op_count_after >= op_count_before) {
2532 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2533 ALOGE("Failed to remove pruneable operation %p, error: %d",
2534 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002535 break;
2536 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002537 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002538 }
2539 if (err) {
2540 result->resultCode = err;
2541 return;
2542 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002543
Shawn Willden9221bff2015-06-18 18:23:54 -06002544 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2545 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002546 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002547 if (authToken) {
2548 mOperationMap.setOperationAuthToken(operationToken, authToken);
2549 }
2550 // Return the authentication lookup result. If this is a per operation
2551 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2552 // application should get an auth token using the handle before the
2553 // first call to update, which will fail if keystore hasn't received the
2554 // auth token.
2555 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002556 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002557 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002558 if (outParams.params) {
2559 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2560 free(outParams.params);
2561 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002562 }
2563
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002564 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2565 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002566 if (!checkAllowedOperationParams(params.params)) {
2567 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2568 return;
2569 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002570 const keymaster1_device_t* dev;
2571 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002572 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002573 keymaster::km_id_t keyid;
2574 const keymaster_key_characteristics_t* characteristics;
2575 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002576 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2577 return;
2578 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002579 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002580 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2581 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002582 result->resultCode = authResult;
2583 return;
2584 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002585 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2586 keymaster_blob_t input = {data, dataLength};
2587 size_t consumed = 0;
2588 keymaster_blob_t output = {NULL, 0};
2589 keymaster_key_param_set_t outParams = {NULL, 0};
2590
Shawn Willden9221bff2015-06-18 18:23:54 -06002591 // Check that all key authorization policy requirements are met.
2592 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2593 key_auths.push_back(characteristics->sw_enforced);
2594 keymaster::AuthorizationSet operation_params(inParams);
2595 result->resultCode =
2596 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2597 operation_params, handle,
2598 false /* is_begin_operation */);
2599 if (result->resultCode) {
2600 return;
2601 }
2602
Chad Brubaker57e106d2015-06-01 12:59:00 -07002603 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2604 &output);
2605 result->data.reset(const_cast<uint8_t*>(output.data));
2606 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002607 result->inputConsumed = consumed;
2608 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002609 if (outParams.params) {
2610 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2611 free(outParams.params);
2612 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002613 }
2614
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002615 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002616 const uint8_t* signature, size_t signatureLength,
2617 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002618 if (!checkAllowedOperationParams(params.params)) {
2619 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2620 return;
2621 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002622 const keymaster1_device_t* dev;
2623 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002624 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002625 keymaster::km_id_t keyid;
2626 const keymaster_key_characteristics_t* characteristics;
2627 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002628 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2629 return;
2630 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002631 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002632 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2633 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002634 result->resultCode = authResult;
2635 return;
2636 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002637 keymaster_error_t err;
2638 if (entropy) {
2639 if (dev->add_rng_entropy) {
2640 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2641 } else {
2642 err = KM_ERROR_UNIMPLEMENTED;
2643 }
2644 if (err) {
2645 result->resultCode = err;
2646 return;
2647 }
2648 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002649
Chad Brubaker57e106d2015-06-01 12:59:00 -07002650 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2651 keymaster_blob_t input = {signature, signatureLength};
2652 keymaster_blob_t output = {NULL, 0};
2653 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002654
2655 // Check that all key authorization policy requirements are met.
2656 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2657 key_auths.push_back(characteristics->sw_enforced);
2658 keymaster::AuthorizationSet operation_params(inParams);
2659 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2660 handle, false /* is_begin_operation */);
2661 if (err) {
2662 result->resultCode = err;
2663 return;
2664 }
2665
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002666 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002667 // Remove the operation regardless of the result
2668 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002669 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002670
2671 result->data.reset(const_cast<uint8_t*>(output.data));
2672 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002673 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002674 if (outParams.params) {
2675 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2676 free(outParams.params);
2677 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002678 }
2679
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002680 int32_t abort(const sp<IBinder>& token) {
2681 const keymaster1_device_t* dev;
2682 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002683 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002684 keymaster::km_id_t keyid;
2685 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002686 return KM_ERROR_INVALID_OPERATION_HANDLE;
2687 }
2688 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002689 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002690 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002691 rc = KM_ERROR_UNIMPLEMENTED;
2692 } else {
2693 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002694 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002695 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002696 if (rc) {
2697 return rc;
2698 }
2699 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002700 }
2701
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002702 bool isOperationAuthorized(const sp<IBinder>& token) {
2703 const keymaster1_device_t* dev;
2704 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002705 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002706 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002707 keymaster::km_id_t keyid;
2708 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002709 return false;
2710 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002711 const hw_auth_token_t* authToken = NULL;
2712 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002713 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002714 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2715 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002716 }
2717
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002718 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002719 if (!checkBinderPermission(P_ADD_AUTH)) {
2720 ALOGW("addAuthToken: permission denied for %d",
2721 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002722 return ::PERMISSION_DENIED;
2723 }
2724 if (length != sizeof(hw_auth_token_t)) {
2725 return KM_ERROR_INVALID_ARGUMENT;
2726 }
2727 hw_auth_token_t* authToken = new hw_auth_token_t;
2728 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2729 // The table takes ownership of authToken.
2730 mAuthTokenTable.AddAuthenticationToken(authToken);
2731 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002732 }
2733
Kenny Root07438c82012-11-02 15:41:02 -07002734private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002735 static const int32_t UID_SELF = -1;
2736
2737 /**
2738 * Get the effective target uid for a binder operation that takes an
2739 * optional uid as the target.
2740 */
2741 inline uid_t getEffectiveUid(int32_t targetUid) {
2742 if (targetUid == UID_SELF) {
2743 return IPCThreadState::self()->getCallingUid();
2744 }
2745 return static_cast<uid_t>(targetUid);
2746 }
2747
2748 /**
2749 * Check if the caller of the current binder method has the required
2750 * permission and if acting on other uids the grants to do so.
2751 */
2752 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2753 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2754 pid_t spid = IPCThreadState::self()->getCallingPid();
2755 if (!has_permission(callingUid, permission, spid)) {
2756 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2757 return false;
2758 }
2759 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2760 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2761 return false;
2762 }
2763 return true;
2764 }
2765
2766 /**
2767 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002768 * permission and the target uid is the caller or the caller is system.
2769 */
2770 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2771 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2772 pid_t spid = IPCThreadState::self()->getCallingPid();
2773 if (!has_permission(callingUid, permission, spid)) {
2774 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2775 return false;
2776 }
2777 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2778 }
2779
2780 /**
2781 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002782 * permission or the target of the operation is the caller's uid. This is
2783 * for operation where the permission is only for cross-uid activity and all
2784 * uids are allowed to act on their own (ie: clearing all entries for a
2785 * given uid).
2786 */
2787 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2788 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2789 if (getEffectiveUid(targetUid) == callingUid) {
2790 return true;
2791 } else {
2792 return checkBinderPermission(permission, targetUid);
2793 }
2794 }
2795
2796 /**
2797 * Helper method to check that the caller has the required permission as
2798 * well as the keystore is in the unlocked state if checkUnlocked is true.
2799 *
2800 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2801 * otherwise the state of keystore when not unlocked and checkUnlocked is
2802 * true.
2803 */
2804 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2805 bool checkUnlocked = true) {
2806 if (!checkBinderPermission(permission, targetUid)) {
2807 return ::PERMISSION_DENIED;
2808 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002809 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002810 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2811 return state;
2812 }
2813
2814 return ::NO_ERROR;
2815
2816 }
2817
Kenny Root9d45d1c2013-02-14 10:32:30 -08002818 inline bool isKeystoreUnlocked(State state) {
2819 switch (state) {
2820 case ::STATE_NO_ERROR:
2821 return true;
2822 case ::STATE_UNINITIALIZED:
2823 case ::STATE_LOCKED:
2824 return false;
2825 }
2826 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002827 }
2828
Chad Brubaker67d2a502015-03-11 17:21:18 +00002829 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002830 const int32_t device_api = device->common.module->module_api_version;
2831 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2832 switch (keyType) {
2833 case TYPE_RSA:
2834 case TYPE_DSA:
2835 case TYPE_EC:
2836 return true;
2837 default:
2838 return false;
2839 }
2840 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2841 switch (keyType) {
2842 case TYPE_RSA:
2843 return true;
2844 case TYPE_DSA:
2845 return device->flags & KEYMASTER_SUPPORTS_DSA;
2846 case TYPE_EC:
2847 return device->flags & KEYMASTER_SUPPORTS_EC;
2848 default:
2849 return false;
2850 }
2851 } else {
2852 return keyType == TYPE_RSA;
2853 }
2854 }
2855
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002856 /**
2857 * Check that all keymaster_key_param_t's provided by the application are
2858 * allowed. Any parameter that keystore adds itself should be disallowed here.
2859 */
2860 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2861 for (auto param: params) {
2862 switch (param.tag) {
2863 case KM_TAG_AUTH_TOKEN:
2864 return false;
2865 default:
2866 break;
2867 }
2868 }
2869 return true;
2870 }
2871
2872 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2873 const keymaster1_device_t* dev,
2874 const std::vector<keymaster_key_param_t>& params,
2875 keymaster_key_characteristics_t* out) {
2876 UniquePtr<keymaster_blob_t> appId;
2877 UniquePtr<keymaster_blob_t> appData;
2878 for (auto param : params) {
2879 if (param.tag == KM_TAG_APPLICATION_ID) {
2880 appId.reset(new keymaster_blob_t);
2881 appId->data = param.blob.data;
2882 appId->data_length = param.blob.data_length;
2883 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2884 appData.reset(new keymaster_blob_t);
2885 appData->data = param.blob.data;
2886 appData->data_length = param.blob.data_length;
2887 }
2888 }
2889 keymaster_key_characteristics_t* result = NULL;
2890 if (!dev->get_key_characteristics) {
2891 return KM_ERROR_UNIMPLEMENTED;
2892 }
2893 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2894 appData.get(), &result);
2895 if (result) {
2896 *out = *result;
2897 free(result);
2898 }
2899 return error;
2900 }
2901
2902 /**
2903 * Get the auth token for this operation from the auth token table.
2904 *
2905 * Returns ::NO_ERROR if the auth token was set or none was required.
2906 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2907 * authorization token exists for that operation and
2908 * failOnTokenMissing is false.
2909 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2910 * token for the operation
2911 */
2912 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2913 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002914 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002915 const hw_auth_token_t** authToken,
2916 bool failOnTokenMissing = true) {
2917
2918 std::vector<keymaster_key_param_t> allCharacteristics;
2919 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2920 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2921 }
2922 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2923 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2924 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002925 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
2926 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002927 switch (err) {
2928 case keymaster::AuthTokenTable::OK:
2929 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2930 return ::NO_ERROR;
2931 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2932 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2933 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2934 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2935 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2936 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2937 (int32_t) ::OP_AUTH_NEEDED;
2938 default:
2939 ALOGE("Unexpected FindAuthorization return value %d", err);
2940 return KM_ERROR_INVALID_ARGUMENT;
2941 }
2942 }
2943
2944 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2945 const hw_auth_token_t* token) {
2946 if (token) {
2947 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2948 reinterpret_cast<const uint8_t*>(token),
2949 sizeof(hw_auth_token_t)));
2950 }
2951 }
2952
2953 /**
2954 * Add the auth token for the operation to the param list if the operation
2955 * requires authorization. Uses the cached result in the OperationMap if available
2956 * otherwise gets the token from the AuthTokenTable and caches the result.
2957 *
2958 * Returns ::NO_ERROR if the auth token was added or not needed.
2959 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2960 * authenticated.
2961 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2962 * operation token.
2963 */
2964 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2965 std::vector<keymaster_key_param_t>* params) {
2966 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002967 mOperationMap.getOperationAuthToken(token, &authToken);
2968 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002969 const keymaster1_device_t* dev;
2970 keymaster_operation_handle_t handle;
2971 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002972 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002973 keymaster::km_id_t keyid;
2974 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
2975 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002976 return KM_ERROR_INVALID_OPERATION_HANDLE;
2977 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002978 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002979 if (result != ::NO_ERROR) {
2980 return result;
2981 }
2982 if (authToken) {
2983 mOperationMap.setOperationAuthToken(token, authToken);
2984 }
2985 }
2986 addAuthToParams(params, authToken);
2987 return ::NO_ERROR;
2988 }
2989
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002990 /**
2991 * Translate a result value to a legacy return value. All keystore errors are
2992 * preserved and keymaster errors become SYSTEM_ERRORs
2993 */
2994 inline int32_t translateResultToLegacyResult(int32_t result) {
2995 if (result > 0) {
2996 return result;
2997 }
2998 return ::SYSTEM_ERROR;
2999 }
3000
Shawn Willden2de8b752015-07-23 05:54:31 -06003001 void addLegacyKeyAuthorizations(std::vector<keymaster_key_param_t>& params, int keyType) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003002 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
3003 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
3004 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
3005 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
3006 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
Shawn Willden2de8b752015-07-23 05:54:31 -06003007 if (keyType == EVP_PKEY_RSA) {
3008 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
3009 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
3010 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PSS));
3011 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_OAEP));
3012 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003013 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
Shawn Willden2de8b752015-07-23 05:54:31 -06003014 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_MD5));
3015 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA1));
3016 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_224));
3017 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_256));
3018 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_384));
3019 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_512));
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003020 params.push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
3021 params.push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
3022 params.push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
3023 params.push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
3024 params.push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
3025 uint64_t now = keymaster::java_time(time(NULL));
3026 params.push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
3027 }
3028
3029 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3030 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3031 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3032 return &characteristics->hw_enforced.params[i];
3033 }
3034 }
3035 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3036 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3037 return &characteristics->sw_enforced.params[i];
3038 }
3039 }
3040 return NULL;
3041 }
3042
3043 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3044 // All legacy keys are DIGEST_NONE/PAD_NONE.
3045 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3046 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3047
3048 // Look up the algorithm of the key.
3049 KeyCharacteristics characteristics;
3050 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3051 if (rc != ::NO_ERROR) {
3052 ALOGE("Failed to get key characteristics");
3053 return;
3054 }
3055 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3056 if (!algorithm) {
3057 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3058 return;
3059 }
3060 params.push_back(*algorithm);
3061 }
3062
3063 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3064 uint8_t** out, size_t* outLength, const uint8_t* signature,
3065 size_t signatureLength, keymaster_purpose_t purpose) {
3066
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003067 std::basic_stringstream<uint8_t> outBuffer;
3068 OperationResult result;
3069 KeymasterArguments inArgs;
3070 addLegacyBeginParams(name, inArgs.params);
3071 sp<IBinder> appToken(new BBinder);
3072 sp<IBinder> token;
3073
3074 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3075 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003076 if (result.resultCode == ::KEY_NOT_FOUND) {
3077 ALOGW("Key not found");
3078 } else {
3079 ALOGW("Error in begin: %d", result.resultCode);
3080 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003081 return translateResultToLegacyResult(result.resultCode);
3082 }
3083 inArgs.params.clear();
3084 token = result.token;
3085 size_t consumed = 0;
3086 size_t lastConsumed = 0;
3087 do {
3088 update(token, inArgs, data + consumed, length - consumed, &result);
3089 if (result.resultCode != ResponseCode::NO_ERROR) {
3090 ALOGW("Error in update: %d", result.resultCode);
3091 return translateResultToLegacyResult(result.resultCode);
3092 }
3093 if (out) {
3094 outBuffer.write(result.data.get(), result.dataLength);
3095 }
3096 lastConsumed = result.inputConsumed;
3097 consumed += lastConsumed;
3098 } while (consumed < length && lastConsumed > 0);
3099
3100 if (consumed != length) {
3101 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3102 return ::SYSTEM_ERROR;
3103 }
3104
3105 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3106 if (result.resultCode != ResponseCode::NO_ERROR) {
3107 ALOGW("Error in finish: %d", result.resultCode);
3108 return translateResultToLegacyResult(result.resultCode);
3109 }
3110 if (out) {
3111 outBuffer.write(result.data.get(), result.dataLength);
3112 }
3113
3114 if (out) {
3115 auto buf = outBuffer.str();
3116 *out = new uint8_t[buf.size()];
3117 memcpy(*out, buf.c_str(), buf.size());
3118 *outLength = buf.size();
3119 }
3120
3121 return ::NO_ERROR;
3122 }
3123
Kenny Root07438c82012-11-02 15:41:02 -07003124 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003125 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003126 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003127 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003128};
3129
3130}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003131
3132int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003133 if (argc < 2) {
3134 ALOGE("A directory must be specified!");
3135 return 1;
3136 }
3137 if (chdir(argv[1]) == -1) {
3138 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3139 return 1;
3140 }
3141
3142 Entropy entropy;
3143 if (!entropy.open()) {
3144 return 1;
3145 }
Kenny Root70e3a862012-02-15 17:20:23 -08003146
Chad Brubakerbd07a232015-06-01 10:44:27 -07003147 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003148 if (keymaster_device_initialize(&dev)) {
3149 ALOGE("keystore keymaster could not be initialized; exiting");
3150 return 1;
3151 }
3152
Chad Brubaker67d2a502015-03-11 17:21:18 +00003153 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003154 if (fallback_keymaster_device_initialize(&fallback)) {
3155 ALOGE("software keymaster could not be initialized; exiting");
3156 return 1;
3157 }
3158
Riley Spahneaabae92014-06-30 12:39:52 -07003159 ks_is_selinux_enabled = is_selinux_enabled();
3160 if (ks_is_selinux_enabled) {
3161 union selinux_callback cb;
3162 cb.func_log = selinux_log_callback;
3163 selinux_set_callback(SELINUX_CB_LOG, cb);
3164 if (getcon(&tctx) != 0) {
3165 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3166 return -1;
3167 }
3168 } else {
3169 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3170 }
3171
Chad Brubakerbd07a232015-06-01 10:44:27 -07003172 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003173 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003174 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3175 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3176 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3177 if (ret != android::OK) {
3178 ALOGE("Couldn't register binder service!");
3179 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003180 }
Kenny Root07438c82012-11-02 15:41:02 -07003181
3182 /*
3183 * We're the only thread in existence, so we're just going to process
3184 * Binder transaction as a single-threaded program.
3185 */
3186 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003187
3188 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003189 return 1;
3190}