blob: 35048430a39a4da957f91d38ad07a6dcfe9ad118 [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 Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Chad Brubakerbd07a232015-06-01 10:44:27 -0700109static int keymaster_device_initialize(keymaster1_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
Chad Brubakerbd07a232015-06-01 10:44:27 -0700113 keymaster::SoftKeymasterDevice* softkeymaster = NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800114 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
115 if (rc) {
116 ALOGE("could not find any keystore module");
117 goto out;
118 }
119
Chad Brubakerbd07a232015-06-01 10:44:27 -0700120 rc = mod->methods->open(mod, KEYSTORE_KEYMASTER, reinterpret_cast<struct hw_device_t**>(dev));
Kenny Root70e3a862012-02-15 17:20:23 -0800121 if (rc) {
122 ALOGE("could not open keymaster device in %s (%s)",
123 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
124 goto out;
125 }
126
Chad Brubakerbd07a232015-06-01 10:44:27 -0700127 // Wrap older hardware modules with a softkeymaster adapter.
128 if ((*dev)->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0) {
129 return 0;
130 }
131 softkeymaster =
132 new keymaster::SoftKeymasterDevice(reinterpret_cast<keymaster0_device_t*>(*dev));
133 *dev = softkeymaster->keymaster_device();
Kenny Root70e3a862012-02-15 17:20:23 -0800134 return 0;
135
136out:
137 *dev = NULL;
138 return rc;
139}
140
Shawn Willden04006752015-04-30 11:12:33 -0600141// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
142// logger used by SoftKeymasterDevice.
143static keymaster::SoftKeymasterLogger softkeymaster_logger;
144
Chad Brubaker67d2a502015-03-11 17:21:18 +0000145static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
146 keymaster::SoftKeymasterDevice* softkeymaster =
147 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600148 *dev = softkeymaster->keymaster_device();
149 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800150 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800151}
152
Chad Brubakerbd07a232015-06-01 10:44:27 -0700153static void keymaster_device_release(keymaster1_device_t* dev) {
154 dev->common.close(&dev->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800155}
156
Kenny Root07438c82012-11-02 15:41:02 -0700157/***************
158 * PERMISSIONS *
159 ***************/
160
161/* Here are the permissions, actions, users, and the main function. */
162typedef enum {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700163 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100164 P_GET = 1 << 1,
165 P_INSERT = 1 << 2,
166 P_DELETE = 1 << 3,
167 P_EXIST = 1 << 4,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700168 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100169 P_RESET = 1 << 6,
170 P_PASSWORD = 1 << 7,
171 P_LOCK = 1 << 8,
172 P_UNLOCK = 1 << 9,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700173 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100174 P_SIGN = 1 << 11,
175 P_VERIFY = 1 << 12,
176 P_GRANT = 1 << 13,
177 P_DUPLICATE = 1 << 14,
178 P_CLEAR_UID = 1 << 15,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700179 P_ADD_AUTH = 1 << 16,
180 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700181} perm_t;
182
183static struct user_euid {
184 uid_t uid;
185 uid_t euid;
186} user_euids[] = {
187 {AID_VPN, AID_SYSTEM},
188 {AID_WIFI, AID_SYSTEM},
189 {AID_ROOT, AID_SYSTEM},
190};
191
Riley Spahneaabae92014-06-30 12:39:52 -0700192/* perm_labels associcated with keystore_key SELinux class verbs. */
193const char *perm_labels[] = {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700194 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700195 "get",
196 "insert",
197 "delete",
198 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700199 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700200 "reset",
201 "password",
202 "lock",
203 "unlock",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700204 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700205 "sign",
206 "verify",
207 "grant",
208 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100209 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700210 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700211 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700212};
213
Kenny Root07438c82012-11-02 15:41:02 -0700214static struct user_perm {
215 uid_t uid;
216 perm_t perms;
217} user_perms[] = {
218 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
219 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
220 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
221 {AID_ROOT, static_cast<perm_t>(P_GET) },
222};
223
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700224static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
225 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700226
Riley Spahneaabae92014-06-30 12:39:52 -0700227static char *tctx;
228static int ks_is_selinux_enabled;
229
230static const char *get_perm_label(perm_t perm) {
231 unsigned int index = ffs(perm);
232 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
233 return perm_labels[index - 1];
234 } else {
235 ALOGE("Keystore: Failed to retrieve permission label.\n");
236 abort();
237 }
238}
239
Kenny Root655b9582013-04-04 08:37:42 -0700240/**
241 * Returns the app ID (in the Android multi-user sense) for the current
242 * UNIX UID.
243 */
244static uid_t get_app_id(uid_t uid) {
245 return uid % AID_USER;
246}
247
248/**
249 * Returns the user ID (in the Android multi-user sense) for the current
250 * UNIX UID.
251 */
252static uid_t get_user_id(uid_t uid) {
253 return uid / AID_USER;
254}
255
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700256static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700257 if (!ks_is_selinux_enabled) {
258 return true;
259 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000260
Riley Spahneaabae92014-06-30 12:39:52 -0700261 char *sctx = NULL;
262 const char *selinux_class = "keystore_key";
263 const char *str_perm = get_perm_label(perm);
264
265 if (!str_perm) {
266 return false;
267 }
268
269 if (getpidcon(spid, &sctx) != 0) {
270 ALOGE("SELinux: Failed to get source pid context.\n");
271 return false;
272 }
273
274 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
275 NULL) == 0;
276 freecon(sctx);
277 return allowed;
278}
279
280static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700281 // All system users are equivalent for multi-user support.
282 if (get_app_id(uid) == AID_SYSTEM) {
283 uid = AID_SYSTEM;
284 }
285
Kenny Root07438c82012-11-02 15:41:02 -0700286 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
287 struct user_perm user = user_perms[i];
288 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700289 return (user.perms & perm) &&
290 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700291 }
292 }
293
Riley Spahneaabae92014-06-30 12:39:52 -0700294 return (DEFAULT_PERMS & perm) &&
295 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700296}
297
Kenny Root49468902013-03-19 13:41:33 -0700298/**
299 * Returns the UID that the callingUid should act as. This is here for
300 * legacy support of the WiFi and VPN systems and should be removed
301 * when WiFi can operate in its own namespace.
302 */
Kenny Root07438c82012-11-02 15:41:02 -0700303static uid_t get_keystore_euid(uid_t uid) {
304 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
305 struct user_euid user = user_euids[i];
306 if (user.uid == uid) {
307 return user.euid;
308 }
309 }
310
311 return uid;
312}
313
Kenny Root49468902013-03-19 13:41:33 -0700314/**
315 * Returns true if the callingUid is allowed to interact in the targetUid's
316 * namespace.
317 */
318static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700319 if (callingUid == targetUid) {
320 return true;
321 }
Kenny Root49468902013-03-19 13:41:33 -0700322 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
323 struct user_euid user = user_euids[i];
324 if (user.euid == callingUid && user.uid == targetUid) {
325 return true;
326 }
327 }
328
329 return false;
330}
331
Kenny Roota91203b2012-02-15 15:00:46 -0800332/* Here is the encoding of keys. This is necessary in order to allow arbitrary
333 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
334 * into two bytes. The first byte is one of [+-.] which represents the first
335 * two bits of the character. The second byte encodes the rest of the bits into
336 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
337 * that Base64 cannot be used here due to the need of prefix match on keys. */
338
Kenny Root655b9582013-04-04 08:37:42 -0700339static size_t encode_key_length(const android::String8& keyName) {
340 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
341 size_t length = keyName.length();
342 for (int i = length; i > 0; --i, ++in) {
343 if (*in < '0' || *in > '~') {
344 ++length;
345 }
346 }
347 return length;
348}
349
Kenny Root07438c82012-11-02 15:41:02 -0700350static int encode_key(char* out, const android::String8& keyName) {
351 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
352 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800353 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700354 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800355 *out = '+' + (*in >> 6);
356 *++out = '0' + (*in & 0x3F);
357 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700358 } else {
359 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800360 }
361 }
362 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800363 return length;
364}
365
Kenny Root07438c82012-11-02 15:41:02 -0700366/*
367 * Converts from the "escaped" format on disk to actual name.
368 * This will be smaller than the input string.
369 *
370 * Characters that should combine with the next at the end will be truncated.
371 */
372static size_t decode_key_length(const char* in, size_t length) {
373 size_t outLength = 0;
374
375 for (const char* end = in + length; in < end; in++) {
376 /* This combines with the next character. */
377 if (*in < '0' || *in > '~') {
378 continue;
379 }
380
381 outLength++;
382 }
383 return outLength;
384}
385
386static void decode_key(char* out, const char* in, size_t length) {
387 for (const char* end = in + length; in < end; in++) {
388 if (*in < '0' || *in > '~') {
389 /* Truncate combining characters at the end. */
390 if (in + 1 >= end) {
391 break;
392 }
393
394 *out = (*in++ - '+') << 6;
395 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800396 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700397 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800398 }
399 }
400 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800401}
402
403static size_t readFully(int fd, uint8_t* data, size_t size) {
404 size_t remaining = size;
405 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800406 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800407 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800408 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800409 }
410 data += n;
411 remaining -= n;
412 }
413 return size;
414}
415
416static size_t writeFully(int fd, uint8_t* data, size_t size) {
417 size_t remaining = size;
418 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800419 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
420 if (n < 0) {
421 ALOGW("write failed: %s", strerror(errno));
422 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800423 }
424 data += n;
425 remaining -= n;
426 }
427 return size;
428}
429
430class Entropy {
431public:
432 Entropy() : mRandom(-1) {}
433 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800434 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800435 close(mRandom);
436 }
437 }
438
439 bool open() {
440 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800441 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
442 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800443 ALOGE("open: %s: %s", randomDevice, strerror(errno));
444 return false;
445 }
446 return true;
447 }
448
Kenny Root51878182012-03-13 12:53:19 -0700449 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800450 return (readFully(mRandom, data, size) == size);
451 }
452
453private:
454 int mRandom;
455};
456
457/* Here is the file format. There are two parts in blob.value, the secret and
458 * the description. The secret is stored in ciphertext, and its original size
459 * can be found in blob.length. The description is stored after the secret in
460 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700461 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700462 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800463 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
464 * and decryptBlob(). Thus they should not be accessed from outside. */
465
Kenny Root822c3a92012-03-23 16:34:39 -0700466/* ** Note to future implementors of encryption: **
467 * Currently this is the construction:
468 * metadata || Enc(MD5(data) || data)
469 *
470 * This should be the construction used for encrypting if re-implementing:
471 *
472 * Derive independent keys for encryption and MAC:
473 * Kenc = AES_encrypt(masterKey, "Encrypt")
474 * Kmac = AES_encrypt(masterKey, "MAC")
475 *
476 * Store this:
477 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
478 * HMAC(Kmac, metadata || Enc(data))
479 */
Kenny Roota91203b2012-02-15 15:00:46 -0800480struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700481 uint8_t version;
482 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700483 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800484 uint8_t info;
485 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700486 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800487 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700488 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800489 int32_t length; // in network byte order when encrypted
490 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
491};
492
Kenny Root822c3a92012-03-23 16:34:39 -0700493typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700494 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700495 TYPE_GENERIC = 1,
496 TYPE_MASTER_KEY = 2,
497 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800498 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700499} BlobType;
500
Kenny Rootf9119d62013-04-03 09:22:15 -0700501static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700502
Kenny Roota91203b2012-02-15 15:00:46 -0800503class Blob {
504public:
Kenny Root07438c82012-11-02 15:41:02 -0700505 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
506 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800507 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800508 mBlob.length = valueLength;
509 memcpy(mBlob.value, value, valueLength);
510
511 mBlob.info = infoLength;
512 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700513
Kenny Root07438c82012-11-02 15:41:02 -0700514 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700515 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700516
Kenny Rootee8068b2013-10-07 09:49:15 -0700517 if (type == TYPE_MASTER_KEY) {
518 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
519 } else {
520 mBlob.flags = KEYSTORE_FLAG_NONE;
521 }
Kenny Roota91203b2012-02-15 15:00:46 -0800522 }
523
524 Blob(blob b) {
525 mBlob = b;
526 }
527
Alex Klyubin1773b442015-02-20 12:33:33 -0800528 Blob() {
529 memset(&mBlob, 0, sizeof(mBlob));
530 }
Kenny Roota91203b2012-02-15 15:00:46 -0800531
Kenny Root51878182012-03-13 12:53:19 -0700532 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.value;
534 }
535
Kenny Root51878182012-03-13 12:53:19 -0700536 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 return mBlob.length;
538 }
539
Kenny Root51878182012-03-13 12:53:19 -0700540 const uint8_t* getInfo() const {
541 return mBlob.value + mBlob.length;
542 }
543
544 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800545 return mBlob.info;
546 }
547
Kenny Root822c3a92012-03-23 16:34:39 -0700548 uint8_t getVersion() const {
549 return mBlob.version;
550 }
551
Kenny Rootf9119d62013-04-03 09:22:15 -0700552 bool isEncrypted() const {
553 if (mBlob.version < 2) {
554 return true;
555 }
556
557 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
558 }
559
560 void setEncrypted(bool encrypted) {
561 if (encrypted) {
562 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
563 } else {
564 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
565 }
566 }
567
Kenny Root17208e02013-09-04 13:56:03 -0700568 bool isFallback() const {
569 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
570 }
571
572 void setFallback(bool fallback) {
573 if (fallback) {
574 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
575 } else {
576 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
577 }
578 }
579
Kenny Root822c3a92012-03-23 16:34:39 -0700580 void setVersion(uint8_t version) {
581 mBlob.version = version;
582 }
583
584 BlobType getType() const {
585 return BlobType(mBlob.type);
586 }
587
588 void setType(BlobType type) {
589 mBlob.type = uint8_t(type);
590 }
591
Kenny Rootf9119d62013-04-03 09:22:15 -0700592 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
593 ALOGV("writing blob %s", filename);
594 if (isEncrypted()) {
595 if (state != STATE_NO_ERROR) {
596 ALOGD("couldn't insert encrypted blob while not unlocked");
597 return LOCKED;
598 }
599
600 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
601 ALOGW("Could not read random data for: %s", filename);
602 return SYSTEM_ERROR;
603 }
Kenny Roota91203b2012-02-15 15:00:46 -0800604 }
605
606 // data includes the value and the value's length
607 size_t dataLength = mBlob.length + sizeof(mBlob.length);
608 // pad data to the AES_BLOCK_SIZE
609 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
610 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
611 // encrypted data includes the digest value
612 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
613 // move info after space for padding
614 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
615 // zero padding area
616 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
617
618 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800619
Kenny Rootf9119d62013-04-03 09:22:15 -0700620 if (isEncrypted()) {
621 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800622
Kenny Rootf9119d62013-04-03 09:22:15 -0700623 uint8_t vector[AES_BLOCK_SIZE];
624 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
625 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
626 aes_key, vector, AES_ENCRYPT);
627 }
628
Kenny Roota91203b2012-02-15 15:00:46 -0800629 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
630 size_t fileLength = encryptedLength + headerLength + mBlob.info;
631
632 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800633 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
634 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
635 if (out < 0) {
636 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800637 return SYSTEM_ERROR;
638 }
639 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
640 if (close(out) != 0) {
641 return SYSTEM_ERROR;
642 }
643 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800644 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800645 unlink(tmpFileName);
646 return SYSTEM_ERROR;
647 }
Kenny Root150ca932012-11-14 14:29:02 -0800648 if (rename(tmpFileName, filename) == -1) {
649 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
650 return SYSTEM_ERROR;
651 }
652 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800653 }
654
Kenny Rootf9119d62013-04-03 09:22:15 -0700655 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
656 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800657 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
658 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800659 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
660 }
661 // fileLength may be less than sizeof(mBlob) since the in
662 // memory version has extra padding to tolerate rounding up to
663 // the AES_BLOCK_SIZE
664 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
665 if (close(in) != 0) {
666 return SYSTEM_ERROR;
667 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700668
669 if (isEncrypted() && (state != STATE_NO_ERROR)) {
670 return LOCKED;
671 }
672
Kenny Roota91203b2012-02-15 15:00:46 -0800673 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
674 if (fileLength < headerLength) {
675 return VALUE_CORRUPTED;
676 }
677
678 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700679 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800680 return VALUE_CORRUPTED;
681 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700682
683 ssize_t digestedLength;
684 if (isEncrypted()) {
685 if (encryptedLength % AES_BLOCK_SIZE != 0) {
686 return VALUE_CORRUPTED;
687 }
688
689 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
690 mBlob.vector, AES_DECRYPT);
691 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
692 uint8_t computedDigest[MD5_DIGEST_LENGTH];
693 MD5(mBlob.digested, digestedLength, computedDigest);
694 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
695 return VALUE_CORRUPTED;
696 }
697 } else {
698 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800699 }
700
701 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
702 mBlob.length = ntohl(mBlob.length);
703 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
704 return VALUE_CORRUPTED;
705 }
706 if (mBlob.info != 0) {
707 // move info from after padding to after data
708 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
709 }
Kenny Root07438c82012-11-02 15:41:02 -0700710 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800711 }
712
713private:
714 struct blob mBlob;
715};
716
Kenny Root655b9582013-04-04 08:37:42 -0700717class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800718public:
Kenny Root655b9582013-04-04 08:37:42 -0700719 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
720 asprintf(&mUserDir, "user_%u", mUserId);
721 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
722 }
723
724 ~UserState() {
725 free(mUserDir);
726 free(mMasterKeyFile);
727 }
728
729 bool initialize() {
730 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
731 ALOGE("Could not create directory '%s'", mUserDir);
732 return false;
733 }
734
735 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800736 setState(STATE_LOCKED);
737 } else {
738 setState(STATE_UNINITIALIZED);
739 }
Kenny Root70e3a862012-02-15 17:20:23 -0800740
Kenny Root655b9582013-04-04 08:37:42 -0700741 return true;
742 }
743
744 uid_t getUserId() const {
745 return mUserId;
746 }
747
748 const char* getUserDirName() const {
749 return mUserDir;
750 }
751
752 const char* getMasterKeyFileName() const {
753 return mMasterKeyFile;
754 }
755
756 void setState(State state) {
757 mState = state;
758 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
759 mRetry = MAX_RETRY;
760 }
Kenny Roota91203b2012-02-15 15:00:46 -0800761 }
762
Kenny Root51878182012-03-13 12:53:19 -0700763 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800764 return mState;
765 }
766
Kenny Root51878182012-03-13 12:53:19 -0700767 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800768 return mRetry;
769 }
770
Kenny Root655b9582013-04-04 08:37:42 -0700771 void zeroizeMasterKeysInMemory() {
772 memset(mMasterKey, 0, sizeof(mMasterKey));
773 memset(mSalt, 0, sizeof(mSalt));
774 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
775 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800776 }
777
Chad Brubaker96d6d782015-05-07 10:19:40 -0700778 bool deleteMasterKey() {
779 setState(STATE_UNINITIALIZED);
780 zeroizeMasterKeysInMemory();
781 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
782 }
783
Kenny Root655b9582013-04-04 08:37:42 -0700784 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
785 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800786 return SYSTEM_ERROR;
787 }
Kenny Root655b9582013-04-04 08:37:42 -0700788 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800789 if (response != NO_ERROR) {
790 return response;
791 }
792 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700793 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800794 }
795
Robin Lee4e865752014-08-19 17:37:55 +0100796 ResponseCode copyMasterKey(UserState* src) {
797 if (mState != STATE_UNINITIALIZED) {
798 return ::SYSTEM_ERROR;
799 }
800 if (src->getState() != STATE_NO_ERROR) {
801 return ::SYSTEM_ERROR;
802 }
803 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
804 setupMasterKeys();
805 return ::NO_ERROR;
806 }
807
Kenny Root655b9582013-04-04 08:37:42 -0700808 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800809 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
810 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
811 AES_KEY passwordAesKey;
812 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700813 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700814 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800815 }
816
Kenny Root655b9582013-04-04 08:37:42 -0700817 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
818 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800819 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800820 return SYSTEM_ERROR;
821 }
822
823 // we read the raw blob to just to get the salt to generate
824 // the AES key, then we create the Blob to use with decryptBlob
825 blob rawBlob;
826 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
827 if (close(in) != 0) {
828 return SYSTEM_ERROR;
829 }
830 // find salt at EOF if present, otherwise we have an old file
831 uint8_t* salt;
832 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
833 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
834 } else {
835 salt = NULL;
836 }
837 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
838 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
839 AES_KEY passwordAesKey;
840 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
841 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700842 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
843 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800844 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700845 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800846 }
847 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
848 // if salt was missing, generate one and write a new master key file with the salt.
849 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700850 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800851 return SYSTEM_ERROR;
852 }
Kenny Root655b9582013-04-04 08:37:42 -0700853 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800854 }
855 if (response == NO_ERROR) {
856 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
857 setupMasterKeys();
858 }
859 return response;
860 }
861 if (mRetry <= 0) {
862 reset();
863 return UNINITIALIZED;
864 }
865 --mRetry;
866 switch (mRetry) {
867 case 0: return WRONG_PASSWORD_0;
868 case 1: return WRONG_PASSWORD_1;
869 case 2: return WRONG_PASSWORD_2;
870 case 3: return WRONG_PASSWORD_3;
871 default: return WRONG_PASSWORD_3;
872 }
873 }
874
Kenny Root655b9582013-04-04 08:37:42 -0700875 AES_KEY* getEncryptionKey() {
876 return &mMasterKeyEncryption;
877 }
878
879 AES_KEY* getDecryptionKey() {
880 return &mMasterKeyDecryption;
881 }
882
Kenny Roota91203b2012-02-15 15:00:46 -0800883 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700884 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800885 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700886 // If the directory doesn't exist then nothing to do.
887 if (errno == ENOENT) {
888 return true;
889 }
Kenny Root655b9582013-04-04 08:37:42 -0700890 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800891 return false;
892 }
Kenny Root655b9582013-04-04 08:37:42 -0700893
894 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800895 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700896 // skip . and ..
897 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700898 continue;
899 }
900
901 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800902 }
903 closedir(dir);
904 return true;
905 }
906
Kenny Root655b9582013-04-04 08:37:42 -0700907private:
908 static const int MASTER_KEY_SIZE_BYTES = 16;
909 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
910
911 static const int MAX_RETRY = 4;
912 static const size_t SALT_SIZE = 16;
913
914 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
915 uint8_t* salt) {
916 size_t saltSize;
917 if (salt != NULL) {
918 saltSize = SALT_SIZE;
919 } else {
920 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
921 salt = (uint8_t*) "keystore";
922 // sizeof = 9, not strlen = 8
923 saltSize = sizeof("keystore");
924 }
925
926 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
927 saltSize, 8192, keySize, key);
928 }
929
930 bool generateSalt(Entropy* entropy) {
931 return entropy->generate_random_data(mSalt, sizeof(mSalt));
932 }
933
934 bool generateMasterKey(Entropy* entropy) {
935 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
936 return false;
937 }
938 if (!generateSalt(entropy)) {
939 return false;
940 }
941 return true;
942 }
943
944 void setupMasterKeys() {
945 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
946 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
947 setState(STATE_NO_ERROR);
948 }
949
950 uid_t mUserId;
951
952 char* mUserDir;
953 char* mMasterKeyFile;
954
955 State mState;
956 int8_t mRetry;
957
958 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
959 uint8_t mSalt[SALT_SIZE];
960
961 AES_KEY mMasterKeyEncryption;
962 AES_KEY mMasterKeyDecryption;
963};
964
965typedef struct {
966 uint32_t uid;
967 const uint8_t* filename;
968} grant_t;
969
970class KeyStore {
971public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000972 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700973 : mEntropy(entropy)
974 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800975 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700976 {
977 memset(&mMetaData, '\0', sizeof(mMetaData));
978 }
979
980 ~KeyStore() {
981 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
982 it != mGrants.end(); it++) {
983 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700984 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800985 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700986
987 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
988 it != mMasterKeys.end(); it++) {
989 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700990 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800991 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700992 }
993
Chad Brubaker67d2a502015-03-11 17:21:18 +0000994 /**
995 * Depending on the hardware keymaster version is this may return a
996 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
997 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
998 * be guarded by a check on the device's version.
999 */
1000 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001001 return mDevice;
1002 }
1003
Chad Brubaker67d2a502015-03-11 17:21:18 +00001004 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001005 return mFallbackDevice;
1006 }
1007
Chad Brubaker67d2a502015-03-11 17:21:18 +00001008 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001009 return blob.isFallback() ? mFallbackDevice: mDevice;
1010 }
1011
Kenny Root655b9582013-04-04 08:37:42 -07001012 ResponseCode initialize() {
1013 readMetaData();
1014 if (upgradeKeystore()) {
1015 writeMetaData();
1016 }
1017
1018 return ::NO_ERROR;
1019 }
1020
Chad Brubaker72593ee2015-05-12 10:42:00 -07001021 State getState(uid_t userId) {
1022 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001023 }
1024
Chad Brubaker72593ee2015-05-12 10:42:00 -07001025 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1026 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001027 return userState->initialize(pw, mEntropy);
1028 }
1029
Chad Brubaker72593ee2015-05-12 10:42:00 -07001030 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1031 UserState *userState = getUserState(dstUser);
1032 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001033 return userState->copyMasterKey(initState);
1034 }
1035
Chad Brubaker72593ee2015-05-12 10:42:00 -07001036 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1037 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001038 return userState->writeMasterKey(pw, mEntropy);
1039 }
1040
Chad Brubaker72593ee2015-05-12 10:42:00 -07001041 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1042 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001043 return userState->readMasterKey(pw, mEntropy);
1044 }
1045
1046 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001047 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001048 encode_key(encoded, keyName);
1049 return android::String8(encoded);
1050 }
1051
1052 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001053 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001054 encode_key(encoded, keyName);
1055 return android::String8::format("%u_%s", uid, encoded);
1056 }
1057
1058 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001059 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001060 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001061 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001062 encoded);
1063 }
1064
Chad Brubaker96d6d782015-05-07 10:19:40 -07001065 /*
1066 * Delete entries owned by userId. If keepUnencryptedEntries is true
1067 * then only encrypted entries will be removed, otherwise all entries will
1068 * be removed.
1069 */
1070 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001071 android::String8 prefix("");
1072 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001073 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001074 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001075 return;
1076 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001077 for (uint32_t i = 0; i < aliases.size(); i++) {
1078 android::String8 filename(aliases[i]);
1079 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001080 getKeyName(filename).string());
1081 bool shouldDelete = true;
1082 if (keepUnenryptedEntries) {
1083 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001084 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001085
Chad Brubaker96d6d782015-05-07 10:19:40 -07001086 /* get can fail if the blob is encrypted and the state is
1087 * not unlocked, only skip deleting blobs that were loaded and
1088 * who are not encrypted. If there are blobs we fail to read for
1089 * other reasons err on the safe side and delete them since we
1090 * can't tell if they're encrypted.
1091 */
1092 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1093 }
1094 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001095 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001096 }
1097 }
1098 if (!userState->deleteMasterKey()) {
1099 ALOGE("Failed to delete user %d's master key", userId);
1100 }
1101 if (!keepUnenryptedEntries) {
1102 if(!userState->reset()) {
1103 ALOGE("Failed to remove user %d's directory", userId);
1104 }
1105 }
Kenny Root655b9582013-04-04 08:37:42 -07001106 }
1107
Chad Brubaker72593ee2015-05-12 10:42:00 -07001108 bool isEmpty(uid_t userId) const {
1109 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001110 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001111 return true;
1112 }
1113
1114 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001115 if (!dir) {
1116 return true;
1117 }
Kenny Root31e27462014-09-10 11:28:03 -07001118
Kenny Roota91203b2012-02-15 15:00:46 -08001119 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001120 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001121 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001122 // We only care about files.
1123 if (file->d_type != DT_REG) {
1124 continue;
1125 }
1126
1127 // Skip anything that starts with a "."
1128 if (file->d_name[0] == '.') {
1129 continue;
1130 }
1131
Kenny Root31e27462014-09-10 11:28:03 -07001132 result = false;
1133 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001134 }
1135 closedir(dir);
1136 return result;
1137 }
1138
Chad Brubaker72593ee2015-05-12 10:42:00 -07001139 void lock(uid_t userId) {
1140 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001141 userState->zeroizeMasterKeysInMemory();
1142 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001143 }
1144
Chad Brubaker72593ee2015-05-12 10:42:00 -07001145 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1146 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001147 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1148 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001149 if (rc != NO_ERROR) {
1150 return rc;
1151 }
1152
1153 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001154 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001155 /* If we upgrade the key, we need to write it to disk again. Then
1156 * it must be read it again since the blob is encrypted each time
1157 * it's written.
1158 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001159 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1160 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001161 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1162 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001163 return rc;
1164 }
1165 }
Kenny Root822c3a92012-03-23 16:34:39 -07001166 }
1167
Kenny Root17208e02013-09-04 13:56:03 -07001168 /*
1169 * This will upgrade software-backed keys to hardware-backed keys when
1170 * the HAL for the device supports the newer key types.
1171 */
1172 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1173 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1174 && keyBlob->isFallback()) {
1175 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001176 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001177
1178 // The HAL allowed the import, reget the key to have the "fresh"
1179 // version.
1180 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001181 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001182 }
1183 }
1184
Kenny Rootd53bc922013-03-21 14:10:15 -07001185 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001186 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1187 return KEY_NOT_FOUND;
1188 }
1189
1190 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001191 }
1192
Chad Brubaker72593ee2015-05-12 10:42:00 -07001193 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1194 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001195 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1196 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001197 }
1198
Chad Brubaker72593ee2015-05-12 10:42:00 -07001199 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001200 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001201 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001202 if (rc != ::NO_ERROR) {
1203 return rc;
1204 }
1205
1206 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1207 // A device doesn't have to implement delete_keypair.
1208 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1209 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1210 rc = ::SYSTEM_ERROR;
1211 }
1212 }
1213 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001214 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1215 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1216 if (dev->delete_key) {
1217 keymaster_key_blob_t blob;
1218 blob.key_material = keyBlob.getValue();
1219 blob.key_material_size = keyBlob.getLength();
1220 dev->delete_key(dev, &blob);
1221 }
1222 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001223 if (rc != ::NO_ERROR) {
1224 return rc;
1225 }
1226
1227 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1228 }
1229
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001230 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001231 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001232
Chad Brubaker72593ee2015-05-12 10:42:00 -07001233 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001234 size_t n = prefix.length();
1235
1236 DIR* dir = opendir(userState->getUserDirName());
1237 if (!dir) {
1238 ALOGW("can't open directory for user: %s", strerror(errno));
1239 return ::SYSTEM_ERROR;
1240 }
1241
1242 struct dirent* file;
1243 while ((file = readdir(dir)) != NULL) {
1244 // We only care about files.
1245 if (file->d_type != DT_REG) {
1246 continue;
1247 }
1248
1249 // Skip anything that starts with a "."
1250 if (file->d_name[0] == '.') {
1251 continue;
1252 }
1253
1254 if (!strncmp(prefix.string(), file->d_name, n)) {
1255 const char* p = &file->d_name[n];
1256 size_t plen = strlen(p);
1257
1258 size_t extra = decode_key_length(p, plen);
1259 char *match = (char*) malloc(extra + 1);
1260 if (match != NULL) {
1261 decode_key(match, p, plen);
1262 matches->push(android::String16(match, extra));
1263 free(match);
1264 } else {
1265 ALOGW("could not allocate match of size %zd", extra);
1266 }
1267 }
1268 }
1269 closedir(dir);
1270 return ::NO_ERROR;
1271 }
1272
Kenny Root07438c82012-11-02 15:41:02 -07001273 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001274 const grant_t* existing = getGrant(filename, granteeUid);
1275 if (existing == NULL) {
1276 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001277 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001278 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001279 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001280 }
1281 }
1282
Kenny Root07438c82012-11-02 15:41:02 -07001283 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001284 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1285 it != mGrants.end(); it++) {
1286 grant_t* grant = *it;
1287 if (grant->uid == granteeUid
1288 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1289 mGrants.erase(it);
1290 return true;
1291 }
Kenny Root70e3a862012-02-15 17:20:23 -08001292 }
Kenny Root70e3a862012-02-15 17:20:23 -08001293 return false;
1294 }
1295
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001296 bool hasGrant(const char* filename, const uid_t uid) const {
1297 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001298 }
1299
Chad Brubaker72593ee2015-05-12 10:42:00 -07001300 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001301 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001302 uint8_t* data;
1303 size_t dataLength;
1304 int rc;
1305
1306 if (mDevice->import_keypair == NULL) {
1307 ALOGE("Keymaster doesn't support import!");
1308 return SYSTEM_ERROR;
1309 }
1310
Kenny Root17208e02013-09-04 13:56:03 -07001311 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001312 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001313 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001314 /*
1315 * Maybe the device doesn't support this type of key. Try to use the
1316 * software fallback keymaster implementation. This is a little bit
1317 * lazier than checking the PKCS#8 key type, but the software
1318 * implementation will do that anyway.
1319 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001320 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001321 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001322
1323 if (rc) {
1324 ALOGE("Error while importing keypair: %d", rc);
1325 return SYSTEM_ERROR;
1326 }
Kenny Root822c3a92012-03-23 16:34:39 -07001327 }
1328
1329 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1330 free(data);
1331
Kenny Rootf9119d62013-04-03 09:22:15 -07001332 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001333 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001334
Chad Brubaker72593ee2015-05-12 10:42:00 -07001335 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001336 }
1337
Kenny Root1b0e3932013-09-05 13:06:32 -07001338 bool isHardwareBacked(const android::String16& keyType) const {
1339 if (mDevice == NULL) {
1340 ALOGW("can't get keymaster device");
1341 return false;
1342 }
1343
1344 if (sRSAKeyType == keyType) {
1345 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1346 } else {
1347 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1348 && (mDevice->common.module->module_api_version
1349 >= KEYMASTER_MODULE_API_VERSION_0_2);
1350 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001351 }
1352
Kenny Root655b9582013-04-04 08:37:42 -07001353 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1354 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001355 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001356 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001357
Chad Brubaker72593ee2015-05-12 10:42:00 -07001358 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001359 if (responseCode == NO_ERROR) {
1360 return responseCode;
1361 }
1362
1363 // If this is one of the legacy UID->UID mappings, use it.
1364 uid_t euid = get_keystore_euid(uid);
1365 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001366 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001367 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001368 if (responseCode == NO_ERROR) {
1369 return responseCode;
1370 }
1371 }
1372
1373 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001374 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001375 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001376 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001377 if (end[0] != '_' || end[1] == 0) {
1378 return KEY_NOT_FOUND;
1379 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001380 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001381 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001382 if (!hasGrant(filepath8.string(), uid)) {
1383 return responseCode;
1384 }
1385
1386 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001387 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001388 }
1389
1390 /**
1391 * Returns any existing UserState or creates it if it doesn't exist.
1392 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001393 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001394 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1395 it != mMasterKeys.end(); it++) {
1396 UserState* state = *it;
1397 if (state->getUserId() == userId) {
1398 return state;
1399 }
1400 }
1401
1402 UserState* userState = new UserState(userId);
1403 if (!userState->initialize()) {
1404 /* There's not much we can do if initialization fails. Trying to
1405 * unlock the keystore for that user will fail as well, so any
1406 * subsequent request for this user will just return SYSTEM_ERROR.
1407 */
1408 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1409 }
1410 mMasterKeys.add(userState);
1411 return userState;
1412 }
1413
1414 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001415 * Returns any existing UserState or creates it if it doesn't exist.
1416 */
1417 UserState* getUserStateByUid(uid_t uid) {
1418 uid_t userId = get_user_id(uid);
1419 return getUserState(userId);
1420 }
1421
1422 /**
Kenny Root655b9582013-04-04 08:37:42 -07001423 * Returns NULL if the UserState doesn't already exist.
1424 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001425 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001426 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1427 it != mMasterKeys.end(); it++) {
1428 UserState* state = *it;
1429 if (state->getUserId() == userId) {
1430 return state;
1431 }
1432 }
1433
1434 return NULL;
1435 }
1436
Chad Brubaker72593ee2015-05-12 10:42:00 -07001437 /**
1438 * Returns NULL if the UserState doesn't already exist.
1439 */
1440 const UserState* getUserStateByUid(uid_t uid) const {
1441 uid_t userId = get_user_id(uid);
1442 return getUserState(userId);
1443 }
1444
Kenny Roota91203b2012-02-15 15:00:46 -08001445private:
Kenny Root655b9582013-04-04 08:37:42 -07001446 static const char* sOldMasterKey;
1447 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001448 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001449 Entropy* mEntropy;
1450
Chad Brubaker67d2a502015-03-11 17:21:18 +00001451 keymaster1_device_t* mDevice;
1452 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001453
Kenny Root655b9582013-04-04 08:37:42 -07001454 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001455
Kenny Root655b9582013-04-04 08:37:42 -07001456 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001457
Kenny Root655b9582013-04-04 08:37:42 -07001458 typedef struct {
1459 uint32_t version;
1460 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001461
Kenny Root655b9582013-04-04 08:37:42 -07001462 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001463
Kenny Root655b9582013-04-04 08:37:42 -07001464 const grant_t* getGrant(const char* filename, uid_t uid) const {
1465 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1466 it != mGrants.end(); it++) {
1467 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001468 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001469 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001470 return grant;
1471 }
1472 }
Kenny Root70e3a862012-02-15 17:20:23 -08001473 return NULL;
1474 }
1475
Kenny Root822c3a92012-03-23 16:34:39 -07001476 /**
1477 * Upgrade code. This will upgrade the key from the current version
1478 * to whatever is newest.
1479 */
Kenny Root655b9582013-04-04 08:37:42 -07001480 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1481 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001482 bool updated = false;
1483 uint8_t version = oldVersion;
1484
1485 /* From V0 -> V1: All old types were unknown */
1486 if (version == 0) {
1487 ALOGV("upgrading to version 1 and setting type %d", type);
1488
1489 blob->setType(type);
1490 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001491 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001492 }
1493 version = 1;
1494 updated = true;
1495 }
1496
Kenny Rootf9119d62013-04-03 09:22:15 -07001497 /* From V1 -> V2: All old keys were encrypted */
1498 if (version == 1) {
1499 ALOGV("upgrading to version 2");
1500
1501 blob->setEncrypted(true);
1502 version = 2;
1503 updated = true;
1504 }
1505
Kenny Root822c3a92012-03-23 16:34:39 -07001506 /*
1507 * If we've updated, set the key blob to the right version
1508 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001509 */
Kenny Root822c3a92012-03-23 16:34:39 -07001510 if (updated) {
1511 ALOGV("updated and writing file %s", filename);
1512 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001513 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001514
1515 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001516 }
1517
1518 /**
1519 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1520 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1521 * Then it overwrites the original blob with the new blob
1522 * format that is returned from the keymaster.
1523 */
Kenny Root655b9582013-04-04 08:37:42 -07001524 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001525 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1526 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1527 if (b.get() == NULL) {
1528 ALOGE("Problem instantiating BIO");
1529 return SYSTEM_ERROR;
1530 }
1531
1532 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1533 if (pkey.get() == NULL) {
1534 ALOGE("Couldn't read old PEM file");
1535 return SYSTEM_ERROR;
1536 }
1537
1538 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1539 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1540 if (len < 0) {
1541 ALOGE("Couldn't measure PKCS#8 length");
1542 return SYSTEM_ERROR;
1543 }
1544
Kenny Root70c98892013-02-07 09:10:36 -08001545 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1546 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001547 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1548 ALOGE("Couldn't convert to PKCS#8");
1549 return SYSTEM_ERROR;
1550 }
1551
Chad Brubaker72593ee2015-05-12 10:42:00 -07001552 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001553 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001554 if (rc != NO_ERROR) {
1555 return rc;
1556 }
1557
Kenny Root655b9582013-04-04 08:37:42 -07001558 return get(filename, blob, TYPE_KEY_PAIR, uid);
1559 }
1560
1561 void readMetaData() {
1562 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1563 if (in < 0) {
1564 return;
1565 }
1566 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1567 if (fileLength != sizeof(mMetaData)) {
1568 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1569 sizeof(mMetaData));
1570 }
1571 close(in);
1572 }
1573
1574 void writeMetaData() {
1575 const char* tmpFileName = ".metadata.tmp";
1576 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1577 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1578 if (out < 0) {
1579 ALOGE("couldn't write metadata file: %s", strerror(errno));
1580 return;
1581 }
1582 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1583 if (fileLength != sizeof(mMetaData)) {
1584 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1585 sizeof(mMetaData));
1586 }
1587 close(out);
1588 rename(tmpFileName, sMetaDataFile);
1589 }
1590
1591 bool upgradeKeystore() {
1592 bool upgraded = false;
1593
1594 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001595 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001596
1597 // Initialize first so the directory is made.
1598 userState->initialize();
1599
1600 // Migrate the old .masterkey file to user 0.
1601 if (access(sOldMasterKey, R_OK) == 0) {
1602 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1603 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1604 return false;
1605 }
1606 }
1607
1608 // Initialize again in case we had a key.
1609 userState->initialize();
1610
1611 // Try to migrate existing keys.
1612 DIR* dir = opendir(".");
1613 if (!dir) {
1614 // Give up now; maybe we can upgrade later.
1615 ALOGE("couldn't open keystore's directory; something is wrong");
1616 return false;
1617 }
1618
1619 struct dirent* file;
1620 while ((file = readdir(dir)) != NULL) {
1621 // We only care about files.
1622 if (file->d_type != DT_REG) {
1623 continue;
1624 }
1625
1626 // Skip anything that starts with a "."
1627 if (file->d_name[0] == '.') {
1628 continue;
1629 }
1630
1631 // Find the current file's user.
1632 char* end;
1633 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1634 if (end[0] != '_' || end[1] == 0) {
1635 continue;
1636 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001637 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001638 if (otherUser->getUserId() != 0) {
1639 unlinkat(dirfd(dir), file->d_name, 0);
1640 }
1641
1642 // Rename the file into user directory.
1643 DIR* otherdir = opendir(otherUser->getUserDirName());
1644 if (otherdir == NULL) {
1645 ALOGW("couldn't open user directory for rename");
1646 continue;
1647 }
1648 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1649 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1650 }
1651 closedir(otherdir);
1652 }
1653 closedir(dir);
1654
1655 mMetaData.version = 1;
1656 upgraded = true;
1657 }
1658
1659 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001660 }
Kenny Roota91203b2012-02-15 15:00:46 -08001661};
1662
Kenny Root655b9582013-04-04 08:37:42 -07001663const char* KeyStore::sOldMasterKey = ".masterkey";
1664const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001665
Kenny Root1b0e3932013-09-05 13:06:32 -07001666const android::String16 KeyStore::sRSAKeyType("RSA");
1667
Kenny Root07438c82012-11-02 15:41:02 -07001668namespace android {
1669class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1670public:
1671 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001672 : mKeyStore(keyStore),
1673 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001674 {
Kenny Roota91203b2012-02-15 15:00:46 -08001675 }
Kenny Roota91203b2012-02-15 15:00:46 -08001676
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001677 void binderDied(const wp<IBinder>& who) {
1678 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1679 for (auto token: operations) {
1680 abort(token);
1681 }
Kenny Root822c3a92012-03-23 16:34:39 -07001682 }
Kenny Roota91203b2012-02-15 15:00:46 -08001683
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001684 int32_t getState(int32_t userId) {
1685 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001686 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001687 }
Kenny Roota91203b2012-02-15 15:00:46 -08001688
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001689 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001690 }
1691
Kenny Root07438c82012-11-02 15:41:02 -07001692 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001693 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001694 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001695 }
Kenny Root07438c82012-11-02 15:41:02 -07001696
Chad Brubaker9489b792015-04-14 11:01:45 -07001697 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001698 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001699 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001700
Kenny Root655b9582013-04-04 08:37:42 -07001701 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001702 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001703 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001704 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001705 *item = NULL;
1706 *itemLength = 0;
1707 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001708 }
Kenny Roota91203b2012-02-15 15:00:46 -08001709
Kenny Root07438c82012-11-02 15:41:02 -07001710 *item = (uint8_t*) malloc(keyBlob.getLength());
1711 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1712 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001713
Kenny Root07438c82012-11-02 15:41:02 -07001714 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001715 }
1716
Kenny Rootf9119d62013-04-03 09:22:15 -07001717 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1718 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001719 targetUid = getEffectiveUid(targetUid);
1720 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1721 flags & KEYSTORE_FLAG_ENCRYPTED);
1722 if (result != ::NO_ERROR) {
1723 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001724 }
1725
Kenny Root07438c82012-11-02 15:41:02 -07001726 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001727 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001728
1729 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001730 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1731
Chad Brubaker72593ee2015-05-12 10:42:00 -07001732 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001733 }
1734
Kenny Root49468902013-03-19 13:41:33 -07001735 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001736 targetUid = getEffectiveUid(targetUid);
1737 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001738 return ::PERMISSION_DENIED;
1739 }
Kenny Root07438c82012-11-02 15:41:02 -07001740 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001741 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001742 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001743 }
1744
Kenny Root49468902013-03-19 13:41:33 -07001745 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001746 targetUid = getEffectiveUid(targetUid);
1747 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001748 return ::PERMISSION_DENIED;
1749 }
1750
Kenny Root07438c82012-11-02 15:41:02 -07001751 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001752 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001753
Kenny Root655b9582013-04-04 08:37:42 -07001754 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001755 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1756 }
1757 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001758 }
1759
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001760 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001761 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001762 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001763 return ::PERMISSION_DENIED;
1764 }
Kenny Root07438c82012-11-02 15:41:02 -07001765 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001766 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001767
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001768 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001769 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001770 }
Kenny Root07438c82012-11-02 15:41:02 -07001771 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001772 }
1773
Kenny Root07438c82012-11-02 15:41:02 -07001774 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001775 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001776 return ::PERMISSION_DENIED;
1777 }
1778
Chad Brubaker9489b792015-04-14 11:01:45 -07001779 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001780 mKeyStore->resetUser(get_user_id(callingUid), false);
1781 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001782 }
1783
Chad Brubaker96d6d782015-05-07 10:19:40 -07001784 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001785 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001786 return ::PERMISSION_DENIED;
1787 }
Kenny Root70e3a862012-02-15 17:20:23 -08001788
Kenny Root07438c82012-11-02 15:41:02 -07001789 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001790 // Flush the auth token table to prevent stale tokens from sticking
1791 // around.
1792 mAuthTokenTable.Clear();
1793
1794 if (password.size() == 0) {
1795 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001796 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001797 return ::NO_ERROR;
1798 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001799 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001800 case ::STATE_UNINITIALIZED: {
1801 // generate master key, encrypt with password, write to file,
1802 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001803 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001804 }
1805 case ::STATE_NO_ERROR: {
1806 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001807 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001808 }
1809 case ::STATE_LOCKED: {
1810 ALOGE("Changing user %d's password while locked, clearing old encryption",
1811 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001812 mKeyStore->resetUser(userId, true);
1813 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001814 }
Kenny Root07438c82012-11-02 15:41:02 -07001815 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001816 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001817 }
Kenny Root70e3a862012-02-15 17:20:23 -08001818 }
1819
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001820 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1821 if (!checkBinderPermission(P_USER_CHANGED)) {
1822 return ::PERMISSION_DENIED;
1823 }
1824
1825 // Sanity check that the new user has an empty keystore.
1826 if (!mKeyStore->isEmpty(userId)) {
1827 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1828 }
1829 // Unconditionally clear the keystore, just to be safe.
1830 mKeyStore->resetUser(userId, false);
1831
1832 // If the user has a parent user then use the parent's
1833 // masterkey/password, otherwise there's nothing to do.
1834 if (parentId != -1) {
1835 return mKeyStore->copyMasterKey(parentId, userId);
1836 } else {
1837 return ::NO_ERROR;
1838 }
1839 }
1840
1841 int32_t onUserRemoved(int32_t userId) {
1842 if (!checkBinderPermission(P_USER_CHANGED)) {
1843 return ::PERMISSION_DENIED;
1844 }
1845
1846 mKeyStore->resetUser(userId, false);
1847 return ::NO_ERROR;
1848 }
1849
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001850 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001851 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001852 return ::PERMISSION_DENIED;
1853 }
Kenny Root70e3a862012-02-15 17:20:23 -08001854
Chad Brubaker72593ee2015-05-12 10:42:00 -07001855 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001856 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001857 ALOGD("calling lock in state: %d", state);
1858 return state;
1859 }
1860
Chad Brubaker72593ee2015-05-12 10:42:00 -07001861 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001862 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001863 }
1864
Chad Brubaker96d6d782015-05-07 10:19:40 -07001865 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001866 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001867 return ::PERMISSION_DENIED;
1868 }
1869
Chad Brubaker72593ee2015-05-12 10:42:00 -07001870 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001871 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001872 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001873 return state;
1874 }
1875
1876 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001877 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001878 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001879 }
1880
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001881 bool isEmpty(int32_t userId) {
1882 if (!checkBinderPermission(P_IS_EMPTY)) {
1883 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001884 }
Kenny Root70e3a862012-02-15 17:20:23 -08001885
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001886 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001887 }
1888
Kenny Root96427ba2013-08-16 14:02:41 -07001889 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1890 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001891 targetUid = getEffectiveUid(targetUid);
1892 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1893 flags & KEYSTORE_FLAG_ENCRYPTED);
1894 if (result != ::NO_ERROR) {
1895 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001896 }
Kenny Root07438c82012-11-02 15:41:02 -07001897 uint8_t* data;
1898 size_t dataLength;
1899 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001900 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001901
Chad Brubaker67d2a502015-03-11 17:21:18 +00001902 const keymaster1_device_t* device = mKeyStore->getDevice();
1903 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001904 if (device == NULL) {
1905 return ::SYSTEM_ERROR;
1906 }
1907
1908 if (device->generate_keypair == NULL) {
1909 return ::SYSTEM_ERROR;
1910 }
1911
Kenny Root17208e02013-09-04 13:56:03 -07001912 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001913 keymaster_dsa_keygen_params_t dsa_params;
1914 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001915
Kenny Root96427ba2013-08-16 14:02:41 -07001916 if (keySize == -1) {
1917 keySize = DSA_DEFAULT_KEY_SIZE;
1918 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1919 || keySize > DSA_MAX_KEY_SIZE) {
1920 ALOGI("invalid key size %d", keySize);
1921 return ::SYSTEM_ERROR;
1922 }
1923 dsa_params.key_size = keySize;
1924
1925 if (args->size() == 3) {
1926 sp<KeystoreArg> gArg = args->itemAt(0);
1927 sp<KeystoreArg> pArg = args->itemAt(1);
1928 sp<KeystoreArg> qArg = args->itemAt(2);
1929
1930 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1931 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1932 dsa_params.generator_len = gArg->size();
1933
1934 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1935 dsa_params.prime_p_len = pArg->size();
1936
1937 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1938 dsa_params.prime_q_len = qArg->size();
1939 } else {
1940 ALOGI("not all DSA parameters were read");
1941 return ::SYSTEM_ERROR;
1942 }
1943 } else if (args->size() != 0) {
1944 ALOGI("DSA args must be 3");
1945 return ::SYSTEM_ERROR;
1946 }
1947
Kenny Root1d448c02013-11-21 10:36:53 -08001948 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001949 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1950 } else {
1951 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001952 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1953 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001954 }
1955 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001956 keymaster_ec_keygen_params_t ec_params;
1957 memset(&ec_params, '\0', sizeof(ec_params));
1958
1959 if (keySize == -1) {
1960 keySize = EC_DEFAULT_KEY_SIZE;
1961 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1962 ALOGI("invalid key size %d", keySize);
1963 return ::SYSTEM_ERROR;
1964 }
1965 ec_params.field_size = keySize;
1966
Kenny Root1d448c02013-11-21 10:36:53 -08001967 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001968 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1969 } else {
1970 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001971 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001972 }
Kenny Root96427ba2013-08-16 14:02:41 -07001973 } else if (keyType == EVP_PKEY_RSA) {
1974 keymaster_rsa_keygen_params_t rsa_params;
1975 memset(&rsa_params, '\0', sizeof(rsa_params));
1976 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1977
1978 if (keySize == -1) {
1979 keySize = RSA_DEFAULT_KEY_SIZE;
1980 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1981 ALOGI("invalid key size %d", keySize);
1982 return ::SYSTEM_ERROR;
1983 }
1984 rsa_params.modulus_size = keySize;
1985
1986 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001987 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001988 return ::SYSTEM_ERROR;
1989 } else if (args->size() == 1) {
1990 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1991 if (pubExpBlob != NULL) {
1992 Unique_BIGNUM pubExpBn(
1993 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1994 pubExpBlob->size(), NULL));
1995 if (pubExpBn.get() == NULL) {
1996 ALOGI("Could not convert public exponent to BN");
1997 return ::SYSTEM_ERROR;
1998 }
1999 unsigned long pubExp = BN_get_word(pubExpBn.get());
2000 if (pubExp == 0xFFFFFFFFL) {
2001 ALOGI("cannot represent public exponent as a long value");
2002 return ::SYSTEM_ERROR;
2003 }
2004 rsa_params.public_exponent = pubExp;
2005 }
2006 }
2007
2008 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
2009 } else {
2010 ALOGW("Unsupported key type %d", keyType);
2011 rc = -1;
2012 }
2013
Kenny Root07438c82012-11-02 15:41:02 -07002014 if (rc) {
2015 return ::SYSTEM_ERROR;
2016 }
2017
Kenny Root655b9582013-04-04 08:37:42 -07002018 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07002019 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002020
2021 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2022 free(data);
2023
Kenny Rootee8068b2013-10-07 09:49:15 -07002024 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002025 keyBlob.setFallback(isFallback);
2026
Chad Brubaker72593ee2015-05-12 10:42:00 -07002027 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08002028 }
2029
Kenny Rootf9119d62013-04-03 09:22:15 -07002030 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2031 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002032 targetUid = getEffectiveUid(targetUid);
2033 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2034 flags & KEYSTORE_FLAG_ENCRYPTED);
2035 if (result != ::NO_ERROR) {
2036 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002037 }
Kenny Root07438c82012-11-02 15:41:02 -07002038 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002039 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002040
Chad Brubaker72593ee2015-05-12 10:42:00 -07002041 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2042 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002043 }
2044
Kenny Root07438c82012-11-02 15:41:02 -07002045 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2046 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002047 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002048 return ::PERMISSION_DENIED;
2049 }
Kenny Root07438c82012-11-02 15:41:02 -07002050
Chad Brubaker9489b792015-04-14 11:01:45 -07002051 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002052 Blob keyBlob;
2053 String8 name8(name);
2054
Kenny Rootd38a0b02013-02-13 12:59:14 -08002055 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002056
Kenny Root655b9582013-04-04 08:37:42 -07002057 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002058 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002059 if (responseCode != ::NO_ERROR) {
2060 return responseCode;
2061 }
2062
Chad Brubaker67d2a502015-03-11 17:21:18 +00002063 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002064 if (device == NULL) {
2065 ALOGE("no keymaster device; cannot sign");
2066 return ::SYSTEM_ERROR;
2067 }
2068
2069 if (device->sign_data == NULL) {
2070 ALOGE("device doesn't implement signing");
2071 return ::SYSTEM_ERROR;
2072 }
2073
2074 keymaster_rsa_sign_params_t params;
2075 params.digest_type = DIGEST_NONE;
2076 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002077 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002078 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002079 if (rc) {
2080 ALOGW("device couldn't sign data");
2081 return ::SYSTEM_ERROR;
2082 }
2083
2084 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002085 }
2086
Kenny Root07438c82012-11-02 15:41:02 -07002087 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2088 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002089 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002090 return ::PERMISSION_DENIED;
2091 }
Kenny Root70e3a862012-02-15 17:20:23 -08002092
Chad Brubaker9489b792015-04-14 11:01:45 -07002093 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002094 Blob keyBlob;
2095 String8 name8(name);
2096 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002097
Kenny Root655b9582013-04-04 08:37:42 -07002098 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002099 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002100 if (responseCode != ::NO_ERROR) {
2101 return responseCode;
2102 }
Kenny Root70e3a862012-02-15 17:20:23 -08002103
Chad Brubaker67d2a502015-03-11 17:21:18 +00002104 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002105 if (device == NULL) {
2106 return ::SYSTEM_ERROR;
2107 }
Kenny Root70e3a862012-02-15 17:20:23 -08002108
Kenny Root07438c82012-11-02 15:41:02 -07002109 if (device->verify_data == NULL) {
2110 return ::SYSTEM_ERROR;
2111 }
Kenny Root70e3a862012-02-15 17:20:23 -08002112
Kenny Root07438c82012-11-02 15:41:02 -07002113 keymaster_rsa_sign_params_t params;
2114 params.digest_type = DIGEST_NONE;
2115 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002116
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002117 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2118 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002119 if (rc) {
2120 return ::SYSTEM_ERROR;
2121 } else {
2122 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002123 }
2124 }
Kenny Root07438c82012-11-02 15:41:02 -07002125
2126 /*
2127 * TODO: The abstraction between things stored in hardware and regular blobs
2128 * of data stored on the filesystem should be moved down to keystore itself.
2129 * Unfortunately the Java code that calls this has naming conventions that it
2130 * knows about. Ideally keystore shouldn't be used to store random blobs of
2131 * data.
2132 *
2133 * Until that happens, it's necessary to have a separate "get_pubkey" and
2134 * "del_key" since the Java code doesn't really communicate what it's
2135 * intentions are.
2136 */
2137 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002138 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002139 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002140 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002141 return ::PERMISSION_DENIED;
2142 }
Kenny Root07438c82012-11-02 15:41:02 -07002143
Kenny Root07438c82012-11-02 15:41:02 -07002144 Blob keyBlob;
2145 String8 name8(name);
2146
Kenny Rootd38a0b02013-02-13 12:59:14 -08002147 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002148
Kenny Root655b9582013-04-04 08:37:42 -07002149 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002150 TYPE_KEY_PAIR);
2151 if (responseCode != ::NO_ERROR) {
2152 return responseCode;
2153 }
2154
Chad Brubaker67d2a502015-03-11 17:21:18 +00002155 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002156 if (device == NULL) {
2157 return ::SYSTEM_ERROR;
2158 }
2159
2160 if (device->get_keypair_public == NULL) {
2161 ALOGE("device has no get_keypair_public implementation!");
2162 return ::SYSTEM_ERROR;
2163 }
2164
Kenny Root17208e02013-09-04 13:56:03 -07002165 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002166 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2167 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002168 if (rc) {
2169 return ::SYSTEM_ERROR;
2170 }
2171
2172 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002173 }
Kenny Root07438c82012-11-02 15:41:02 -07002174
Kenny Root07438c82012-11-02 15:41:02 -07002175 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002176 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002177 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2178 if (result != ::NO_ERROR) {
2179 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002180 }
2181
2182 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002183 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002184
Kenny Root655b9582013-04-04 08:37:42 -07002185 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002186 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2187 }
2188
Kenny Root655b9582013-04-04 08:37:42 -07002189 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002190 return ::NO_ERROR;
2191 }
2192
2193 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002194 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002195 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2196 if (result != ::NO_ERROR) {
2197 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002198 }
2199
2200 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002201 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002202
Kenny Root655b9582013-04-04 08:37:42 -07002203 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002204 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2205 }
2206
Kenny Root655b9582013-04-04 08:37:42 -07002207 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002208 }
2209
2210 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002211 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002212 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002213 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002214 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002215 }
Kenny Root07438c82012-11-02 15:41:02 -07002216
2217 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002218 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002219
Kenny Root655b9582013-04-04 08:37:42 -07002220 if (access(filename.string(), R_OK) == -1) {
2221 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002222 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002223 }
2224
Kenny Root655b9582013-04-04 08:37:42 -07002225 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002226 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002227 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002228 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002229 }
2230
2231 struct stat s;
2232 int ret = fstat(fd, &s);
2233 close(fd);
2234 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002235 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002236 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002237 }
2238
Kenny Root36a9e232013-02-04 14:24:15 -08002239 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002240 }
2241
Kenny Rootd53bc922013-03-21 14:10:15 -07002242 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2243 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002244 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002245 pid_t spid = IPCThreadState::self()->getCallingPid();
2246 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002247 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002248 return -1L;
2249 }
2250
Chad Brubaker72593ee2015-05-12 10:42:00 -07002251 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002252 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002253 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002254 return state;
2255 }
2256
Kenny Rootd53bc922013-03-21 14:10:15 -07002257 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2258 srcUid = callingUid;
2259 } else if (!is_granted_to(callingUid, srcUid)) {
2260 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002261 return ::PERMISSION_DENIED;
2262 }
2263
Kenny Rootd53bc922013-03-21 14:10:15 -07002264 if (destUid == -1) {
2265 destUid = callingUid;
2266 }
2267
2268 if (srcUid != destUid) {
2269 if (static_cast<uid_t>(srcUid) != callingUid) {
2270 ALOGD("can only duplicate from caller to other or to same uid: "
2271 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2272 return ::PERMISSION_DENIED;
2273 }
2274
2275 if (!is_granted_to(callingUid, destUid)) {
2276 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2277 return ::PERMISSION_DENIED;
2278 }
2279 }
2280
2281 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002282 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002283
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002285 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002286
Kenny Root655b9582013-04-04 08:37:42 -07002287 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2288 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002289 return ::SYSTEM_ERROR;
2290 }
2291
Kenny Rootd53bc922013-03-21 14:10:15 -07002292 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002293 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002294 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002295 if (responseCode != ::NO_ERROR) {
2296 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002297 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002298
Chad Brubaker72593ee2015-05-12 10:42:00 -07002299 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002300 }
2301
Kenny Root1b0e3932013-09-05 13:06:32 -07002302 int32_t is_hardware_backed(const String16& keyType) {
2303 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002304 }
2305
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002306 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002307 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002308 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002309 return ::PERMISSION_DENIED;
2310 }
2311
Robin Lee4b84fdc2014-09-24 11:56:57 +01002312 String8 prefix = String8::format("%u_", targetUid);
2313 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002314 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002315 return ::SYSTEM_ERROR;
2316 }
2317
Robin Lee4b84fdc2014-09-24 11:56:57 +01002318 for (uint32_t i = 0; i < aliases.size(); i++) {
2319 String8 name8(aliases[i]);
2320 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002321 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002322 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002323 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002324 }
2325
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002326 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2327 const keymaster1_device_t* device = mKeyStore->getDevice();
2328 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2329 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2330 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2331 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2332 device->add_rng_entropy != NULL) {
2333 devResult = device->add_rng_entropy(device, data, dataLength);
2334 }
2335 if (fallback->add_rng_entropy) {
2336 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2337 }
2338 if (devResult) {
2339 return devResult;
2340 }
2341 if (fallbackResult) {
2342 return fallbackResult;
2343 }
2344 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002345 }
2346
Chad Brubaker17d68b92015-02-05 22:04:16 -08002347 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002348 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2349 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002350 uid = getEffectiveUid(uid);
2351 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2352 flags & KEYSTORE_FLAG_ENCRYPTED);
2353 if (rc != ::NO_ERROR) {
2354 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002355 }
2356
Chad Brubaker9489b792015-04-14 11:01:45 -07002357 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002358 bool isFallback = false;
2359 keymaster_key_blob_t blob;
2360 keymaster_key_characteristics_t *out = NULL;
2361
2362 const keymaster1_device_t* device = mKeyStore->getDevice();
2363 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2364 if (device == NULL) {
2365 return ::SYSTEM_ERROR;
2366 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002367 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002368 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2369 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002370 if (!entropy) {
2371 rc = KM_ERROR_OK;
2372 } else if (device->add_rng_entropy) {
2373 rc = device->add_rng_entropy(device, entropy, entropyLength);
2374 } else {
2375 rc = KM_ERROR_UNIMPLEMENTED;
2376 }
2377 if (rc == KM_ERROR_OK) {
2378 rc = device->generate_key(device, params.params.data(), params.params.size(),
2379 &blob, &out);
2380 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002381 }
2382 // If the HW device didn't support generate_key or generate_key failed
2383 // fall back to the software implementation.
2384 if (rc && fallback->generate_key != NULL) {
2385 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002386 if (!entropy) {
2387 rc = KM_ERROR_OK;
2388 } else if (fallback->add_rng_entropy) {
2389 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2390 } else {
2391 rc = KM_ERROR_UNIMPLEMENTED;
2392 }
2393 if (rc == KM_ERROR_OK) {
2394 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2395 &blob,
2396 &out);
2397 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002398 }
2399
2400 if (out) {
2401 if (outCharacteristics) {
2402 outCharacteristics->characteristics = *out;
2403 } else {
2404 keymaster_free_characteristics(out);
2405 }
2406 free(out);
2407 }
2408
2409 if (rc) {
2410 return rc;
2411 }
2412
2413 String8 name8(name);
2414 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2415
2416 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2417 keyBlob.setFallback(isFallback);
2418 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2419
2420 free(const_cast<uint8_t*>(blob.key_material));
2421
Chad Brubaker72593ee2015-05-12 10:42:00 -07002422 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002423 }
2424
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002425 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002426 const keymaster_blob_t* clientId,
2427 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002428 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002429 if (!outCharacteristics) {
2430 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2431 }
2432
2433 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2434
2435 Blob keyBlob;
2436 String8 name8(name);
2437 int rc;
2438
2439 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2440 TYPE_KEYMASTER_10);
2441 if (responseCode != ::NO_ERROR) {
2442 return responseCode;
2443 }
2444 keymaster_key_blob_t key;
2445 key.key_material_size = keyBlob.getLength();
2446 key.key_material = keyBlob.getValue();
2447 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2448 keymaster_key_characteristics_t *out = NULL;
2449 if (!dev->get_key_characteristics) {
2450 ALOGW("device does not implement get_key_characteristics");
2451 return KM_ERROR_UNIMPLEMENTED;
2452 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002453 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002454 if (out) {
2455 outCharacteristics->characteristics = *out;
2456 free(out);
2457 }
2458 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002459 }
2460
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002461 int32_t importKey(const String16& name, const KeymasterArguments& params,
2462 keymaster_key_format_t format, const uint8_t *keyData,
2463 size_t keyLength, int uid, int flags,
2464 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002465 uid = getEffectiveUid(uid);
2466 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2467 flags & KEYSTORE_FLAG_ENCRYPTED);
2468 if (rc != ::NO_ERROR) {
2469 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002470 }
2471
Chad Brubaker9489b792015-04-14 11:01:45 -07002472 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002473 bool isFallback = false;
2474 keymaster_key_blob_t blob;
2475 keymaster_key_characteristics_t *out = NULL;
2476
2477 const keymaster1_device_t* device = mKeyStore->getDevice();
2478 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2479 if (device == NULL) {
2480 return ::SYSTEM_ERROR;
2481 }
2482 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2483 device->import_key != NULL) {
2484 rc = device->import_key(device, params.params.data(), params.params.size(),
2485 format, keyData, keyLength, &blob, &out);
2486 }
2487 if (rc && fallback->import_key != NULL) {
2488 isFallback = true;
2489 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2490 format, keyData, keyLength, &blob, &out);
2491 }
2492 if (out) {
2493 if (outCharacteristics) {
2494 outCharacteristics->characteristics = *out;
2495 } else {
2496 keymaster_free_characteristics(out);
2497 }
2498 free(out);
2499 }
2500 if (rc) {
2501 return rc;
2502 }
2503
2504 String8 name8(name);
2505 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2506
2507 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2508 keyBlob.setFallback(isFallback);
2509 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2510
2511 free((void*) blob.key_material);
2512
Chad Brubaker72593ee2015-05-12 10:42:00 -07002513 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002514 }
2515
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002516 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002517 const keymaster_blob_t* clientId,
2518 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002519
2520 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2521
2522 Blob keyBlob;
2523 String8 name8(name);
2524 int rc;
2525
2526 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2527 TYPE_KEYMASTER_10);
2528 if (responseCode != ::NO_ERROR) {
2529 result->resultCode = responseCode;
2530 return;
2531 }
2532 keymaster_key_blob_t key;
2533 key.key_material_size = keyBlob.getLength();
2534 key.key_material = keyBlob.getValue();
2535 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2536 if (!dev->export_key) {
2537 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2538 return;
2539 }
2540 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002541 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002542 &ptr, &result->dataLength);
2543 result->exportData.reset(ptr);
2544 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002545 }
2546
Chad Brubakerad6514a2015-04-09 14:00:26 -07002547
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002548 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002549 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2550 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002551 if (!result || !outParams) {
2552 ALOGE("Unexpected null arguments to begin()");
2553 return;
2554 }
2555 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2556 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2557 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2558 result->resultCode = ::PERMISSION_DENIED;
2559 return;
2560 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002561 if (!checkAllowedOperationParams(params.params)) {
2562 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2563 return;
2564 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002565 Blob keyBlob;
2566 String8 name8(name);
2567 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2568 TYPE_KEYMASTER_10);
2569 if (responseCode != ::NO_ERROR) {
2570 result->resultCode = responseCode;
2571 return;
2572 }
2573 keymaster_key_blob_t key;
2574 key.key_material_size = keyBlob.getLength();
2575 key.key_material = keyBlob.getValue();
2576 keymaster_key_param_t* out;
2577 size_t outSize;
2578 keymaster_operation_handle_t handle;
2579 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002580 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002581 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002582 Unique_keymaster_key_characteristics characteristics;
2583 characteristics.reset(new keymaster_key_characteristics_t);
2584 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2585 if (err) {
2586 result->resultCode = err;
2587 return;
2588 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002589 const hw_auth_token_t* authToken = NULL;
2590 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002591 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002592 // If per-operation auth is needed we need to begin the operation and
2593 // the client will need to authorize that operation before calling
2594 // update. Any other auth issues stop here.
2595 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2596 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002597 return;
2598 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002599 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002600 // Add entropy to the device first.
2601 if (entropy) {
2602 if (dev->add_rng_entropy) {
2603 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2604 } else {
2605 err = KM_ERROR_UNIMPLEMENTED;
2606 }
2607 if (err) {
2608 result->resultCode = err;
2609 return;
2610 }
2611 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002612 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2613 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002614
2615 // If there are too many operations abort the oldest operation that was
2616 // started as pruneable and try again.
2617 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2618 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2619 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2620 if (abort(oldest) != ::NO_ERROR) {
2621 break;
2622 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002623 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002624 &handle);
2625 }
2626 if (err) {
2627 result->resultCode = err;
2628 return;
2629 }
2630 if (out) {
2631 outParams->params.assign(out, out + outSize);
2632 free(out);
2633 }
2634
Chad Brubakerad6514a2015-04-09 14:00:26 -07002635 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2636 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002637 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002638 if (authToken) {
2639 mOperationMap.setOperationAuthToken(operationToken, authToken);
2640 }
2641 // Return the authentication lookup result. If this is a per operation
2642 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2643 // application should get an auth token using the handle before the
2644 // first call to update, which will fail if keystore hasn't received the
2645 // auth token.
2646 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002647 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002648 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002649 }
2650
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002651 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2652 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002653 if (!checkAllowedOperationParams(params.params)) {
2654 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2655 return;
2656 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002657 const keymaster1_device_t* dev;
2658 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002659 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002660 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2661 return;
2662 }
2663 uint8_t* output_buf = NULL;
2664 size_t output_length = 0;
2665 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002666 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002667 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2668 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002669 result->resultCode = authResult;
2670 return;
2671 }
2672 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2673 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002674 result->data.reset(output_buf);
2675 result->dataLength = output_length;
2676 result->inputConsumed = consumed;
2677 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002678 }
2679
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002680 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2681 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002682 if (!checkAllowedOperationParams(params.params)) {
2683 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2684 return;
2685 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002686 const keymaster1_device_t* dev;
2687 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002688 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002689 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2690 return;
2691 }
2692 uint8_t* output_buf = NULL;
2693 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002694 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002695 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2696 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002697 result->resultCode = authResult;
2698 return;
2699 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002700
Chad Brubaker06801e02015-03-31 15:13:13 -07002701 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2702 signature, signatureLength, &output_buf,
2703 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002704 // Remove the operation regardless of the result
2705 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002706 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002707 result->data.reset(output_buf);
2708 result->dataLength = output_length;
2709 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002710 }
2711
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002712 int32_t abort(const sp<IBinder>& token) {
2713 const keymaster1_device_t* dev;
2714 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002715 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002716 return KM_ERROR_INVALID_OPERATION_HANDLE;
2717 }
2718 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002719 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002720 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002721 rc = KM_ERROR_UNIMPLEMENTED;
2722 } else {
2723 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002724 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002725 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002726 if (rc) {
2727 return rc;
2728 }
2729 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002730 }
2731
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002732 bool isOperationAuthorized(const sp<IBinder>& token) {
2733 const keymaster1_device_t* dev;
2734 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002735 const keymaster_key_characteristics_t* characteristics;
2736 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002737 return false;
2738 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002739 const hw_auth_token_t* authToken = NULL;
2740 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002741 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002742 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2743 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002744 }
2745
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002746 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002747 if (!checkBinderPermission(P_ADD_AUTH)) {
2748 ALOGW("addAuthToken: permission denied for %d",
2749 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002750 return ::PERMISSION_DENIED;
2751 }
2752 if (length != sizeof(hw_auth_token_t)) {
2753 return KM_ERROR_INVALID_ARGUMENT;
2754 }
2755 hw_auth_token_t* authToken = new hw_auth_token_t;
2756 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2757 // The table takes ownership of authToken.
2758 mAuthTokenTable.AddAuthenticationToken(authToken);
2759 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002760 }
2761
Kenny Root07438c82012-11-02 15:41:02 -07002762private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002763 static const int32_t UID_SELF = -1;
2764
2765 /**
2766 * Get the effective target uid for a binder operation that takes an
2767 * optional uid as the target.
2768 */
2769 inline uid_t getEffectiveUid(int32_t targetUid) {
2770 if (targetUid == UID_SELF) {
2771 return IPCThreadState::self()->getCallingUid();
2772 }
2773 return static_cast<uid_t>(targetUid);
2774 }
2775
2776 /**
2777 * Check if the caller of the current binder method has the required
2778 * permission and if acting on other uids the grants to do so.
2779 */
2780 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2781 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2782 pid_t spid = IPCThreadState::self()->getCallingPid();
2783 if (!has_permission(callingUid, permission, spid)) {
2784 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2785 return false;
2786 }
2787 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2788 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2789 return false;
2790 }
2791 return true;
2792 }
2793
2794 /**
2795 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002796 * permission and the target uid is the caller or the caller is system.
2797 */
2798 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2799 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2800 pid_t spid = IPCThreadState::self()->getCallingPid();
2801 if (!has_permission(callingUid, permission, spid)) {
2802 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2803 return false;
2804 }
2805 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2806 }
2807
2808 /**
2809 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002810 * permission or the target of the operation is the caller's uid. This is
2811 * for operation where the permission is only for cross-uid activity and all
2812 * uids are allowed to act on their own (ie: clearing all entries for a
2813 * given uid).
2814 */
2815 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2816 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2817 if (getEffectiveUid(targetUid) == callingUid) {
2818 return true;
2819 } else {
2820 return checkBinderPermission(permission, targetUid);
2821 }
2822 }
2823
2824 /**
2825 * Helper method to check that the caller has the required permission as
2826 * well as the keystore is in the unlocked state if checkUnlocked is true.
2827 *
2828 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2829 * otherwise the state of keystore when not unlocked and checkUnlocked is
2830 * true.
2831 */
2832 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2833 bool checkUnlocked = true) {
2834 if (!checkBinderPermission(permission, targetUid)) {
2835 return ::PERMISSION_DENIED;
2836 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002837 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002838 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2839 return state;
2840 }
2841
2842 return ::NO_ERROR;
2843
2844 }
2845
Kenny Root9d45d1c2013-02-14 10:32:30 -08002846 inline bool isKeystoreUnlocked(State state) {
2847 switch (state) {
2848 case ::STATE_NO_ERROR:
2849 return true;
2850 case ::STATE_UNINITIALIZED:
2851 case ::STATE_LOCKED:
2852 return false;
2853 }
2854 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002855 }
2856
Chad Brubaker67d2a502015-03-11 17:21:18 +00002857 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002858 const int32_t device_api = device->common.module->module_api_version;
2859 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2860 switch (keyType) {
2861 case TYPE_RSA:
2862 case TYPE_DSA:
2863 case TYPE_EC:
2864 return true;
2865 default:
2866 return false;
2867 }
2868 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2869 switch (keyType) {
2870 case TYPE_RSA:
2871 return true;
2872 case TYPE_DSA:
2873 return device->flags & KEYMASTER_SUPPORTS_DSA;
2874 case TYPE_EC:
2875 return device->flags & KEYMASTER_SUPPORTS_EC;
2876 default:
2877 return false;
2878 }
2879 } else {
2880 return keyType == TYPE_RSA;
2881 }
2882 }
2883
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002884 /**
2885 * Check that all keymaster_key_param_t's provided by the application are
2886 * allowed. Any parameter that keystore adds itself should be disallowed here.
2887 */
2888 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2889 for (auto param: params) {
2890 switch (param.tag) {
2891 case KM_TAG_AUTH_TOKEN:
2892 return false;
2893 default:
2894 break;
2895 }
2896 }
2897 return true;
2898 }
2899
2900 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2901 const keymaster1_device_t* dev,
2902 const std::vector<keymaster_key_param_t>& params,
2903 keymaster_key_characteristics_t* out) {
2904 UniquePtr<keymaster_blob_t> appId;
2905 UniquePtr<keymaster_blob_t> appData;
2906 for (auto param : params) {
2907 if (param.tag == KM_TAG_APPLICATION_ID) {
2908 appId.reset(new keymaster_blob_t);
2909 appId->data = param.blob.data;
2910 appId->data_length = param.blob.data_length;
2911 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2912 appData.reset(new keymaster_blob_t);
2913 appData->data = param.blob.data;
2914 appData->data_length = param.blob.data_length;
2915 }
2916 }
2917 keymaster_key_characteristics_t* result = NULL;
2918 if (!dev->get_key_characteristics) {
2919 return KM_ERROR_UNIMPLEMENTED;
2920 }
2921 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2922 appData.get(), &result);
2923 if (result) {
2924 *out = *result;
2925 free(result);
2926 }
2927 return error;
2928 }
2929
2930 /**
2931 * Get the auth token for this operation from the auth token table.
2932 *
2933 * Returns ::NO_ERROR if the auth token was set or none was required.
2934 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2935 * authorization token exists for that operation and
2936 * failOnTokenMissing is false.
2937 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2938 * token for the operation
2939 */
2940 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2941 keymaster_operation_handle_t handle,
2942 const hw_auth_token_t** authToken,
2943 bool failOnTokenMissing = true) {
2944
2945 std::vector<keymaster_key_param_t> allCharacteristics;
2946 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2947 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2948 }
2949 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2950 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2951 }
2952 keymaster::AuthTokenTable::Error err =
2953 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2954 allCharacteristics.size(), handle, authToken);
2955 switch (err) {
2956 case keymaster::AuthTokenTable::OK:
2957 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2958 return ::NO_ERROR;
2959 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2960 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2961 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2962 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2963 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2964 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2965 (int32_t) ::OP_AUTH_NEEDED;
2966 default:
2967 ALOGE("Unexpected FindAuthorization return value %d", err);
2968 return KM_ERROR_INVALID_ARGUMENT;
2969 }
2970 }
2971
2972 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2973 const hw_auth_token_t* token) {
2974 if (token) {
2975 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2976 reinterpret_cast<const uint8_t*>(token),
2977 sizeof(hw_auth_token_t)));
2978 }
2979 }
2980
2981 /**
2982 * Add the auth token for the operation to the param list if the operation
2983 * requires authorization. Uses the cached result in the OperationMap if available
2984 * otherwise gets the token from the AuthTokenTable and caches the result.
2985 *
2986 * Returns ::NO_ERROR if the auth token was added or not needed.
2987 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2988 * authenticated.
2989 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2990 * operation token.
2991 */
2992 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2993 std::vector<keymaster_key_param_t>* params) {
2994 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002995 mOperationMap.getOperationAuthToken(token, &authToken);
2996 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002997 const keymaster1_device_t* dev;
2998 keymaster_operation_handle_t handle;
2999 const keymaster_key_characteristics_t* characteristics = NULL;
3000 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3001 return KM_ERROR_INVALID_OPERATION_HANDLE;
3002 }
3003 int32_t result = getAuthToken(characteristics, handle, &authToken);
3004 if (result != ::NO_ERROR) {
3005 return result;
3006 }
3007 if (authToken) {
3008 mOperationMap.setOperationAuthToken(token, authToken);
3009 }
3010 }
3011 addAuthToParams(params, authToken);
3012 return ::NO_ERROR;
3013 }
3014
Kenny Root07438c82012-11-02 15:41:02 -07003015 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003016 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003017 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003018};
3019
3020}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003021
3022int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003023 if (argc < 2) {
3024 ALOGE("A directory must be specified!");
3025 return 1;
3026 }
3027 if (chdir(argv[1]) == -1) {
3028 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3029 return 1;
3030 }
3031
3032 Entropy entropy;
3033 if (!entropy.open()) {
3034 return 1;
3035 }
Kenny Root70e3a862012-02-15 17:20:23 -08003036
Chad Brubakerbd07a232015-06-01 10:44:27 -07003037 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003038 if (keymaster_device_initialize(&dev)) {
3039 ALOGE("keystore keymaster could not be initialized; exiting");
3040 return 1;
3041 }
3042
Chad Brubaker67d2a502015-03-11 17:21:18 +00003043 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003044 if (fallback_keymaster_device_initialize(&fallback)) {
3045 ALOGE("software keymaster could not be initialized; exiting");
3046 return 1;
3047 }
3048
Riley Spahneaabae92014-06-30 12:39:52 -07003049 ks_is_selinux_enabled = is_selinux_enabled();
3050 if (ks_is_selinux_enabled) {
3051 union selinux_callback cb;
3052 cb.func_log = selinux_log_callback;
3053 selinux_set_callback(SELINUX_CB_LOG, cb);
3054 if (getcon(&tctx) != 0) {
3055 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3056 return -1;
3057 }
3058 } else {
3059 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3060 }
3061
Chad Brubakerbd07a232015-06-01 10:44:27 -07003062 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003063 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003064 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3065 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3066 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3067 if (ret != android::OK) {
3068 ALOGE("Couldn't register binder service!");
3069 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003070 }
Kenny Root07438c82012-11-02 15:41:02 -07003071
3072 /*
3073 * We're the only thread in existence, so we're just going to process
3074 * Binder transaction as a single-threaded program.
3075 */
3076 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003077
3078 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003079 return 1;
3080}