blob: e4b32b946ff3eb23ac436fc24a42489f9e4330fa [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
William Robertse46b8552015-10-02 08:19:52 -0700230struct audit_data {
231 pid_t pid;
232 uid_t uid;
233};
234
Riley Spahneaabae92014-06-30 12:39:52 -0700235static char *tctx;
236static int ks_is_selinux_enabled;
237
238static const char *get_perm_label(perm_t perm) {
239 unsigned int index = ffs(perm);
240 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
241 return perm_labels[index - 1];
242 } else {
243 ALOGE("Keystore: Failed to retrieve permission label.\n");
244 abort();
245 }
246}
247
Kenny Root655b9582013-04-04 08:37:42 -0700248/**
249 * Returns the app ID (in the Android multi-user sense) for the current
250 * UNIX UID.
251 */
252static uid_t get_app_id(uid_t uid) {
253 return uid % AID_USER;
254}
255
256/**
257 * Returns the user ID (in the Android multi-user sense) for the current
258 * UNIX UID.
259 */
260static uid_t get_user_id(uid_t uid) {
261 return uid / AID_USER;
262}
263
William Robertse46b8552015-10-02 08:19:52 -0700264static int audit_callback(void *data, security_class_t /* cls */, char *buf, size_t len)
265{
266 struct audit_data *ad = reinterpret_cast<struct audit_data *>(data);
267 if (!ad) {
268 ALOGE("No keystore audit data");
269 return 0;
270 }
271
272 snprintf(buf, len, "pid=%d uid=%d", ad->pid, ad->uid);
273 return 0;
274}
275
276static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700277 if (!ks_is_selinux_enabled) {
278 return true;
279 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000280
William Robertse46b8552015-10-02 08:19:52 -0700281 audit_data ad;
Riley Spahneaabae92014-06-30 12:39:52 -0700282 char *sctx = NULL;
283 const char *selinux_class = "keystore_key";
284 const char *str_perm = get_perm_label(perm);
285
286 if (!str_perm) {
287 return false;
288 }
289
290 if (getpidcon(spid, &sctx) != 0) {
291 ALOGE("SELinux: Failed to get source pid context.\n");
292 return false;
293 }
294
William Robertse46b8552015-10-02 08:19:52 -0700295 ad.pid = spid;
296 ad.uid = uid;
297
Riley Spahneaabae92014-06-30 12:39:52 -0700298 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
William Robertse46b8552015-10-02 08:19:52 -0700299 reinterpret_cast<void *>(&ad)) == 0;
Riley Spahneaabae92014-06-30 12:39:52 -0700300 freecon(sctx);
301 return allowed;
302}
303
304static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700305 // All system users are equivalent for multi-user support.
306 if (get_app_id(uid) == AID_SYSTEM) {
307 uid = AID_SYSTEM;
308 }
309
Kenny Root07438c82012-11-02 15:41:02 -0700310 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
311 struct user_perm user = user_perms[i];
312 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700313 return (user.perms & perm) &&
314 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700315 }
316 }
317
Riley Spahneaabae92014-06-30 12:39:52 -0700318 return (DEFAULT_PERMS & perm) &&
319 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700320}
321
Kenny Root49468902013-03-19 13:41:33 -0700322/**
323 * Returns the UID that the callingUid should act as. This is here for
324 * legacy support of the WiFi and VPN systems and should be removed
325 * when WiFi can operate in its own namespace.
326 */
Kenny Root07438c82012-11-02 15:41:02 -0700327static uid_t get_keystore_euid(uid_t uid) {
328 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
329 struct user_euid user = user_euids[i];
330 if (user.uid == uid) {
331 return user.euid;
332 }
333 }
334
335 return uid;
336}
337
Kenny Root49468902013-03-19 13:41:33 -0700338/**
339 * Returns true if the callingUid is allowed to interact in the targetUid's
340 * namespace.
341 */
342static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700343 if (callingUid == targetUid) {
344 return true;
345 }
Kenny Root49468902013-03-19 13:41:33 -0700346 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
347 struct user_euid user = user_euids[i];
348 if (user.euid == callingUid && user.uid == targetUid) {
349 return true;
350 }
351 }
352
353 return false;
354}
355
Kenny Roota91203b2012-02-15 15:00:46 -0800356/* Here is the encoding of keys. This is necessary in order to allow arbitrary
357 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
358 * into two bytes. The first byte is one of [+-.] which represents the first
359 * two bits of the character. The second byte encodes the rest of the bits into
360 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
361 * that Base64 cannot be used here due to the need of prefix match on keys. */
362
Kenny Root655b9582013-04-04 08:37:42 -0700363static size_t encode_key_length(const android::String8& keyName) {
364 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
365 size_t length = keyName.length();
366 for (int i = length; i > 0; --i, ++in) {
367 if (*in < '0' || *in > '~') {
368 ++length;
369 }
370 }
371 return length;
372}
373
Kenny Root07438c82012-11-02 15:41:02 -0700374static int encode_key(char* out, const android::String8& keyName) {
375 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
376 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800377 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700378 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800379 *out = '+' + (*in >> 6);
380 *++out = '0' + (*in & 0x3F);
381 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700382 } else {
383 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800384 }
385 }
386 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800387 return length;
388}
389
Kenny Root07438c82012-11-02 15:41:02 -0700390/*
391 * Converts from the "escaped" format on disk to actual name.
392 * This will be smaller than the input string.
393 *
394 * Characters that should combine with the next at the end will be truncated.
395 */
396static size_t decode_key_length(const char* in, size_t length) {
397 size_t outLength = 0;
398
399 for (const char* end = in + length; in < end; in++) {
400 /* This combines with the next character. */
401 if (*in < '0' || *in > '~') {
402 continue;
403 }
404
405 outLength++;
406 }
407 return outLength;
408}
409
410static void decode_key(char* out, const char* in, size_t length) {
411 for (const char* end = in + length; in < end; in++) {
412 if (*in < '0' || *in > '~') {
413 /* Truncate combining characters at the end. */
414 if (in + 1 >= end) {
415 break;
416 }
417
418 *out = (*in++ - '+') << 6;
419 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800420 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700421 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800422 }
423 }
424 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800425}
426
427static size_t readFully(int fd, uint8_t* data, size_t size) {
428 size_t remaining = size;
429 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800430 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800431 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800432 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800433 }
434 data += n;
435 remaining -= n;
436 }
437 return size;
438}
439
440static size_t writeFully(int fd, uint8_t* data, size_t size) {
441 size_t remaining = size;
442 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800443 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
444 if (n < 0) {
445 ALOGW("write failed: %s", strerror(errno));
446 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800447 }
448 data += n;
449 remaining -= n;
450 }
451 return size;
452}
453
454class Entropy {
455public:
456 Entropy() : mRandom(-1) {}
457 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800458 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800459 close(mRandom);
460 }
461 }
462
463 bool open() {
464 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800465 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
466 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800467 ALOGE("open: %s: %s", randomDevice, strerror(errno));
468 return false;
469 }
470 return true;
471 }
472
Kenny Root51878182012-03-13 12:53:19 -0700473 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800474 return (readFully(mRandom, data, size) == size);
475 }
476
477private:
478 int mRandom;
479};
480
481/* Here is the file format. There are two parts in blob.value, the secret and
482 * the description. The secret is stored in ciphertext, and its original size
483 * can be found in blob.length. The description is stored after the secret in
484 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700485 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700486 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800487 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
488 * and decryptBlob(). Thus they should not be accessed from outside. */
489
Kenny Root822c3a92012-03-23 16:34:39 -0700490/* ** Note to future implementors of encryption: **
491 * Currently this is the construction:
492 * metadata || Enc(MD5(data) || data)
493 *
494 * This should be the construction used for encrypting if re-implementing:
495 *
496 * Derive independent keys for encryption and MAC:
497 * Kenc = AES_encrypt(masterKey, "Encrypt")
498 * Kmac = AES_encrypt(masterKey, "MAC")
499 *
500 * Store this:
501 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
502 * HMAC(Kmac, metadata || Enc(data))
503 */
Kenny Roota91203b2012-02-15 15:00:46 -0800504struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700505 uint8_t version;
506 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700507 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800508 uint8_t info;
509 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700510 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800511 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700512 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800513 int32_t length; // in network byte order when encrypted
514 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
515};
516
Kenny Root822c3a92012-03-23 16:34:39 -0700517typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700518 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700519 TYPE_GENERIC = 1,
520 TYPE_MASTER_KEY = 2,
521 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800522 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700523} BlobType;
524
Kenny Rootf9119d62013-04-03 09:22:15 -0700525static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700526
Kenny Roota91203b2012-02-15 15:00:46 -0800527class Blob {
528public:
Chad Brubaker803f37f2015-07-29 13:53:36 -0700529 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700530 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800531 memset(&mBlob, 0, sizeof(mBlob));
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700532 if (valueLength > VALUE_SIZE) {
533 valueLength = VALUE_SIZE;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700534 ALOGW("Provided blob length too large");
535 }
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700536 if (infoLength + valueLength > VALUE_SIZE) {
537 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700538 ALOGW("Provided info length too large");
539 }
Kenny Roota91203b2012-02-15 15:00:46 -0800540 mBlob.length = valueLength;
541 memcpy(mBlob.value, value, valueLength);
542
543 mBlob.info = infoLength;
544 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700545
Kenny Root07438c82012-11-02 15:41:02 -0700546 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700547 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700548
Kenny Rootee8068b2013-10-07 09:49:15 -0700549 if (type == TYPE_MASTER_KEY) {
550 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
551 } else {
552 mBlob.flags = KEYSTORE_FLAG_NONE;
553 }
Kenny Roota91203b2012-02-15 15:00:46 -0800554 }
555
556 Blob(blob b) {
557 mBlob = b;
558 }
559
Alex Klyubin1773b442015-02-20 12:33:33 -0800560 Blob() {
561 memset(&mBlob, 0, sizeof(mBlob));
562 }
Kenny Roota91203b2012-02-15 15:00:46 -0800563
Kenny Root51878182012-03-13 12:53:19 -0700564 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800565 return mBlob.value;
566 }
567
Kenny Root51878182012-03-13 12:53:19 -0700568 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800569 return mBlob.length;
570 }
571
Kenny Root51878182012-03-13 12:53:19 -0700572 const uint8_t* getInfo() const {
573 return mBlob.value + mBlob.length;
574 }
575
576 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800577 return mBlob.info;
578 }
579
Kenny Root822c3a92012-03-23 16:34:39 -0700580 uint8_t getVersion() const {
581 return mBlob.version;
582 }
583
Kenny Rootf9119d62013-04-03 09:22:15 -0700584 bool isEncrypted() const {
585 if (mBlob.version < 2) {
586 return true;
587 }
588
589 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
590 }
591
592 void setEncrypted(bool encrypted) {
593 if (encrypted) {
594 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
595 } else {
596 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
597 }
598 }
599
Kenny Root17208e02013-09-04 13:56:03 -0700600 bool isFallback() const {
601 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
602 }
603
604 void setFallback(bool fallback) {
605 if (fallback) {
606 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
607 } else {
608 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
609 }
610 }
611
Kenny Root822c3a92012-03-23 16:34:39 -0700612 void setVersion(uint8_t version) {
613 mBlob.version = version;
614 }
615
616 BlobType getType() const {
617 return BlobType(mBlob.type);
618 }
619
620 void setType(BlobType type) {
621 mBlob.type = uint8_t(type);
622 }
623
Kenny Rootf9119d62013-04-03 09:22:15 -0700624 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
625 ALOGV("writing blob %s", filename);
626 if (isEncrypted()) {
627 if (state != STATE_NO_ERROR) {
628 ALOGD("couldn't insert encrypted blob while not unlocked");
629 return LOCKED;
630 }
631
632 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
633 ALOGW("Could not read random data for: %s", filename);
634 return SYSTEM_ERROR;
635 }
Kenny Roota91203b2012-02-15 15:00:46 -0800636 }
637
638 // data includes the value and the value's length
639 size_t dataLength = mBlob.length + sizeof(mBlob.length);
640 // pad data to the AES_BLOCK_SIZE
641 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
642 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
643 // encrypted data includes the digest value
644 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
645 // move info after space for padding
646 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
647 // zero padding area
648 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
649
650 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800651
Kenny Rootf9119d62013-04-03 09:22:15 -0700652 if (isEncrypted()) {
653 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800654
Kenny Rootf9119d62013-04-03 09:22:15 -0700655 uint8_t vector[AES_BLOCK_SIZE];
656 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
657 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
658 aes_key, vector, AES_ENCRYPT);
659 }
660
Kenny Roota91203b2012-02-15 15:00:46 -0800661 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
662 size_t fileLength = encryptedLength + headerLength + mBlob.info;
663
664 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800665 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
666 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
667 if (out < 0) {
668 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800669 return SYSTEM_ERROR;
670 }
671 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
672 if (close(out) != 0) {
673 return SYSTEM_ERROR;
674 }
675 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800676 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800677 unlink(tmpFileName);
678 return SYSTEM_ERROR;
679 }
Kenny Root150ca932012-11-14 14:29:02 -0800680 if (rename(tmpFileName, filename) == -1) {
681 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
682 return SYSTEM_ERROR;
683 }
684 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800685 }
686
Kenny Rootf9119d62013-04-03 09:22:15 -0700687 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
688 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800689 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
690 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800691 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
692 }
693 // fileLength may be less than sizeof(mBlob) since the in
694 // memory version has extra padding to tolerate rounding up to
695 // the AES_BLOCK_SIZE
696 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
697 if (close(in) != 0) {
698 return SYSTEM_ERROR;
699 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700700
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700701 if (fileLength == 0) {
702 return VALUE_CORRUPTED;
703 }
704
Kenny Rootf9119d62013-04-03 09:22:15 -0700705 if (isEncrypted() && (state != STATE_NO_ERROR)) {
706 return LOCKED;
707 }
708
Kenny Roota91203b2012-02-15 15:00:46 -0800709 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
710 if (fileLength < headerLength) {
711 return VALUE_CORRUPTED;
712 }
713
714 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700715 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800716 return VALUE_CORRUPTED;
717 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700718
719 ssize_t digestedLength;
720 if (isEncrypted()) {
721 if (encryptedLength % AES_BLOCK_SIZE != 0) {
722 return VALUE_CORRUPTED;
723 }
724
725 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
726 mBlob.vector, AES_DECRYPT);
727 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
728 uint8_t computedDigest[MD5_DIGEST_LENGTH];
729 MD5(mBlob.digested, digestedLength, computedDigest);
730 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
731 return VALUE_CORRUPTED;
732 }
733 } else {
734 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800735 }
736
737 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
738 mBlob.length = ntohl(mBlob.length);
739 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
740 return VALUE_CORRUPTED;
741 }
742 if (mBlob.info != 0) {
743 // move info from after padding to after data
744 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
745 }
Kenny Root07438c82012-11-02 15:41:02 -0700746 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800747 }
748
749private:
750 struct blob mBlob;
751};
752
Kenny Root655b9582013-04-04 08:37:42 -0700753class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800754public:
Kenny Root655b9582013-04-04 08:37:42 -0700755 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
756 asprintf(&mUserDir, "user_%u", mUserId);
757 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
758 }
759
760 ~UserState() {
761 free(mUserDir);
762 free(mMasterKeyFile);
763 }
764
765 bool initialize() {
766 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
767 ALOGE("Could not create directory '%s'", mUserDir);
768 return false;
769 }
770
771 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800772 setState(STATE_LOCKED);
773 } else {
774 setState(STATE_UNINITIALIZED);
775 }
Kenny Root70e3a862012-02-15 17:20:23 -0800776
Kenny Root655b9582013-04-04 08:37:42 -0700777 return true;
778 }
779
780 uid_t getUserId() const {
781 return mUserId;
782 }
783
784 const char* getUserDirName() const {
785 return mUserDir;
786 }
787
788 const char* getMasterKeyFileName() const {
789 return mMasterKeyFile;
790 }
791
792 void setState(State state) {
793 mState = state;
794 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
795 mRetry = MAX_RETRY;
796 }
Kenny Roota91203b2012-02-15 15:00:46 -0800797 }
798
Kenny Root51878182012-03-13 12:53:19 -0700799 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800800 return mState;
801 }
802
Kenny Root51878182012-03-13 12:53:19 -0700803 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800804 return mRetry;
805 }
806
Kenny Root655b9582013-04-04 08:37:42 -0700807 void zeroizeMasterKeysInMemory() {
808 memset(mMasterKey, 0, sizeof(mMasterKey));
809 memset(mSalt, 0, sizeof(mSalt));
810 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
811 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800812 }
813
Chad Brubaker96d6d782015-05-07 10:19:40 -0700814 bool deleteMasterKey() {
815 setState(STATE_UNINITIALIZED);
816 zeroizeMasterKeysInMemory();
817 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
818 }
819
Kenny Root655b9582013-04-04 08:37:42 -0700820 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
821 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800822 return SYSTEM_ERROR;
823 }
Kenny Root655b9582013-04-04 08:37:42 -0700824 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800825 if (response != NO_ERROR) {
826 return response;
827 }
828 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700829 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800830 }
831
Robin Lee4e865752014-08-19 17:37:55 +0100832 ResponseCode copyMasterKey(UserState* src) {
833 if (mState != STATE_UNINITIALIZED) {
834 return ::SYSTEM_ERROR;
835 }
836 if (src->getState() != STATE_NO_ERROR) {
837 return ::SYSTEM_ERROR;
838 }
839 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
840 setupMasterKeys();
841 return ::NO_ERROR;
842 }
843
Kenny Root655b9582013-04-04 08:37:42 -0700844 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800845 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
846 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
847 AES_KEY passwordAesKey;
848 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700849 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700850 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800851 }
852
Kenny Root655b9582013-04-04 08:37:42 -0700853 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
854 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800855 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800856 return SYSTEM_ERROR;
857 }
858
859 // we read the raw blob to just to get the salt to generate
860 // the AES key, then we create the Blob to use with decryptBlob
861 blob rawBlob;
862 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
863 if (close(in) != 0) {
864 return SYSTEM_ERROR;
865 }
866 // find salt at EOF if present, otherwise we have an old file
867 uint8_t* salt;
868 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
869 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
870 } else {
871 salt = NULL;
872 }
873 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
874 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
875 AES_KEY passwordAesKey;
876 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
877 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700878 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
879 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800880 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700881 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800882 }
883 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
884 // if salt was missing, generate one and write a new master key file with the salt.
885 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700886 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800887 return SYSTEM_ERROR;
888 }
Kenny Root655b9582013-04-04 08:37:42 -0700889 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800890 }
891 if (response == NO_ERROR) {
892 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
893 setupMasterKeys();
894 }
895 return response;
896 }
897 if (mRetry <= 0) {
898 reset();
899 return UNINITIALIZED;
900 }
901 --mRetry;
902 switch (mRetry) {
903 case 0: return WRONG_PASSWORD_0;
904 case 1: return WRONG_PASSWORD_1;
905 case 2: return WRONG_PASSWORD_2;
906 case 3: return WRONG_PASSWORD_3;
907 default: return WRONG_PASSWORD_3;
908 }
909 }
910
Kenny Root655b9582013-04-04 08:37:42 -0700911 AES_KEY* getEncryptionKey() {
912 return &mMasterKeyEncryption;
913 }
914
915 AES_KEY* getDecryptionKey() {
916 return &mMasterKeyDecryption;
917 }
918
Kenny Roota91203b2012-02-15 15:00:46 -0800919 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700920 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800921 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700922 // If the directory doesn't exist then nothing to do.
923 if (errno == ENOENT) {
924 return true;
925 }
Kenny Root655b9582013-04-04 08:37:42 -0700926 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800927 return false;
928 }
Kenny Root655b9582013-04-04 08:37:42 -0700929
930 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800931 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700932 // skip . and ..
933 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700934 continue;
935 }
936
937 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800938 }
939 closedir(dir);
940 return true;
941 }
942
Kenny Root655b9582013-04-04 08:37:42 -0700943private:
944 static const int MASTER_KEY_SIZE_BYTES = 16;
945 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
946
947 static const int MAX_RETRY = 4;
948 static const size_t SALT_SIZE = 16;
949
950 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
951 uint8_t* salt) {
952 size_t saltSize;
953 if (salt != NULL) {
954 saltSize = SALT_SIZE;
955 } else {
956 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
957 salt = (uint8_t*) "keystore";
958 // sizeof = 9, not strlen = 8
959 saltSize = sizeof("keystore");
960 }
961
962 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
963 saltSize, 8192, keySize, key);
964 }
965
966 bool generateSalt(Entropy* entropy) {
967 return entropy->generate_random_data(mSalt, sizeof(mSalt));
968 }
969
970 bool generateMasterKey(Entropy* entropy) {
971 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
972 return false;
973 }
974 if (!generateSalt(entropy)) {
975 return false;
976 }
977 return true;
978 }
979
980 void setupMasterKeys() {
981 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
982 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
983 setState(STATE_NO_ERROR);
984 }
985
986 uid_t mUserId;
987
988 char* mUserDir;
989 char* mMasterKeyFile;
990
991 State mState;
992 int8_t mRetry;
993
994 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
995 uint8_t mSalt[SALT_SIZE];
996
997 AES_KEY mMasterKeyEncryption;
998 AES_KEY mMasterKeyDecryption;
999};
1000
1001typedef struct {
1002 uint32_t uid;
1003 const uint8_t* filename;
1004} grant_t;
1005
1006class KeyStore {
1007public:
Chad Brubaker67d2a502015-03-11 17:21:18 +00001008 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001009 : mEntropy(entropy)
1010 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001011 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001012 {
1013 memset(&mMetaData, '\0', sizeof(mMetaData));
1014 }
1015
1016 ~KeyStore() {
1017 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1018 it != mGrants.end(); it++) {
1019 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001020 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001021 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001022
1023 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1024 it != mMasterKeys.end(); it++) {
1025 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001026 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001027 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001028 }
1029
Chad Brubaker67d2a502015-03-11 17:21:18 +00001030 /**
1031 * Depending on the hardware keymaster version is this may return a
1032 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1033 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1034 * be guarded by a check on the device's version.
1035 */
1036 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001037 return mDevice;
1038 }
1039
Chad Brubaker67d2a502015-03-11 17:21:18 +00001040 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001041 return mFallbackDevice;
1042 }
1043
Chad Brubaker67d2a502015-03-11 17:21:18 +00001044 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001045 return blob.isFallback() ? mFallbackDevice: mDevice;
1046 }
1047
Kenny Root655b9582013-04-04 08:37:42 -07001048 ResponseCode initialize() {
1049 readMetaData();
1050 if (upgradeKeystore()) {
1051 writeMetaData();
1052 }
1053
1054 return ::NO_ERROR;
1055 }
1056
Chad Brubaker72593ee2015-05-12 10:42:00 -07001057 State getState(uid_t userId) {
1058 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001059 }
1060
Chad Brubaker72593ee2015-05-12 10:42:00 -07001061 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1062 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001063 return userState->initialize(pw, mEntropy);
1064 }
1065
Chad Brubaker72593ee2015-05-12 10:42:00 -07001066 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1067 UserState *userState = getUserState(dstUser);
1068 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001069 return userState->copyMasterKey(initState);
1070 }
1071
Chad Brubaker72593ee2015-05-12 10:42:00 -07001072 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1073 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001074 return userState->writeMasterKey(pw, mEntropy);
1075 }
1076
Chad Brubaker72593ee2015-05-12 10:42:00 -07001077 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1078 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001079 return userState->readMasterKey(pw, mEntropy);
1080 }
1081
1082 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001083 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001084 encode_key(encoded, keyName);
1085 return android::String8(encoded);
1086 }
1087
1088 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001089 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001090 encode_key(encoded, keyName);
1091 return android::String8::format("%u_%s", uid, encoded);
1092 }
1093
1094 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001095 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001096 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001097 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001098 encoded);
1099 }
1100
Chad Brubaker96d6d782015-05-07 10:19:40 -07001101 /*
1102 * Delete entries owned by userId. If keepUnencryptedEntries is true
1103 * then only encrypted entries will be removed, otherwise all entries will
1104 * be removed.
1105 */
1106 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001107 android::String8 prefix("");
1108 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001109 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001110 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001111 return;
1112 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001113 for (uint32_t i = 0; i < aliases.size(); i++) {
1114 android::String8 filename(aliases[i]);
1115 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001116 getKeyName(filename).string());
1117 bool shouldDelete = true;
1118 if (keepUnenryptedEntries) {
1119 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001120 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001121
Chad Brubaker96d6d782015-05-07 10:19:40 -07001122 /* get can fail if the blob is encrypted and the state is
1123 * not unlocked, only skip deleting blobs that were loaded and
1124 * who are not encrypted. If there are blobs we fail to read for
1125 * other reasons err on the safe side and delete them since we
1126 * can't tell if they're encrypted.
1127 */
1128 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1129 }
1130 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001131 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001132 }
1133 }
1134 if (!userState->deleteMasterKey()) {
1135 ALOGE("Failed to delete user %d's master key", userId);
1136 }
1137 if (!keepUnenryptedEntries) {
1138 if(!userState->reset()) {
1139 ALOGE("Failed to remove user %d's directory", userId);
1140 }
1141 }
Kenny Root655b9582013-04-04 08:37:42 -07001142 }
1143
Chad Brubaker72593ee2015-05-12 10:42:00 -07001144 bool isEmpty(uid_t userId) const {
1145 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001146 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001147 return true;
1148 }
1149
1150 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001151 if (!dir) {
1152 return true;
1153 }
Kenny Root31e27462014-09-10 11:28:03 -07001154
Kenny Roota91203b2012-02-15 15:00:46 -08001155 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001156 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001157 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001158 // We only care about files.
1159 if (file->d_type != DT_REG) {
1160 continue;
1161 }
1162
1163 // Skip anything that starts with a "."
1164 if (file->d_name[0] == '.') {
1165 continue;
1166 }
1167
Kenny Root31e27462014-09-10 11:28:03 -07001168 result = false;
1169 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001170 }
1171 closedir(dir);
1172 return result;
1173 }
1174
Chad Brubaker72593ee2015-05-12 10:42:00 -07001175 void lock(uid_t userId) {
1176 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001177 userState->zeroizeMasterKeysInMemory();
1178 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001179 }
1180
Chad Brubaker72593ee2015-05-12 10:42:00 -07001181 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1182 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001183 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1184 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001185 if (rc != NO_ERROR) {
1186 return rc;
1187 }
1188
1189 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001190 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001191 /* If we upgrade the key, we need to write it to disk again. Then
1192 * it must be read it again since the blob is encrypted each time
1193 * it's written.
1194 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001195 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1196 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001197 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1198 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001199 return rc;
1200 }
1201 }
Kenny Root822c3a92012-03-23 16:34:39 -07001202 }
1203
Kenny Root17208e02013-09-04 13:56:03 -07001204 /*
1205 * This will upgrade software-backed keys to hardware-backed keys when
1206 * the HAL for the device supports the newer key types.
1207 */
1208 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1209 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1210 && keyBlob->isFallback()) {
1211 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001212 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001213
1214 // The HAL allowed the import, reget the key to have the "fresh"
1215 // version.
1216 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001217 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001218 }
1219 }
1220
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001221 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1222 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001223 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001224 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001225 }
1226
Kenny Rootd53bc922013-03-21 14:10:15 -07001227 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001228 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1229 return KEY_NOT_FOUND;
1230 }
1231
1232 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001233 }
1234
Chad Brubaker72593ee2015-05-12 10:42:00 -07001235 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1236 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001237 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1238 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001239 }
1240
Chad Brubaker72593ee2015-05-12 10:42:00 -07001241 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001242 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001243 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001244 if (rc == ::VALUE_CORRUPTED) {
1245 // The file is corrupt, the best we can do is rm it.
1246 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1247 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001248 if (rc != ::NO_ERROR) {
1249 return rc;
1250 }
1251
1252 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1253 // A device doesn't have to implement delete_keypair.
1254 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1255 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1256 rc = ::SYSTEM_ERROR;
1257 }
1258 }
1259 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001260 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1261 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1262 if (dev->delete_key) {
1263 keymaster_key_blob_t blob;
1264 blob.key_material = keyBlob.getValue();
1265 blob.key_material_size = keyBlob.getLength();
1266 dev->delete_key(dev, &blob);
1267 }
1268 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001269 if (rc != ::NO_ERROR) {
1270 return rc;
1271 }
1272
1273 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1274 }
1275
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001276 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001277 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001278
Chad Brubaker72593ee2015-05-12 10:42:00 -07001279 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001280 size_t n = prefix.length();
1281
1282 DIR* dir = opendir(userState->getUserDirName());
1283 if (!dir) {
1284 ALOGW("can't open directory for user: %s", strerror(errno));
1285 return ::SYSTEM_ERROR;
1286 }
1287
1288 struct dirent* file;
1289 while ((file = readdir(dir)) != NULL) {
1290 // We only care about files.
1291 if (file->d_type != DT_REG) {
1292 continue;
1293 }
1294
1295 // Skip anything that starts with a "."
1296 if (file->d_name[0] == '.') {
1297 continue;
1298 }
1299
1300 if (!strncmp(prefix.string(), file->d_name, n)) {
1301 const char* p = &file->d_name[n];
1302 size_t plen = strlen(p);
1303
1304 size_t extra = decode_key_length(p, plen);
1305 char *match = (char*) malloc(extra + 1);
1306 if (match != NULL) {
1307 decode_key(match, p, plen);
1308 matches->push(android::String16(match, extra));
1309 free(match);
1310 } else {
1311 ALOGW("could not allocate match of size %zd", extra);
1312 }
1313 }
1314 }
1315 closedir(dir);
1316 return ::NO_ERROR;
1317 }
1318
Kenny Root07438c82012-11-02 15:41:02 -07001319 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001320 const grant_t* existing = getGrant(filename, granteeUid);
1321 if (existing == NULL) {
1322 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001323 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001324 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001325 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001326 }
1327 }
1328
Kenny Root07438c82012-11-02 15:41:02 -07001329 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001330 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1331 it != mGrants.end(); it++) {
1332 grant_t* grant = *it;
1333 if (grant->uid == granteeUid
1334 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1335 mGrants.erase(it);
1336 return true;
1337 }
Kenny Root70e3a862012-02-15 17:20:23 -08001338 }
Kenny Root70e3a862012-02-15 17:20:23 -08001339 return false;
1340 }
1341
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001342 bool hasGrant(const char* filename, const uid_t uid) const {
1343 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001344 }
1345
Chad Brubaker72593ee2015-05-12 10:42:00 -07001346 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001347 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001348 uint8_t* data;
1349 size_t dataLength;
1350 int rc;
1351
1352 if (mDevice->import_keypair == NULL) {
1353 ALOGE("Keymaster doesn't support import!");
1354 return SYSTEM_ERROR;
1355 }
1356
Kenny Root17208e02013-09-04 13:56:03 -07001357 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001358 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001359 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001360 /*
1361 * Maybe the device doesn't support this type of key. Try to use the
1362 * software fallback keymaster implementation. This is a little bit
1363 * lazier than checking the PKCS#8 key type, but the software
1364 * implementation will do that anyway.
1365 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001366 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001367 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001368
1369 if (rc) {
1370 ALOGE("Error while importing keypair: %d", rc);
1371 return SYSTEM_ERROR;
1372 }
Kenny Root822c3a92012-03-23 16:34:39 -07001373 }
1374
1375 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1376 free(data);
1377
Kenny Rootf9119d62013-04-03 09:22:15 -07001378 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001379 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001380
Chad Brubaker72593ee2015-05-12 10:42:00 -07001381 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001382 }
1383
Kenny Root1b0e3932013-09-05 13:06:32 -07001384 bool isHardwareBacked(const android::String16& keyType) const {
1385 if (mDevice == NULL) {
1386 ALOGW("can't get keymaster device");
1387 return false;
1388 }
1389
1390 if (sRSAKeyType == keyType) {
1391 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1392 } else {
1393 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1394 && (mDevice->common.module->module_api_version
1395 >= KEYMASTER_MODULE_API_VERSION_0_2);
1396 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001397 }
1398
Kenny Root655b9582013-04-04 08:37:42 -07001399 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1400 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001401 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001402 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001403
Chad Brubaker72593ee2015-05-12 10:42:00 -07001404 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001405 if (responseCode == NO_ERROR) {
1406 return responseCode;
1407 }
1408
1409 // If this is one of the legacy UID->UID mappings, use it.
1410 uid_t euid = get_keystore_euid(uid);
1411 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001412 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001413 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001414 if (responseCode == NO_ERROR) {
1415 return responseCode;
1416 }
1417 }
1418
1419 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001420 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001421 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001422 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001423 if (end[0] != '_' || end[1] == 0) {
1424 return KEY_NOT_FOUND;
1425 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001426 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001427 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001428 if (!hasGrant(filepath8.string(), uid)) {
1429 return responseCode;
1430 }
1431
1432 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001433 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001434 }
1435
1436 /**
1437 * Returns any existing UserState or creates it if it doesn't exist.
1438 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001439 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001440 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1441 it != mMasterKeys.end(); it++) {
1442 UserState* state = *it;
1443 if (state->getUserId() == userId) {
1444 return state;
1445 }
1446 }
1447
1448 UserState* userState = new UserState(userId);
1449 if (!userState->initialize()) {
1450 /* There's not much we can do if initialization fails. Trying to
1451 * unlock the keystore for that user will fail as well, so any
1452 * subsequent request for this user will just return SYSTEM_ERROR.
1453 */
1454 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1455 }
1456 mMasterKeys.add(userState);
1457 return userState;
1458 }
1459
1460 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001461 * Returns any existing UserState or creates it if it doesn't exist.
1462 */
1463 UserState* getUserStateByUid(uid_t uid) {
1464 uid_t userId = get_user_id(uid);
1465 return getUserState(userId);
1466 }
1467
1468 /**
Kenny Root655b9582013-04-04 08:37:42 -07001469 * Returns NULL if the UserState doesn't already exist.
1470 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001471 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001472 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1473 it != mMasterKeys.end(); it++) {
1474 UserState* state = *it;
1475 if (state->getUserId() == userId) {
1476 return state;
1477 }
1478 }
1479
1480 return NULL;
1481 }
1482
Chad Brubaker72593ee2015-05-12 10:42:00 -07001483 /**
1484 * Returns NULL if the UserState doesn't already exist.
1485 */
1486 const UserState* getUserStateByUid(uid_t uid) const {
1487 uid_t userId = get_user_id(uid);
1488 return getUserState(userId);
1489 }
1490
Kenny Roota91203b2012-02-15 15:00:46 -08001491private:
Kenny Root655b9582013-04-04 08:37:42 -07001492 static const char* sOldMasterKey;
1493 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001494 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001495 Entropy* mEntropy;
1496
Chad Brubaker67d2a502015-03-11 17:21:18 +00001497 keymaster1_device_t* mDevice;
1498 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001499
Kenny Root655b9582013-04-04 08:37:42 -07001500 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001501
Kenny Root655b9582013-04-04 08:37:42 -07001502 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001503
Kenny Root655b9582013-04-04 08:37:42 -07001504 typedef struct {
1505 uint32_t version;
1506 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001507
Kenny Root655b9582013-04-04 08:37:42 -07001508 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001509
Kenny Root655b9582013-04-04 08:37:42 -07001510 const grant_t* getGrant(const char* filename, uid_t uid) const {
1511 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1512 it != mGrants.end(); it++) {
1513 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001514 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001515 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001516 return grant;
1517 }
1518 }
Kenny Root70e3a862012-02-15 17:20:23 -08001519 return NULL;
1520 }
1521
Kenny Root822c3a92012-03-23 16:34:39 -07001522 /**
1523 * Upgrade code. This will upgrade the key from the current version
1524 * to whatever is newest.
1525 */
Kenny Root655b9582013-04-04 08:37:42 -07001526 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1527 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001528 bool updated = false;
1529 uint8_t version = oldVersion;
1530
1531 /* From V0 -> V1: All old types were unknown */
1532 if (version == 0) {
1533 ALOGV("upgrading to version 1 and setting type %d", type);
1534
1535 blob->setType(type);
1536 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001537 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001538 }
1539 version = 1;
1540 updated = true;
1541 }
1542
Kenny Rootf9119d62013-04-03 09:22:15 -07001543 /* From V1 -> V2: All old keys were encrypted */
1544 if (version == 1) {
1545 ALOGV("upgrading to version 2");
1546
1547 blob->setEncrypted(true);
1548 version = 2;
1549 updated = true;
1550 }
1551
Kenny Root822c3a92012-03-23 16:34:39 -07001552 /*
1553 * If we've updated, set the key blob to the right version
1554 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001555 */
Kenny Root822c3a92012-03-23 16:34:39 -07001556 if (updated) {
1557 ALOGV("updated and writing file %s", filename);
1558 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001559 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001560
1561 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001562 }
1563
1564 /**
1565 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1566 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1567 * Then it overwrites the original blob with the new blob
1568 * format that is returned from the keymaster.
1569 */
Kenny Root655b9582013-04-04 08:37:42 -07001570 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001571 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1572 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1573 if (b.get() == NULL) {
1574 ALOGE("Problem instantiating BIO");
1575 return SYSTEM_ERROR;
1576 }
1577
1578 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1579 if (pkey.get() == NULL) {
1580 ALOGE("Couldn't read old PEM file");
1581 return SYSTEM_ERROR;
1582 }
1583
1584 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1585 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1586 if (len < 0) {
1587 ALOGE("Couldn't measure PKCS#8 length");
1588 return SYSTEM_ERROR;
1589 }
1590
Kenny Root70c98892013-02-07 09:10:36 -08001591 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1592 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001593 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1594 ALOGE("Couldn't convert to PKCS#8");
1595 return SYSTEM_ERROR;
1596 }
1597
Chad Brubaker72593ee2015-05-12 10:42:00 -07001598 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001599 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001600 if (rc != NO_ERROR) {
1601 return rc;
1602 }
1603
Kenny Root655b9582013-04-04 08:37:42 -07001604 return get(filename, blob, TYPE_KEY_PAIR, uid);
1605 }
1606
1607 void readMetaData() {
1608 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1609 if (in < 0) {
1610 return;
1611 }
1612 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1613 if (fileLength != sizeof(mMetaData)) {
1614 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1615 sizeof(mMetaData));
1616 }
1617 close(in);
1618 }
1619
1620 void writeMetaData() {
1621 const char* tmpFileName = ".metadata.tmp";
1622 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1623 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1624 if (out < 0) {
1625 ALOGE("couldn't write metadata file: %s", strerror(errno));
1626 return;
1627 }
1628 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1629 if (fileLength != sizeof(mMetaData)) {
1630 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1631 sizeof(mMetaData));
1632 }
1633 close(out);
1634 rename(tmpFileName, sMetaDataFile);
1635 }
1636
1637 bool upgradeKeystore() {
1638 bool upgraded = false;
1639
1640 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001641 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001642
1643 // Initialize first so the directory is made.
1644 userState->initialize();
1645
1646 // Migrate the old .masterkey file to user 0.
1647 if (access(sOldMasterKey, R_OK) == 0) {
1648 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1649 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1650 return false;
1651 }
1652 }
1653
1654 // Initialize again in case we had a key.
1655 userState->initialize();
1656
1657 // Try to migrate existing keys.
1658 DIR* dir = opendir(".");
1659 if (!dir) {
1660 // Give up now; maybe we can upgrade later.
1661 ALOGE("couldn't open keystore's directory; something is wrong");
1662 return false;
1663 }
1664
1665 struct dirent* file;
1666 while ((file = readdir(dir)) != NULL) {
1667 // We only care about files.
1668 if (file->d_type != DT_REG) {
1669 continue;
1670 }
1671
1672 // Skip anything that starts with a "."
1673 if (file->d_name[0] == '.') {
1674 continue;
1675 }
1676
1677 // Find the current file's user.
1678 char* end;
1679 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1680 if (end[0] != '_' || end[1] == 0) {
1681 continue;
1682 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001683 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001684 if (otherUser->getUserId() != 0) {
1685 unlinkat(dirfd(dir), file->d_name, 0);
1686 }
1687
1688 // Rename the file into user directory.
1689 DIR* otherdir = opendir(otherUser->getUserDirName());
1690 if (otherdir == NULL) {
1691 ALOGW("couldn't open user directory for rename");
1692 continue;
1693 }
1694 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1695 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1696 }
1697 closedir(otherdir);
1698 }
1699 closedir(dir);
1700
1701 mMetaData.version = 1;
1702 upgraded = true;
1703 }
1704
1705 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001706 }
Kenny Roota91203b2012-02-15 15:00:46 -08001707};
1708
Kenny Root655b9582013-04-04 08:37:42 -07001709const char* KeyStore::sOldMasterKey = ".masterkey";
1710const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001711
Kenny Root1b0e3932013-09-05 13:06:32 -07001712const android::String16 KeyStore::sRSAKeyType("RSA");
1713
Kenny Root07438c82012-11-02 15:41:02 -07001714namespace android {
1715class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1716public:
1717 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001718 : mKeyStore(keyStore),
1719 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001720 {
Kenny Roota91203b2012-02-15 15:00:46 -08001721 }
Kenny Roota91203b2012-02-15 15:00:46 -08001722
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001723 void binderDied(const wp<IBinder>& who) {
1724 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1725 for (auto token: operations) {
1726 abort(token);
1727 }
Kenny Root822c3a92012-03-23 16:34:39 -07001728 }
Kenny Roota91203b2012-02-15 15:00:46 -08001729
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001730 int32_t getState(int32_t userId) {
1731 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001732 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001733 }
Kenny Roota91203b2012-02-15 15:00:46 -08001734
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001735 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001736 }
1737
Kenny Root07438c82012-11-02 15:41:02 -07001738 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001739 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001740 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001741 }
Kenny Root07438c82012-11-02 15:41:02 -07001742
Chad Brubaker9489b792015-04-14 11:01:45 -07001743 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001744 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001745 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001746
Kenny Root655b9582013-04-04 08:37:42 -07001747 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001748 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001749 if (responseCode != ::NO_ERROR) {
1750 *item = NULL;
1751 *itemLength = 0;
1752 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001753 }
Kenny Roota91203b2012-02-15 15:00:46 -08001754
Kenny Root07438c82012-11-02 15:41:02 -07001755 *item = (uint8_t*) malloc(keyBlob.getLength());
1756 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1757 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001758
Kenny Root07438c82012-11-02 15:41:02 -07001759 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001760 }
1761
Kenny Rootf9119d62013-04-03 09:22:15 -07001762 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1763 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001764 targetUid = getEffectiveUid(targetUid);
1765 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1766 flags & KEYSTORE_FLAG_ENCRYPTED);
1767 if (result != ::NO_ERROR) {
1768 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001769 }
1770
Kenny Root07438c82012-11-02 15:41:02 -07001771 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001772 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001773
1774 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001775 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1776
Chad Brubaker72593ee2015-05-12 10:42:00 -07001777 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001778 }
1779
Kenny Root49468902013-03-19 13:41:33 -07001780 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001781 targetUid = getEffectiveUid(targetUid);
1782 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001783 return ::PERMISSION_DENIED;
1784 }
Kenny Root07438c82012-11-02 15:41:02 -07001785 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001786 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001787 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001788 }
1789
Kenny Root49468902013-03-19 13:41:33 -07001790 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001791 targetUid = getEffectiveUid(targetUid);
1792 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001793 return ::PERMISSION_DENIED;
1794 }
1795
Kenny Root07438c82012-11-02 15:41:02 -07001796 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001797 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001798
Kenny Root655b9582013-04-04 08:37:42 -07001799 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001800 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1801 }
1802 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001803 }
1804
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001805 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001806 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001807 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001808 return ::PERMISSION_DENIED;
1809 }
Kenny Root07438c82012-11-02 15:41:02 -07001810 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001811 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001812
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001813 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001814 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001815 }
Kenny Root07438c82012-11-02 15:41:02 -07001816 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001817 }
1818
Kenny Root07438c82012-11-02 15:41:02 -07001819 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001820 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001821 return ::PERMISSION_DENIED;
1822 }
1823
Chad Brubaker9489b792015-04-14 11:01:45 -07001824 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001825 mKeyStore->resetUser(get_user_id(callingUid), false);
1826 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001827 }
1828
Chad Brubaker96d6d782015-05-07 10:19:40 -07001829 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001830 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001831 return ::PERMISSION_DENIED;
1832 }
Kenny Root70e3a862012-02-15 17:20:23 -08001833
Kenny Root07438c82012-11-02 15:41:02 -07001834 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001835 // Flush the auth token table to prevent stale tokens from sticking
1836 // around.
1837 mAuthTokenTable.Clear();
1838
1839 if (password.size() == 0) {
1840 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001841 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001842 return ::NO_ERROR;
1843 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001844 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001845 case ::STATE_UNINITIALIZED: {
1846 // generate master key, encrypt with password, write to file,
1847 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001848 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001849 }
1850 case ::STATE_NO_ERROR: {
1851 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001852 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001853 }
1854 case ::STATE_LOCKED: {
1855 ALOGE("Changing user %d's password while locked, clearing old encryption",
1856 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001857 mKeyStore->resetUser(userId, true);
1858 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001859 }
Kenny Root07438c82012-11-02 15:41:02 -07001860 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001861 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001862 }
Kenny Root70e3a862012-02-15 17:20:23 -08001863 }
1864
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001865 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1866 if (!checkBinderPermission(P_USER_CHANGED)) {
1867 return ::PERMISSION_DENIED;
1868 }
1869
1870 // Sanity check that the new user has an empty keystore.
1871 if (!mKeyStore->isEmpty(userId)) {
1872 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1873 }
1874 // Unconditionally clear the keystore, just to be safe.
1875 mKeyStore->resetUser(userId, false);
1876
1877 // If the user has a parent user then use the parent's
1878 // masterkey/password, otherwise there's nothing to do.
1879 if (parentId != -1) {
1880 return mKeyStore->copyMasterKey(parentId, userId);
1881 } else {
1882 return ::NO_ERROR;
1883 }
1884 }
1885
1886 int32_t onUserRemoved(int32_t userId) {
1887 if (!checkBinderPermission(P_USER_CHANGED)) {
1888 return ::PERMISSION_DENIED;
1889 }
1890
1891 mKeyStore->resetUser(userId, false);
1892 return ::NO_ERROR;
1893 }
1894
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001895 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001896 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001897 return ::PERMISSION_DENIED;
1898 }
Kenny Root70e3a862012-02-15 17:20:23 -08001899
Chad Brubaker72593ee2015-05-12 10:42:00 -07001900 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001901 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001902 ALOGD("calling lock in state: %d", state);
1903 return state;
1904 }
1905
Chad Brubaker72593ee2015-05-12 10:42:00 -07001906 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001907 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001908 }
1909
Chad Brubaker96d6d782015-05-07 10:19:40 -07001910 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001911 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001912 return ::PERMISSION_DENIED;
1913 }
1914
Chad Brubaker72593ee2015-05-12 10:42:00 -07001915 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001916 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001917 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001918 return state;
1919 }
1920
1921 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001922 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001923 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001924 }
1925
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001926 bool isEmpty(int32_t userId) {
1927 if (!checkBinderPermission(P_IS_EMPTY)) {
1928 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001929 }
Kenny Root70e3a862012-02-15 17:20:23 -08001930
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001931 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001932 }
1933
Kenny Root96427ba2013-08-16 14:02:41 -07001934 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1935 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001936 targetUid = getEffectiveUid(targetUid);
1937 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1938 flags & KEYSTORE_FLAG_ENCRYPTED);
1939 if (result != ::NO_ERROR) {
1940 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001941 }
Kenny Root07438c82012-11-02 15:41:02 -07001942
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001943 KeymasterArguments params;
Shawn Willden2de8b752015-07-23 05:54:31 -06001944 addLegacyKeyAuthorizations(params.params, keyType);
Kenny Root07438c82012-11-02 15:41:02 -07001945
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001946 switch (keyType) {
1947 case EVP_PKEY_EC: {
1948 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
1949 if (keySize == -1) {
1950 keySize = EC_DEFAULT_KEY_SIZE;
1951 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1952 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07001953 return ::SYSTEM_ERROR;
1954 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001955 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1956 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001957 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001958 case EVP_PKEY_RSA: {
1959 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1960 if (keySize == -1) {
1961 keySize = RSA_DEFAULT_KEY_SIZE;
1962 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1963 ALOGI("invalid key size %d", keySize);
1964 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07001965 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001966 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1967 unsigned long exponent = RSA_DEFAULT_EXPONENT;
1968 if (args->size() > 1) {
1969 ALOGI("invalid number of arguments: %zu", args->size());
1970 return ::SYSTEM_ERROR;
1971 } else if (args->size() == 1) {
1972 sp<KeystoreArg> expArg = args->itemAt(0);
1973 if (expArg != NULL) {
1974 Unique_BIGNUM pubExpBn(
1975 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
1976 expArg->size(), NULL));
1977 if (pubExpBn.get() == NULL) {
1978 ALOGI("Could not convert public exponent to BN");
1979 return ::SYSTEM_ERROR;
1980 }
1981 exponent = BN_get_word(pubExpBn.get());
1982 if (exponent == 0xFFFFFFFFL) {
1983 ALOGW("cannot represent public exponent as a long value");
1984 return ::SYSTEM_ERROR;
1985 }
1986 } else {
1987 ALOGW("public exponent not read");
1988 return ::SYSTEM_ERROR;
1989 }
1990 }
1991 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
1992 exponent));
1993 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001994 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001995 default: {
1996 ALOGW("Unsupported key type %d", keyType);
1997 return ::SYSTEM_ERROR;
1998 }
Kenny Root96427ba2013-08-16 14:02:41 -07001999 }
2000
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002001 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2002 /*outCharacteristics*/ NULL);
2003 if (rc != ::NO_ERROR) {
2004 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002005 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002006 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002007 }
2008
Kenny Rootf9119d62013-04-03 09:22:15 -07002009 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2010 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002011 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002012
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002013 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2014 if (!pkcs8.get()) {
2015 return ::SYSTEM_ERROR;
2016 }
2017 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2018 if (!pkey.get()) {
2019 return ::SYSTEM_ERROR;
2020 }
2021 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002022 KeymasterArguments params;
2023 addLegacyKeyAuthorizations(params.params, type);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002024 switch (type) {
2025 case EVP_PKEY_RSA:
2026 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2027 break;
2028 case EVP_PKEY_EC:
2029 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2030 KM_ALGORITHM_EC));
2031 break;
2032 default:
2033 ALOGW("Unsupported key type %d", type);
2034 return ::SYSTEM_ERROR;
2035 }
2036 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2037 /*outCharacteristics*/ NULL);
2038 if (rc != ::NO_ERROR) {
2039 ALOGW("importKey failed: %d", rc);
2040 }
2041 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002042 }
2043
Kenny Root07438c82012-11-02 15:41:02 -07002044 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002045 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002046 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002047 return ::PERMISSION_DENIED;
2048 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002049 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002050 }
2051
Kenny Root07438c82012-11-02 15:41:02 -07002052 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2053 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002054 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002055 return ::PERMISSION_DENIED;
2056 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002057 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2058 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002059 }
Kenny Root07438c82012-11-02 15:41:02 -07002060
2061 /*
2062 * TODO: The abstraction between things stored in hardware and regular blobs
2063 * of data stored on the filesystem should be moved down to keystore itself.
2064 * Unfortunately the Java code that calls this has naming conventions that it
2065 * knows about. Ideally keystore shouldn't be used to store random blobs of
2066 * data.
2067 *
2068 * Until that happens, it's necessary to have a separate "get_pubkey" and
2069 * "del_key" since the Java code doesn't really communicate what it's
2070 * intentions are.
2071 */
2072 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002073 ExportResult result;
2074 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2075 if (result.resultCode != ::NO_ERROR) {
2076 ALOGW("export failed: %d", result.resultCode);
2077 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002078 }
Kenny Root07438c82012-11-02 15:41:02 -07002079
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002080 *pubkey = result.exportData.release();
2081 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002082 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002083 }
Kenny Root07438c82012-11-02 15:41:02 -07002084
Kenny Root07438c82012-11-02 15:41:02 -07002085 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002086 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002087 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2088 if (result != ::NO_ERROR) {
2089 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002090 }
2091
2092 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002093 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002094
Kenny Root655b9582013-04-04 08:37:42 -07002095 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002096 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2097 }
2098
Kenny Root655b9582013-04-04 08:37:42 -07002099 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002100 return ::NO_ERROR;
2101 }
2102
2103 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002104 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002105 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2106 if (result != ::NO_ERROR) {
2107 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002108 }
2109
2110 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002111 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002112
Kenny Root655b9582013-04-04 08:37:42 -07002113 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002114 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2115 }
2116
Kenny Root655b9582013-04-04 08:37:42 -07002117 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002118 }
2119
2120 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002121 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002122 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002123 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002124 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002125 }
Kenny Root07438c82012-11-02 15:41:02 -07002126
2127 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002128 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002129
Kenny Root655b9582013-04-04 08:37:42 -07002130 if (access(filename.string(), R_OK) == -1) {
2131 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002132 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002133 }
2134
Kenny Root655b9582013-04-04 08:37:42 -07002135 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002136 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002137 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002138 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002139 }
2140
2141 struct stat s;
2142 int ret = fstat(fd, &s);
2143 close(fd);
2144 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002145 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002146 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002147 }
2148
Kenny Root36a9e232013-02-04 14:24:15 -08002149 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002150 }
2151
Kenny Rootd53bc922013-03-21 14:10:15 -07002152 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2153 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002154 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002155 pid_t spid = IPCThreadState::self()->getCallingPid();
2156 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002157 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002158 return -1L;
2159 }
2160
Chad Brubaker72593ee2015-05-12 10:42:00 -07002161 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002162 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002163 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002164 return state;
2165 }
2166
Kenny Rootd53bc922013-03-21 14:10:15 -07002167 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2168 srcUid = callingUid;
2169 } else if (!is_granted_to(callingUid, srcUid)) {
2170 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002171 return ::PERMISSION_DENIED;
2172 }
2173
Kenny Rootd53bc922013-03-21 14:10:15 -07002174 if (destUid == -1) {
2175 destUid = callingUid;
2176 }
2177
2178 if (srcUid != destUid) {
2179 if (static_cast<uid_t>(srcUid) != callingUid) {
2180 ALOGD("can only duplicate from caller to other or to same uid: "
2181 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2182 return ::PERMISSION_DENIED;
2183 }
2184
2185 if (!is_granted_to(callingUid, destUid)) {
2186 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2187 return ::PERMISSION_DENIED;
2188 }
2189 }
2190
2191 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002192 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002193
Kenny Rootd53bc922013-03-21 14:10:15 -07002194 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002195 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002196
Kenny Root655b9582013-04-04 08:37:42 -07002197 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2198 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002199 return ::SYSTEM_ERROR;
2200 }
2201
Kenny Rootd53bc922013-03-21 14:10:15 -07002202 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002203 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002204 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002205 if (responseCode != ::NO_ERROR) {
2206 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002207 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002208
Chad Brubaker72593ee2015-05-12 10:42:00 -07002209 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002210 }
2211
Kenny Root1b0e3932013-09-05 13:06:32 -07002212 int32_t is_hardware_backed(const String16& keyType) {
2213 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002214 }
2215
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002216 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002217 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002218 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002219 return ::PERMISSION_DENIED;
2220 }
2221
Robin Lee4b84fdc2014-09-24 11:56:57 +01002222 String8 prefix = String8::format("%u_", targetUid);
2223 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002224 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002225 return ::SYSTEM_ERROR;
2226 }
2227
Robin Lee4b84fdc2014-09-24 11:56:57 +01002228 for (uint32_t i = 0; i < aliases.size(); i++) {
2229 String8 name8(aliases[i]);
2230 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002231 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002232 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002233 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002234 }
2235
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002236 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2237 const keymaster1_device_t* device = mKeyStore->getDevice();
2238 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2239 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2240 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2241 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2242 device->add_rng_entropy != NULL) {
2243 devResult = device->add_rng_entropy(device, data, dataLength);
2244 }
2245 if (fallback->add_rng_entropy) {
2246 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2247 }
2248 if (devResult) {
2249 return devResult;
2250 }
2251 if (fallbackResult) {
2252 return fallbackResult;
2253 }
2254 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002255 }
2256
Chad Brubaker17d68b92015-02-05 22:04:16 -08002257 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002258 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2259 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002260 uid = getEffectiveUid(uid);
2261 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2262 flags & KEYSTORE_FLAG_ENCRYPTED);
2263 if (rc != ::NO_ERROR) {
2264 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002265 }
2266
Chad Brubaker9489b792015-04-14 11:01:45 -07002267 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002268 bool isFallback = false;
2269 keymaster_key_blob_t blob;
2270 keymaster_key_characteristics_t *out = NULL;
2271
2272 const keymaster1_device_t* device = mKeyStore->getDevice();
2273 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002274 std::vector<keymaster_key_param_t> opParams(params.params);
2275 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002276 if (device == NULL) {
2277 return ::SYSTEM_ERROR;
2278 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002279 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002280 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2281 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002282 if (!entropy) {
2283 rc = KM_ERROR_OK;
2284 } else if (device->add_rng_entropy) {
2285 rc = device->add_rng_entropy(device, entropy, entropyLength);
2286 } else {
2287 rc = KM_ERROR_UNIMPLEMENTED;
2288 }
2289 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002290 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002291 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002292 }
2293 // If the HW device didn't support generate_key or generate_key failed
2294 // fall back to the software implementation.
2295 if (rc && fallback->generate_key != NULL) {
2296 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002297 if (!entropy) {
2298 rc = KM_ERROR_OK;
2299 } else if (fallback->add_rng_entropy) {
2300 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2301 } else {
2302 rc = KM_ERROR_UNIMPLEMENTED;
2303 }
2304 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002305 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002306 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002307 }
2308
2309 if (out) {
2310 if (outCharacteristics) {
2311 outCharacteristics->characteristics = *out;
2312 } else {
2313 keymaster_free_characteristics(out);
2314 }
2315 free(out);
2316 }
2317
2318 if (rc) {
2319 return rc;
2320 }
2321
2322 String8 name8(name);
2323 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2324
2325 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2326 keyBlob.setFallback(isFallback);
2327 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2328
2329 free(const_cast<uint8_t*>(blob.key_material));
2330
Chad Brubaker72593ee2015-05-12 10:42:00 -07002331 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002332 }
2333
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002334 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002335 const keymaster_blob_t* clientId,
2336 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002337 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002338 if (!outCharacteristics) {
2339 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2340 }
2341
2342 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2343
2344 Blob keyBlob;
2345 String8 name8(name);
2346 int rc;
2347
2348 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2349 TYPE_KEYMASTER_10);
2350 if (responseCode != ::NO_ERROR) {
2351 return responseCode;
2352 }
2353 keymaster_key_blob_t key;
2354 key.key_material_size = keyBlob.getLength();
2355 key.key_material = keyBlob.getValue();
2356 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2357 keymaster_key_characteristics_t *out = NULL;
2358 if (!dev->get_key_characteristics) {
2359 ALOGW("device does not implement get_key_characteristics");
2360 return KM_ERROR_UNIMPLEMENTED;
2361 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002362 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002363 if (out) {
2364 outCharacteristics->characteristics = *out;
2365 free(out);
2366 }
2367 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002368 }
2369
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002370 int32_t importKey(const String16& name, const KeymasterArguments& params,
2371 keymaster_key_format_t format, const uint8_t *keyData,
2372 size_t keyLength, int uid, int flags,
2373 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002374 uid = getEffectiveUid(uid);
2375 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2376 flags & KEYSTORE_FLAG_ENCRYPTED);
2377 if (rc != ::NO_ERROR) {
2378 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002379 }
2380
Chad Brubaker9489b792015-04-14 11:01:45 -07002381 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002382 bool isFallback = false;
2383 keymaster_key_blob_t blob;
2384 keymaster_key_characteristics_t *out = NULL;
2385
2386 const keymaster1_device_t* device = mKeyStore->getDevice();
2387 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002388 std::vector<keymaster_key_param_t> opParams(params.params);
2389 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2390 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002391 if (device == NULL) {
2392 return ::SYSTEM_ERROR;
2393 }
2394 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2395 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002396 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002397 }
2398 if (rc && fallback->import_key != NULL) {
2399 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002400 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002401 }
2402 if (out) {
2403 if (outCharacteristics) {
2404 outCharacteristics->characteristics = *out;
2405 } else {
2406 keymaster_free_characteristics(out);
2407 }
2408 free(out);
2409 }
2410 if (rc) {
2411 return rc;
2412 }
2413
2414 String8 name8(name);
2415 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2416
2417 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2418 keyBlob.setFallback(isFallback);
2419 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2420
2421 free((void*) blob.key_material);
2422
Chad Brubaker72593ee2015-05-12 10:42:00 -07002423 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002424 }
2425
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002426 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002427 const keymaster_blob_t* clientId,
2428 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002429
2430 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2431
2432 Blob keyBlob;
2433 String8 name8(name);
2434 int rc;
2435
2436 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2437 TYPE_KEYMASTER_10);
2438 if (responseCode != ::NO_ERROR) {
2439 result->resultCode = responseCode;
2440 return;
2441 }
2442 keymaster_key_blob_t key;
2443 key.key_material_size = keyBlob.getLength();
2444 key.key_material = keyBlob.getValue();
2445 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2446 if (!dev->export_key) {
2447 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2448 return;
2449 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002450 keymaster_blob_t output = {NULL, 0};
2451 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2452 result->exportData.reset(const_cast<uint8_t*>(output.data));
2453 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002454 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002455 }
2456
Chad Brubakerad6514a2015-04-09 14:00:26 -07002457
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002458 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002459 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002460 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002461 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2462 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2463 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2464 result->resultCode = ::PERMISSION_DENIED;
2465 return;
2466 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002467 if (!checkAllowedOperationParams(params.params)) {
2468 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2469 return;
2470 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002471 Blob keyBlob;
2472 String8 name8(name);
2473 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2474 TYPE_KEYMASTER_10);
2475 if (responseCode != ::NO_ERROR) {
2476 result->resultCode = responseCode;
2477 return;
2478 }
2479 keymaster_key_blob_t key;
2480 key.key_material_size = keyBlob.getLength();
2481 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002482 keymaster_operation_handle_t handle;
2483 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002484 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002485 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002486 Unique_keymaster_key_characteristics characteristics;
2487 characteristics.reset(new keymaster_key_characteristics_t);
2488 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2489 if (err) {
2490 result->resultCode = err;
2491 return;
2492 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002493 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002494 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002495 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002496 // If per-operation auth is needed we need to begin the operation and
2497 // the client will need to authorize that operation before calling
2498 // update. Any other auth issues stop here.
2499 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2500 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002501 return;
2502 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002503 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002504 // Add entropy to the device first.
2505 if (entropy) {
2506 if (dev->add_rng_entropy) {
2507 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2508 } else {
2509 err = KM_ERROR_UNIMPLEMENTED;
2510 }
2511 if (err) {
2512 result->resultCode = err;
2513 return;
2514 }
2515 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002516 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002517
Shawn Willden9221bff2015-06-18 18:23:54 -06002518 // Create a keyid for this key.
2519 keymaster::km_id_t keyid;
2520 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2521 ALOGE("Failed to create a key ID for authorization checking.");
2522 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2523 return;
2524 }
2525
2526 // Check that all key authorization policy requirements are met.
2527 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2528 key_auths.push_back(characteristics->sw_enforced);
2529 keymaster::AuthorizationSet operation_params(inParams);
2530 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2531 0 /* op_handle */,
2532 true /* is_begin_operation */);
2533 if (err) {
2534 result->resultCode = err;
2535 return;
2536 }
2537
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002538 keymaster_key_param_set_t outParams = {NULL, 0};
2539 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2540
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002541 // If there are too many operations abort the oldest operation that was
2542 // started as pruneable and try again.
2543 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2544 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2545 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002546
2547 // We mostly ignore errors from abort() below because all we care about is whether at
2548 // least one pruneable operation has been removed.
2549 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2550 int abort_error = abort(oldest);
2551 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2552 if (op_count_after >= op_count_before) {
2553 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2554 ALOGE("Failed to remove pruneable operation %p, error: %d",
2555 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002556 break;
2557 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002558 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002559 }
2560 if (err) {
2561 result->resultCode = err;
2562 return;
2563 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002564
Shawn Willden9221bff2015-06-18 18:23:54 -06002565 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2566 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002567 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002568 if (authToken) {
2569 mOperationMap.setOperationAuthToken(operationToken, authToken);
2570 }
2571 // Return the authentication lookup result. If this is a per operation
2572 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2573 // application should get an auth token using the handle before the
2574 // first call to update, which will fail if keystore hasn't received the
2575 // auth token.
2576 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002577 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002578 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002579 if (outParams.params) {
2580 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2581 free(outParams.params);
2582 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002583 }
2584
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002585 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2586 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002587 if (!checkAllowedOperationParams(params.params)) {
2588 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2589 return;
2590 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002591 const keymaster1_device_t* dev;
2592 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002593 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002594 keymaster::km_id_t keyid;
2595 const keymaster_key_characteristics_t* characteristics;
2596 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002597 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2598 return;
2599 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002600 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002601 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2602 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002603 result->resultCode = authResult;
2604 return;
2605 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002606 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2607 keymaster_blob_t input = {data, dataLength};
2608 size_t consumed = 0;
2609 keymaster_blob_t output = {NULL, 0};
2610 keymaster_key_param_set_t outParams = {NULL, 0};
2611
Shawn Willden9221bff2015-06-18 18:23:54 -06002612 // Check that all key authorization policy requirements are met.
2613 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2614 key_auths.push_back(characteristics->sw_enforced);
2615 keymaster::AuthorizationSet operation_params(inParams);
2616 result->resultCode =
2617 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2618 operation_params, handle,
2619 false /* is_begin_operation */);
2620 if (result->resultCode) {
2621 return;
2622 }
2623
Chad Brubaker57e106d2015-06-01 12:59:00 -07002624 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2625 &output);
2626 result->data.reset(const_cast<uint8_t*>(output.data));
2627 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002628 result->inputConsumed = consumed;
2629 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002630 if (outParams.params) {
2631 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2632 free(outParams.params);
2633 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002634 }
2635
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002636 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002637 const uint8_t* signature, size_t signatureLength,
2638 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002639 if (!checkAllowedOperationParams(params.params)) {
2640 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2641 return;
2642 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002643 const keymaster1_device_t* dev;
2644 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002645 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002646 keymaster::km_id_t keyid;
2647 const keymaster_key_characteristics_t* characteristics;
2648 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002649 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2650 return;
2651 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002652 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002653 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2654 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002655 result->resultCode = authResult;
2656 return;
2657 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002658 keymaster_error_t err;
2659 if (entropy) {
2660 if (dev->add_rng_entropy) {
2661 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2662 } else {
2663 err = KM_ERROR_UNIMPLEMENTED;
2664 }
2665 if (err) {
2666 result->resultCode = err;
2667 return;
2668 }
2669 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002670
Chad Brubaker57e106d2015-06-01 12:59:00 -07002671 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2672 keymaster_blob_t input = {signature, signatureLength};
2673 keymaster_blob_t output = {NULL, 0};
2674 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002675
2676 // Check that all key authorization policy requirements are met.
2677 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2678 key_auths.push_back(characteristics->sw_enforced);
2679 keymaster::AuthorizationSet operation_params(inParams);
2680 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2681 handle, false /* is_begin_operation */);
2682 if (err) {
2683 result->resultCode = err;
2684 return;
2685 }
2686
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002687 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002688 // Remove the operation regardless of the result
2689 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002690 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002691
2692 result->data.reset(const_cast<uint8_t*>(output.data));
2693 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002694 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002695 if (outParams.params) {
2696 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2697 free(outParams.params);
2698 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002699 }
2700
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002701 int32_t abort(const sp<IBinder>& token) {
2702 const keymaster1_device_t* dev;
2703 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002704 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002705 keymaster::km_id_t keyid;
2706 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002707 return KM_ERROR_INVALID_OPERATION_HANDLE;
2708 }
2709 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002710 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002711 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002712 rc = KM_ERROR_UNIMPLEMENTED;
2713 } else {
2714 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002715 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002716 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002717 if (rc) {
2718 return rc;
2719 }
2720 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002721 }
2722
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002723 bool isOperationAuthorized(const sp<IBinder>& token) {
2724 const keymaster1_device_t* dev;
2725 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002726 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002727 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002728 keymaster::km_id_t keyid;
2729 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002730 return false;
2731 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002732 const hw_auth_token_t* authToken = NULL;
2733 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002734 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002735 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2736 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002737 }
2738
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002739 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002740 if (!checkBinderPermission(P_ADD_AUTH)) {
2741 ALOGW("addAuthToken: permission denied for %d",
2742 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002743 return ::PERMISSION_DENIED;
2744 }
2745 if (length != sizeof(hw_auth_token_t)) {
2746 return KM_ERROR_INVALID_ARGUMENT;
2747 }
2748 hw_auth_token_t* authToken = new hw_auth_token_t;
2749 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2750 // The table takes ownership of authToken.
2751 mAuthTokenTable.AddAuthenticationToken(authToken);
2752 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002753 }
2754
Kenny Root07438c82012-11-02 15:41:02 -07002755private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002756 static const int32_t UID_SELF = -1;
2757
2758 /**
2759 * Get the effective target uid for a binder operation that takes an
2760 * optional uid as the target.
2761 */
2762 inline uid_t getEffectiveUid(int32_t targetUid) {
2763 if (targetUid == UID_SELF) {
2764 return IPCThreadState::self()->getCallingUid();
2765 }
2766 return static_cast<uid_t>(targetUid);
2767 }
2768
2769 /**
2770 * Check if the caller of the current binder method has the required
2771 * permission and if acting on other uids the grants to do so.
2772 */
2773 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2774 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2775 pid_t spid = IPCThreadState::self()->getCallingPid();
2776 if (!has_permission(callingUid, permission, spid)) {
2777 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2778 return false;
2779 }
2780 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2781 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2782 return false;
2783 }
2784 return true;
2785 }
2786
2787 /**
2788 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002789 * permission and the target uid is the caller or the caller is system.
2790 */
2791 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2792 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2793 pid_t spid = IPCThreadState::self()->getCallingPid();
2794 if (!has_permission(callingUid, permission, spid)) {
2795 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2796 return false;
2797 }
2798 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2799 }
2800
2801 /**
2802 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002803 * permission or the target of the operation is the caller's uid. This is
2804 * for operation where the permission is only for cross-uid activity and all
2805 * uids are allowed to act on their own (ie: clearing all entries for a
2806 * given uid).
2807 */
2808 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2809 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2810 if (getEffectiveUid(targetUid) == callingUid) {
2811 return true;
2812 } else {
2813 return checkBinderPermission(permission, targetUid);
2814 }
2815 }
2816
2817 /**
2818 * Helper method to check that the caller has the required permission as
2819 * well as the keystore is in the unlocked state if checkUnlocked is true.
2820 *
2821 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2822 * otherwise the state of keystore when not unlocked and checkUnlocked is
2823 * true.
2824 */
2825 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2826 bool checkUnlocked = true) {
2827 if (!checkBinderPermission(permission, targetUid)) {
2828 return ::PERMISSION_DENIED;
2829 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002830 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002831 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2832 return state;
2833 }
2834
2835 return ::NO_ERROR;
2836
2837 }
2838
Kenny Root9d45d1c2013-02-14 10:32:30 -08002839 inline bool isKeystoreUnlocked(State state) {
2840 switch (state) {
2841 case ::STATE_NO_ERROR:
2842 return true;
2843 case ::STATE_UNINITIALIZED:
2844 case ::STATE_LOCKED:
2845 return false;
2846 }
2847 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002848 }
2849
Chad Brubaker67d2a502015-03-11 17:21:18 +00002850 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002851 const int32_t device_api = device->common.module->module_api_version;
2852 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2853 switch (keyType) {
2854 case TYPE_RSA:
2855 case TYPE_DSA:
2856 case TYPE_EC:
2857 return true;
2858 default:
2859 return false;
2860 }
2861 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2862 switch (keyType) {
2863 case TYPE_RSA:
2864 return true;
2865 case TYPE_DSA:
2866 return device->flags & KEYMASTER_SUPPORTS_DSA;
2867 case TYPE_EC:
2868 return device->flags & KEYMASTER_SUPPORTS_EC;
2869 default:
2870 return false;
2871 }
2872 } else {
2873 return keyType == TYPE_RSA;
2874 }
2875 }
2876
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002877 /**
2878 * Check that all keymaster_key_param_t's provided by the application are
2879 * allowed. Any parameter that keystore adds itself should be disallowed here.
2880 */
2881 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2882 for (auto param: params) {
2883 switch (param.tag) {
2884 case KM_TAG_AUTH_TOKEN:
2885 return false;
2886 default:
2887 break;
2888 }
2889 }
2890 return true;
2891 }
2892
2893 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2894 const keymaster1_device_t* dev,
2895 const std::vector<keymaster_key_param_t>& params,
2896 keymaster_key_characteristics_t* out) {
2897 UniquePtr<keymaster_blob_t> appId;
2898 UniquePtr<keymaster_blob_t> appData;
2899 for (auto param : params) {
2900 if (param.tag == KM_TAG_APPLICATION_ID) {
2901 appId.reset(new keymaster_blob_t);
2902 appId->data = param.blob.data;
2903 appId->data_length = param.blob.data_length;
2904 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2905 appData.reset(new keymaster_blob_t);
2906 appData->data = param.blob.data;
2907 appData->data_length = param.blob.data_length;
2908 }
2909 }
2910 keymaster_key_characteristics_t* result = NULL;
2911 if (!dev->get_key_characteristics) {
2912 return KM_ERROR_UNIMPLEMENTED;
2913 }
2914 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2915 appData.get(), &result);
2916 if (result) {
2917 *out = *result;
2918 free(result);
2919 }
2920 return error;
2921 }
2922
2923 /**
2924 * Get the auth token for this operation from the auth token table.
2925 *
2926 * Returns ::NO_ERROR if the auth token was set or none was required.
2927 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2928 * authorization token exists for that operation and
2929 * failOnTokenMissing is false.
2930 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2931 * token for the operation
2932 */
2933 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2934 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002935 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002936 const hw_auth_token_t** authToken,
2937 bool failOnTokenMissing = true) {
2938
2939 std::vector<keymaster_key_param_t> allCharacteristics;
2940 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2941 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2942 }
2943 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2944 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2945 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002946 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
2947 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002948 switch (err) {
2949 case keymaster::AuthTokenTable::OK:
2950 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2951 return ::NO_ERROR;
2952 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2953 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2954 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2955 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2956 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2957 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2958 (int32_t) ::OP_AUTH_NEEDED;
2959 default:
2960 ALOGE("Unexpected FindAuthorization return value %d", err);
2961 return KM_ERROR_INVALID_ARGUMENT;
2962 }
2963 }
2964
2965 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2966 const hw_auth_token_t* token) {
2967 if (token) {
2968 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2969 reinterpret_cast<const uint8_t*>(token),
2970 sizeof(hw_auth_token_t)));
2971 }
2972 }
2973
2974 /**
2975 * Add the auth token for the operation to the param list if the operation
2976 * requires authorization. Uses the cached result in the OperationMap if available
2977 * otherwise gets the token from the AuthTokenTable and caches the result.
2978 *
2979 * Returns ::NO_ERROR if the auth token was added or not needed.
2980 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2981 * authenticated.
2982 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2983 * operation token.
2984 */
2985 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2986 std::vector<keymaster_key_param_t>* params) {
2987 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002988 mOperationMap.getOperationAuthToken(token, &authToken);
2989 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002990 const keymaster1_device_t* dev;
2991 keymaster_operation_handle_t handle;
2992 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002993 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002994 keymaster::km_id_t keyid;
2995 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
2996 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002997 return KM_ERROR_INVALID_OPERATION_HANDLE;
2998 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002999 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003000 if (result != ::NO_ERROR) {
3001 return result;
3002 }
3003 if (authToken) {
3004 mOperationMap.setOperationAuthToken(token, authToken);
3005 }
3006 }
3007 addAuthToParams(params, authToken);
3008 return ::NO_ERROR;
3009 }
3010
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003011 /**
3012 * Translate a result value to a legacy return value. All keystore errors are
3013 * preserved and keymaster errors become SYSTEM_ERRORs
3014 */
3015 inline int32_t translateResultToLegacyResult(int32_t result) {
3016 if (result > 0) {
3017 return result;
3018 }
3019 return ::SYSTEM_ERROR;
3020 }
3021
Shawn Willden2de8b752015-07-23 05:54:31 -06003022 void addLegacyKeyAuthorizations(std::vector<keymaster_key_param_t>& params, int keyType) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003023 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
3024 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
3025 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
3026 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
3027 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
Shawn Willden2de8b752015-07-23 05:54:31 -06003028 if (keyType == EVP_PKEY_RSA) {
3029 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
3030 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
3031 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PSS));
3032 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_OAEP));
3033 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003034 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
Shawn Willden2de8b752015-07-23 05:54:31 -06003035 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_MD5));
3036 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA1));
3037 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_224));
3038 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_256));
3039 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_384));
3040 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_512));
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003041 params.push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
3042 params.push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
3043 params.push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
3044 params.push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
3045 params.push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
3046 uint64_t now = keymaster::java_time(time(NULL));
3047 params.push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
3048 }
3049
3050 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3051 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3052 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3053 return &characteristics->hw_enforced.params[i];
3054 }
3055 }
3056 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3057 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3058 return &characteristics->sw_enforced.params[i];
3059 }
3060 }
3061 return NULL;
3062 }
3063
3064 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3065 // All legacy keys are DIGEST_NONE/PAD_NONE.
3066 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3067 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3068
3069 // Look up the algorithm of the key.
3070 KeyCharacteristics characteristics;
3071 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3072 if (rc != ::NO_ERROR) {
3073 ALOGE("Failed to get key characteristics");
3074 return;
3075 }
3076 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3077 if (!algorithm) {
3078 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3079 return;
3080 }
3081 params.push_back(*algorithm);
3082 }
3083
3084 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3085 uint8_t** out, size_t* outLength, const uint8_t* signature,
3086 size_t signatureLength, keymaster_purpose_t purpose) {
3087
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003088 std::basic_stringstream<uint8_t> outBuffer;
3089 OperationResult result;
3090 KeymasterArguments inArgs;
3091 addLegacyBeginParams(name, inArgs.params);
3092 sp<IBinder> appToken(new BBinder);
3093 sp<IBinder> token;
3094
3095 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3096 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003097 if (result.resultCode == ::KEY_NOT_FOUND) {
3098 ALOGW("Key not found");
3099 } else {
3100 ALOGW("Error in begin: %d", result.resultCode);
3101 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003102 return translateResultToLegacyResult(result.resultCode);
3103 }
3104 inArgs.params.clear();
3105 token = result.token;
3106 size_t consumed = 0;
3107 size_t lastConsumed = 0;
3108 do {
3109 update(token, inArgs, data + consumed, length - consumed, &result);
3110 if (result.resultCode != ResponseCode::NO_ERROR) {
3111 ALOGW("Error in update: %d", result.resultCode);
3112 return translateResultToLegacyResult(result.resultCode);
3113 }
3114 if (out) {
3115 outBuffer.write(result.data.get(), result.dataLength);
3116 }
3117 lastConsumed = result.inputConsumed;
3118 consumed += lastConsumed;
3119 } while (consumed < length && lastConsumed > 0);
3120
3121 if (consumed != length) {
3122 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3123 return ::SYSTEM_ERROR;
3124 }
3125
3126 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3127 if (result.resultCode != ResponseCode::NO_ERROR) {
3128 ALOGW("Error in finish: %d", result.resultCode);
3129 return translateResultToLegacyResult(result.resultCode);
3130 }
3131 if (out) {
3132 outBuffer.write(result.data.get(), result.dataLength);
3133 }
3134
3135 if (out) {
3136 auto buf = outBuffer.str();
3137 *out = new uint8_t[buf.size()];
3138 memcpy(*out, buf.c_str(), buf.size());
3139 *outLength = buf.size();
3140 }
3141
3142 return ::NO_ERROR;
3143 }
3144
Kenny Root07438c82012-11-02 15:41:02 -07003145 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003146 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003147 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003148 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003149};
3150
3151}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003152
3153int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003154 if (argc < 2) {
3155 ALOGE("A directory must be specified!");
3156 return 1;
3157 }
3158 if (chdir(argv[1]) == -1) {
3159 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3160 return 1;
3161 }
3162
3163 Entropy entropy;
3164 if (!entropy.open()) {
3165 return 1;
3166 }
Kenny Root70e3a862012-02-15 17:20:23 -08003167
Chad Brubakerbd07a232015-06-01 10:44:27 -07003168 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003169 if (keymaster_device_initialize(&dev)) {
3170 ALOGE("keystore keymaster could not be initialized; exiting");
3171 return 1;
3172 }
3173
Chad Brubaker67d2a502015-03-11 17:21:18 +00003174 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003175 if (fallback_keymaster_device_initialize(&fallback)) {
3176 ALOGE("software keymaster could not be initialized; exiting");
3177 return 1;
3178 }
3179
Riley Spahneaabae92014-06-30 12:39:52 -07003180 ks_is_selinux_enabled = is_selinux_enabled();
3181 if (ks_is_selinux_enabled) {
3182 union selinux_callback cb;
William Robertse46b8552015-10-02 08:19:52 -07003183 cb.func_audit = audit_callback;
3184 selinux_set_callback(SELINUX_CB_AUDIT, cb);
Riley Spahneaabae92014-06-30 12:39:52 -07003185 cb.func_log = selinux_log_callback;
3186 selinux_set_callback(SELINUX_CB_LOG, cb);
3187 if (getcon(&tctx) != 0) {
3188 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3189 return -1;
3190 }
3191 } else {
3192 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3193 }
3194
Chad Brubakerbd07a232015-06-01 10:44:27 -07003195 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003196 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003197 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3198 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3199 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3200 if (ret != android::OK) {
3201 ALOGE("Couldn't register binder service!");
3202 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003203 }
Kenny Root07438c82012-11-02 15:41:02 -07003204
3205 /*
3206 * We're the only thread in existence, so we're just going to process
3207 * Binder transaction as a single-threaded program.
3208 */
3209 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003210
3211 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003212 return 1;
3213}