blob: 4b4d45614ba56453a3fe3a6f72bfdf2dd70d8e9a [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 Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Kenny Root17208e02013-09-04 13:56:03 -070046#include <keymaster/softkeymaster.h>
Chad Brubaker919cb2a2015-02-05 21:58:25 -080047#include <keymaster/soft_keymaster_device.h>
Kenny Root17208e02013-09-04 13:56:03 -070048
Kenny Root26cfc082013-09-11 14:38:56 -070049#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070050#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080052
Kenny Root07438c82012-11-02 15:41:02 -070053#include <keystore/IKeystoreService.h>
54#include <binder/IPCThreadState.h>
55#include <binder/IServiceManager.h>
56
Kenny Roota91203b2012-02-15 15:00:46 -080057#include <cutils/log.h>
58#include <cutils/sockets.h>
59#include <private/android_filesystem_config.h>
60
Kenny Root07438c82012-11-02 15:41:02 -070061#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080062
Riley Spahneaabae92014-06-30 12:39:52 -070063#include <selinux/android.h>
64
Chad Brubakerd80c7b42015-03-31 11:04:28 -070065#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070066#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080067#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070068
Kenny Roota91203b2012-02-15 15:00:46 -080069/* KeyStore is a secured storage for key-value pairs. In this implementation,
70 * each file stores one key-value pair. Keys are encoded in file names, and
71 * values are encrypted with checksums. The encryption key is protected by a
72 * user-defined password. To keep things simple, buffers are always larger than
73 * the maximum space we needed, so boundary checks on buffers are omitted. */
74
75#define KEY_SIZE ((NAME_MAX - 15) / 2)
76#define VALUE_SIZE 32768
77#define PASSWORD_SIZE VALUE_SIZE
78
Kenny Root822c3a92012-03-23 16:34:39 -070079
Kenny Root96427ba2013-08-16 14:02:41 -070080struct BIGNUM_Delete {
81 void operator()(BIGNUM* p) const {
82 BN_free(p);
83 }
84};
85typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
86
Kenny Root822c3a92012-03-23 16:34:39 -070087struct BIO_Delete {
88 void operator()(BIO* p) const {
89 BIO_free(p);
90 }
91};
92typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
93
94struct EVP_PKEY_Delete {
95 void operator()(EVP_PKEY* p) const {
96 EVP_PKEY_free(p);
97 }
98};
99typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
100
101struct PKCS8_PRIV_KEY_INFO_Delete {
102 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
103 PKCS8_PRIV_KEY_INFO_free(p);
104 }
105};
106typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
107
108
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800133static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
134 keymaster::SoftKeymasterDevice* softkeymaster =
135 new keymaster::SoftKeymasterDevice();
136 // SoftKeymasterDevice is designed to make this cast safe.
137 *dev = reinterpret_cast<keymaster1_device_t*>(softkeymaster);
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800138 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800139}
140
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700141static void keymaster_device_release(keymaster0_device_t* dev) {
142 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800143}
144
Kenny Root07438c82012-11-02 15:41:02 -0700145/***************
146 * PERMISSIONS *
147 ***************/
148
149/* Here are the permissions, actions, users, and the main function. */
150typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100151 P_TEST = 1 << 0,
152 P_GET = 1 << 1,
153 P_INSERT = 1 << 2,
154 P_DELETE = 1 << 3,
155 P_EXIST = 1 << 4,
156 P_SAW = 1 << 5,
157 P_RESET = 1 << 6,
158 P_PASSWORD = 1 << 7,
159 P_LOCK = 1 << 8,
160 P_UNLOCK = 1 << 9,
161 P_ZERO = 1 << 10,
162 P_SIGN = 1 << 11,
163 P_VERIFY = 1 << 12,
164 P_GRANT = 1 << 13,
165 P_DUPLICATE = 1 << 14,
166 P_CLEAR_UID = 1 << 15,
167 P_RESET_UID = 1 << 16,
168 P_SYNC_UID = 1 << 17,
169 P_PASSWORD_UID = 1 << 18,
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700170 P_ADD_AUTH = 1 << 19,
Kenny Root07438c82012-11-02 15:41:02 -0700171} perm_t;
172
173static struct user_euid {
174 uid_t uid;
175 uid_t euid;
176} user_euids[] = {
177 {AID_VPN, AID_SYSTEM},
178 {AID_WIFI, AID_SYSTEM},
179 {AID_ROOT, AID_SYSTEM},
180};
181
Riley Spahneaabae92014-06-30 12:39:52 -0700182/* perm_labels associcated with keystore_key SELinux class verbs. */
183const char *perm_labels[] = {
184 "test",
185 "get",
186 "insert",
187 "delete",
188 "exist",
189 "saw",
190 "reset",
191 "password",
192 "lock",
193 "unlock",
194 "zero",
195 "sign",
196 "verify",
197 "grant",
198 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100199 "clear_uid",
200 "reset_uid",
201 "sync_uid",
202 "password_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700203 "add_auth",
Riley Spahneaabae92014-06-30 12:39:52 -0700204};
205
Kenny Root07438c82012-11-02 15:41:02 -0700206static struct user_perm {
207 uid_t uid;
208 perm_t perms;
209} user_perms[] = {
210 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
211 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
212 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
213 {AID_ROOT, static_cast<perm_t>(P_GET) },
214};
215
216static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
217 | P_VERIFY);
218
Riley Spahneaabae92014-06-30 12:39:52 -0700219static char *tctx;
220static int ks_is_selinux_enabled;
221
222static const char *get_perm_label(perm_t perm) {
223 unsigned int index = ffs(perm);
224 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
225 return perm_labels[index - 1];
226 } else {
227 ALOGE("Keystore: Failed to retrieve permission label.\n");
228 abort();
229 }
230}
231
Kenny Root655b9582013-04-04 08:37:42 -0700232/**
233 * Returns the app ID (in the Android multi-user sense) for the current
234 * UNIX UID.
235 */
236static uid_t get_app_id(uid_t uid) {
237 return uid % AID_USER;
238}
239
240/**
241 * Returns the user ID (in the Android multi-user sense) for the current
242 * UNIX UID.
243 */
244static uid_t get_user_id(uid_t uid) {
245 return uid / AID_USER;
246}
247
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700248static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700249 if (!ks_is_selinux_enabled) {
250 return true;
251 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000252
Riley Spahneaabae92014-06-30 12:39:52 -0700253 char *sctx = NULL;
254 const char *selinux_class = "keystore_key";
255 const char *str_perm = get_perm_label(perm);
256
257 if (!str_perm) {
258 return false;
259 }
260
261 if (getpidcon(spid, &sctx) != 0) {
262 ALOGE("SELinux: Failed to get source pid context.\n");
263 return false;
264 }
265
266 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
267 NULL) == 0;
268 freecon(sctx);
269 return allowed;
270}
271
272static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700273 // All system users are equivalent for multi-user support.
274 if (get_app_id(uid) == AID_SYSTEM) {
275 uid = AID_SYSTEM;
276 }
277
Kenny Root07438c82012-11-02 15:41:02 -0700278 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
279 struct user_perm user = user_perms[i];
280 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700281 return (user.perms & perm) &&
282 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700283 }
284 }
285
Riley Spahneaabae92014-06-30 12:39:52 -0700286 return (DEFAULT_PERMS & perm) &&
287 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700288}
289
Kenny Root49468902013-03-19 13:41:33 -0700290/**
291 * Returns the UID that the callingUid should act as. This is here for
292 * legacy support of the WiFi and VPN systems and should be removed
293 * when WiFi can operate in its own namespace.
294 */
Kenny Root07438c82012-11-02 15:41:02 -0700295static uid_t get_keystore_euid(uid_t uid) {
296 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
297 struct user_euid user = user_euids[i];
298 if (user.uid == uid) {
299 return user.euid;
300 }
301 }
302
303 return uid;
304}
305
Kenny Root49468902013-03-19 13:41:33 -0700306/**
307 * Returns true if the callingUid is allowed to interact in the targetUid's
308 * namespace.
309 */
310static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
311 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
312 struct user_euid user = user_euids[i];
313 if (user.euid == callingUid && user.uid == targetUid) {
314 return true;
315 }
316 }
317
318 return false;
319}
320
Kenny Root007cb232014-07-30 16:59:42 -0700321/**
322 * Allow the system to perform some privileged tasks that have to do with
323 * system maintenance. This should not be used for any function that uses
324 * the keys in any way (e.g., signing).
325 */
326static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
327 return callingUid == targetUid || callingUid == AID_SYSTEM;
328}
329
Kenny Roota91203b2012-02-15 15:00:46 -0800330/* Here is the encoding of keys. This is necessary in order to allow arbitrary
331 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
332 * into two bytes. The first byte is one of [+-.] which represents the first
333 * two bits of the character. The second byte encodes the rest of the bits into
334 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
335 * that Base64 cannot be used here due to the need of prefix match on keys. */
336
Kenny Root655b9582013-04-04 08:37:42 -0700337static size_t encode_key_length(const android::String8& keyName) {
338 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
339 size_t length = keyName.length();
340 for (int i = length; i > 0; --i, ++in) {
341 if (*in < '0' || *in > '~') {
342 ++length;
343 }
344 }
345 return length;
346}
347
Kenny Root07438c82012-11-02 15:41:02 -0700348static int encode_key(char* out, const android::String8& keyName) {
349 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
350 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800351 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700352 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800353 *out = '+' + (*in >> 6);
354 *++out = '0' + (*in & 0x3F);
355 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700356 } else {
357 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800358 }
359 }
360 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800361 return length;
362}
363
Kenny Root07438c82012-11-02 15:41:02 -0700364/*
365 * Converts from the "escaped" format on disk to actual name.
366 * This will be smaller than the input string.
367 *
368 * Characters that should combine with the next at the end will be truncated.
369 */
370static size_t decode_key_length(const char* in, size_t length) {
371 size_t outLength = 0;
372
373 for (const char* end = in + length; in < end; in++) {
374 /* This combines with the next character. */
375 if (*in < '0' || *in > '~') {
376 continue;
377 }
378
379 outLength++;
380 }
381 return outLength;
382}
383
384static void decode_key(char* out, const char* in, size_t length) {
385 for (const char* end = in + length; in < end; in++) {
386 if (*in < '0' || *in > '~') {
387 /* Truncate combining characters at the end. */
388 if (in + 1 >= end) {
389 break;
390 }
391
392 *out = (*in++ - '+') << 6;
393 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800394 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700395 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800396 }
397 }
398 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800399}
400
401static size_t readFully(int fd, uint8_t* data, size_t size) {
402 size_t remaining = size;
403 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800404 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800405 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800406 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800407 }
408 data += n;
409 remaining -= n;
410 }
411 return size;
412}
413
414static size_t writeFully(int fd, uint8_t* data, size_t size) {
415 size_t remaining = size;
416 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800417 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
418 if (n < 0) {
419 ALOGW("write failed: %s", strerror(errno));
420 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800421 }
422 data += n;
423 remaining -= n;
424 }
425 return size;
426}
427
428class Entropy {
429public:
430 Entropy() : mRandom(-1) {}
431 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800432 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800433 close(mRandom);
434 }
435 }
436
437 bool open() {
438 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800439 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
440 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800441 ALOGE("open: %s: %s", randomDevice, strerror(errno));
442 return false;
443 }
444 return true;
445 }
446
Kenny Root51878182012-03-13 12:53:19 -0700447 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800448 return (readFully(mRandom, data, size) == size);
449 }
450
451private:
452 int mRandom;
453};
454
455/* Here is the file format. There are two parts in blob.value, the secret and
456 * the description. The secret is stored in ciphertext, and its original size
457 * can be found in blob.length. The description is stored after the secret in
458 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700459 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700460 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800461 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
462 * and decryptBlob(). Thus they should not be accessed from outside. */
463
Kenny Root822c3a92012-03-23 16:34:39 -0700464/* ** Note to future implementors of encryption: **
465 * Currently this is the construction:
466 * metadata || Enc(MD5(data) || data)
467 *
468 * This should be the construction used for encrypting if re-implementing:
469 *
470 * Derive independent keys for encryption and MAC:
471 * Kenc = AES_encrypt(masterKey, "Encrypt")
472 * Kmac = AES_encrypt(masterKey, "MAC")
473 *
474 * Store this:
475 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
476 * HMAC(Kmac, metadata || Enc(data))
477 */
Kenny Roota91203b2012-02-15 15:00:46 -0800478struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700479 uint8_t version;
480 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700481 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800482 uint8_t info;
483 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700484 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800485 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700486 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800487 int32_t length; // in network byte order when encrypted
488 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
489};
490
Kenny Root822c3a92012-03-23 16:34:39 -0700491typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700492 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700493 TYPE_GENERIC = 1,
494 TYPE_MASTER_KEY = 2,
495 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800496 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700497} BlobType;
498
Kenny Rootf9119d62013-04-03 09:22:15 -0700499static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700500
Kenny Roota91203b2012-02-15 15:00:46 -0800501class Blob {
502public:
Kenny Root07438c82012-11-02 15:41:02 -0700503 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
504 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800505 mBlob.length = valueLength;
506 memcpy(mBlob.value, value, valueLength);
507
508 mBlob.info = infoLength;
509 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700510
Kenny Root07438c82012-11-02 15:41:02 -0700511 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700512 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700513
Kenny Rootee8068b2013-10-07 09:49:15 -0700514 if (type == TYPE_MASTER_KEY) {
515 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
516 } else {
517 mBlob.flags = KEYSTORE_FLAG_NONE;
518 }
Kenny Roota91203b2012-02-15 15:00:46 -0800519 }
520
521 Blob(blob b) {
522 mBlob = b;
523 }
524
525 Blob() {}
526
Kenny Root51878182012-03-13 12:53:19 -0700527 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800528 return mBlob.value;
529 }
530
Kenny Root51878182012-03-13 12:53:19 -0700531 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800532 return mBlob.length;
533 }
534
Kenny Root51878182012-03-13 12:53:19 -0700535 const uint8_t* getInfo() const {
536 return mBlob.value + mBlob.length;
537 }
538
539 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800540 return mBlob.info;
541 }
542
Kenny Root822c3a92012-03-23 16:34:39 -0700543 uint8_t getVersion() const {
544 return mBlob.version;
545 }
546
Kenny Rootf9119d62013-04-03 09:22:15 -0700547 bool isEncrypted() const {
548 if (mBlob.version < 2) {
549 return true;
550 }
551
552 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
553 }
554
555 void setEncrypted(bool encrypted) {
556 if (encrypted) {
557 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
558 } else {
559 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
560 }
561 }
562
Kenny Root17208e02013-09-04 13:56:03 -0700563 bool isFallback() const {
564 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
565 }
566
567 void setFallback(bool fallback) {
568 if (fallback) {
569 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
570 } else {
571 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
572 }
573 }
574
Kenny Root822c3a92012-03-23 16:34:39 -0700575 void setVersion(uint8_t version) {
576 mBlob.version = version;
577 }
578
579 BlobType getType() const {
580 return BlobType(mBlob.type);
581 }
582
583 void setType(BlobType type) {
584 mBlob.type = uint8_t(type);
585 }
586
Kenny Rootf9119d62013-04-03 09:22:15 -0700587 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
588 ALOGV("writing blob %s", filename);
589 if (isEncrypted()) {
590 if (state != STATE_NO_ERROR) {
591 ALOGD("couldn't insert encrypted blob while not unlocked");
592 return LOCKED;
593 }
594
595 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
596 ALOGW("Could not read random data for: %s", filename);
597 return SYSTEM_ERROR;
598 }
Kenny Roota91203b2012-02-15 15:00:46 -0800599 }
600
601 // data includes the value and the value's length
602 size_t dataLength = mBlob.length + sizeof(mBlob.length);
603 // pad data to the AES_BLOCK_SIZE
604 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
605 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
606 // encrypted data includes the digest value
607 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
608 // move info after space for padding
609 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
610 // zero padding area
611 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
612
613 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800614
Kenny Rootf9119d62013-04-03 09:22:15 -0700615 if (isEncrypted()) {
616 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800617
Kenny Rootf9119d62013-04-03 09:22:15 -0700618 uint8_t vector[AES_BLOCK_SIZE];
619 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
620 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
621 aes_key, vector, AES_ENCRYPT);
622 }
623
Kenny Roota91203b2012-02-15 15:00:46 -0800624 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
625 size_t fileLength = encryptedLength + headerLength + mBlob.info;
626
627 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800628 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
629 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
630 if (out < 0) {
631 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800632 return SYSTEM_ERROR;
633 }
634 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
635 if (close(out) != 0) {
636 return SYSTEM_ERROR;
637 }
638 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800639 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800640 unlink(tmpFileName);
641 return SYSTEM_ERROR;
642 }
Kenny Root150ca932012-11-14 14:29:02 -0800643 if (rename(tmpFileName, filename) == -1) {
644 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
645 return SYSTEM_ERROR;
646 }
647 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800648 }
649
Kenny Rootf9119d62013-04-03 09:22:15 -0700650 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
651 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800652 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
653 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800654 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
655 }
656 // fileLength may be less than sizeof(mBlob) since the in
657 // memory version has extra padding to tolerate rounding up to
658 // the AES_BLOCK_SIZE
659 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
660 if (close(in) != 0) {
661 return SYSTEM_ERROR;
662 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700663
664 if (isEncrypted() && (state != STATE_NO_ERROR)) {
665 return LOCKED;
666 }
667
Kenny Roota91203b2012-02-15 15:00:46 -0800668 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
669 if (fileLength < headerLength) {
670 return VALUE_CORRUPTED;
671 }
672
673 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700674 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800675 return VALUE_CORRUPTED;
676 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700677
678 ssize_t digestedLength;
679 if (isEncrypted()) {
680 if (encryptedLength % AES_BLOCK_SIZE != 0) {
681 return VALUE_CORRUPTED;
682 }
683
684 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
685 mBlob.vector, AES_DECRYPT);
686 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
687 uint8_t computedDigest[MD5_DIGEST_LENGTH];
688 MD5(mBlob.digested, digestedLength, computedDigest);
689 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
690 return VALUE_CORRUPTED;
691 }
692 } else {
693 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800694 }
695
696 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
697 mBlob.length = ntohl(mBlob.length);
698 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
699 return VALUE_CORRUPTED;
700 }
701 if (mBlob.info != 0) {
702 // move info from after padding to after data
703 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
704 }
Kenny Root07438c82012-11-02 15:41:02 -0700705 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800706 }
707
708private:
709 struct blob mBlob;
710};
711
Kenny Root655b9582013-04-04 08:37:42 -0700712class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800713public:
Kenny Root655b9582013-04-04 08:37:42 -0700714 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
715 asprintf(&mUserDir, "user_%u", mUserId);
716 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
717 }
718
719 ~UserState() {
720 free(mUserDir);
721 free(mMasterKeyFile);
722 }
723
724 bool initialize() {
725 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
726 ALOGE("Could not create directory '%s'", mUserDir);
727 return false;
728 }
729
730 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800731 setState(STATE_LOCKED);
732 } else {
733 setState(STATE_UNINITIALIZED);
734 }
Kenny Root70e3a862012-02-15 17:20:23 -0800735
Kenny Root655b9582013-04-04 08:37:42 -0700736 return true;
737 }
738
739 uid_t getUserId() const {
740 return mUserId;
741 }
742
743 const char* getUserDirName() const {
744 return mUserDir;
745 }
746
747 const char* getMasterKeyFileName() const {
748 return mMasterKeyFile;
749 }
750
751 void setState(State state) {
752 mState = state;
753 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
754 mRetry = MAX_RETRY;
755 }
Kenny Roota91203b2012-02-15 15:00:46 -0800756 }
757
Kenny Root51878182012-03-13 12:53:19 -0700758 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800759 return mState;
760 }
761
Kenny Root51878182012-03-13 12:53:19 -0700762 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800763 return mRetry;
764 }
765
Kenny Root655b9582013-04-04 08:37:42 -0700766 void zeroizeMasterKeysInMemory() {
767 memset(mMasterKey, 0, sizeof(mMasterKey));
768 memset(mSalt, 0, sizeof(mSalt));
769 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
770 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800771 }
772
Kenny Root655b9582013-04-04 08:37:42 -0700773 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
774 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800775 return SYSTEM_ERROR;
776 }
Kenny Root655b9582013-04-04 08:37:42 -0700777 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800778 if (response != NO_ERROR) {
779 return response;
780 }
781 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700782 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800783 }
784
Robin Lee4e865752014-08-19 17:37:55 +0100785 ResponseCode copyMasterKey(UserState* src) {
786 if (mState != STATE_UNINITIALIZED) {
787 return ::SYSTEM_ERROR;
788 }
789 if (src->getState() != STATE_NO_ERROR) {
790 return ::SYSTEM_ERROR;
791 }
792 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
793 setupMasterKeys();
794 return ::NO_ERROR;
795 }
796
Kenny Root655b9582013-04-04 08:37:42 -0700797 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800798 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
799 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
800 AES_KEY passwordAesKey;
801 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700802 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700803 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800804 }
805
Kenny Root655b9582013-04-04 08:37:42 -0700806 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
807 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800808 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800809 return SYSTEM_ERROR;
810 }
811
812 // we read the raw blob to just to get the salt to generate
813 // the AES key, then we create the Blob to use with decryptBlob
814 blob rawBlob;
815 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
816 if (close(in) != 0) {
817 return SYSTEM_ERROR;
818 }
819 // find salt at EOF if present, otherwise we have an old file
820 uint8_t* salt;
821 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
822 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
823 } else {
824 salt = NULL;
825 }
826 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
827 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
828 AES_KEY passwordAesKey;
829 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
830 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700831 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
832 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800833 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700834 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800835 }
836 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
837 // if salt was missing, generate one and write a new master key file with the salt.
838 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700839 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800840 return SYSTEM_ERROR;
841 }
Kenny Root655b9582013-04-04 08:37:42 -0700842 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800843 }
844 if (response == NO_ERROR) {
845 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
846 setupMasterKeys();
847 }
848 return response;
849 }
850 if (mRetry <= 0) {
851 reset();
852 return UNINITIALIZED;
853 }
854 --mRetry;
855 switch (mRetry) {
856 case 0: return WRONG_PASSWORD_0;
857 case 1: return WRONG_PASSWORD_1;
858 case 2: return WRONG_PASSWORD_2;
859 case 3: return WRONG_PASSWORD_3;
860 default: return WRONG_PASSWORD_3;
861 }
862 }
863
Kenny Root655b9582013-04-04 08:37:42 -0700864 AES_KEY* getEncryptionKey() {
865 return &mMasterKeyEncryption;
866 }
867
868 AES_KEY* getDecryptionKey() {
869 return &mMasterKeyDecryption;
870 }
871
Kenny Roota91203b2012-02-15 15:00:46 -0800872 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700873 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800874 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700875 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800876 return false;
877 }
Kenny Root655b9582013-04-04 08:37:42 -0700878
879 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800880 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700881 // We only care about files.
882 if (file->d_type != DT_REG) {
883 continue;
884 }
885
886 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700887 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700888 continue;
889 }
890
891 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800892 }
893 closedir(dir);
894 return true;
895 }
896
Kenny Root655b9582013-04-04 08:37:42 -0700897private:
898 static const int MASTER_KEY_SIZE_BYTES = 16;
899 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
900
901 static const int MAX_RETRY = 4;
902 static const size_t SALT_SIZE = 16;
903
904 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
905 uint8_t* salt) {
906 size_t saltSize;
907 if (salt != NULL) {
908 saltSize = SALT_SIZE;
909 } else {
910 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
911 salt = (uint8_t*) "keystore";
912 // sizeof = 9, not strlen = 8
913 saltSize = sizeof("keystore");
914 }
915
916 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
917 saltSize, 8192, keySize, key);
918 }
919
920 bool generateSalt(Entropy* entropy) {
921 return entropy->generate_random_data(mSalt, sizeof(mSalt));
922 }
923
924 bool generateMasterKey(Entropy* entropy) {
925 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
926 return false;
927 }
928 if (!generateSalt(entropy)) {
929 return false;
930 }
931 return true;
932 }
933
934 void setupMasterKeys() {
935 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
936 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
937 setState(STATE_NO_ERROR);
938 }
939
940 uid_t mUserId;
941
942 char* mUserDir;
943 char* mMasterKeyFile;
944
945 State mState;
946 int8_t mRetry;
947
948 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
949 uint8_t mSalt[SALT_SIZE];
950
951 AES_KEY mMasterKeyEncryption;
952 AES_KEY mMasterKeyDecryption;
953};
954
955typedef struct {
956 uint32_t uid;
957 const uint8_t* filename;
958} grant_t;
959
960class KeyStore {
961public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800962 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700963 : mEntropy(entropy)
964 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800965 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700966 {
967 memset(&mMetaData, '\0', sizeof(mMetaData));
968 }
969
970 ~KeyStore() {
971 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
972 it != mGrants.end(); it++) {
973 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700974 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800975 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700976
977 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
978 it != mMasterKeys.end(); it++) {
979 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700980 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800981 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700982 }
983
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800984 /**
985 * Depending on the hardware keymaster version is this may return a
986 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
987 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
988 * be guarded by a check on the device's version.
989 */
990 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700991 return mDevice;
992 }
993
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800994 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800995 return mFallbackDevice;
996 }
997
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800998 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800999 return blob.isFallback() ? mFallbackDevice: mDevice;
1000 }
1001
Kenny Root655b9582013-04-04 08:37:42 -07001002 ResponseCode initialize() {
1003 readMetaData();
1004 if (upgradeKeystore()) {
1005 writeMetaData();
1006 }
1007
1008 return ::NO_ERROR;
1009 }
1010
1011 State getState(uid_t uid) {
1012 return getUserState(uid)->getState();
1013 }
1014
1015 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1016 UserState* userState = getUserState(uid);
1017 return userState->initialize(pw, mEntropy);
1018 }
1019
Robin Lee4e865752014-08-19 17:37:55 +01001020 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1021 UserState *userState = getUserState(uid);
1022 UserState *initState = getUserState(src);
1023 return userState->copyMasterKey(initState);
1024 }
1025
Kenny Root655b9582013-04-04 08:37:42 -07001026 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001027 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001028 return userState->writeMasterKey(pw, mEntropy);
1029 }
1030
1031 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001032 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001033 return userState->readMasterKey(pw, mEntropy);
1034 }
1035
1036 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001037 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001038 encode_key(encoded, keyName);
1039 return android::String8(encoded);
1040 }
1041
1042 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001043 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001044 encode_key(encoded, keyName);
1045 return android::String8::format("%u_%s", uid, encoded);
1046 }
1047
1048 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001049 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001050 encode_key(encoded, keyName);
1051 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1052 encoded);
1053 }
1054
1055 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001056 android::String8 prefix("");
1057 android::Vector<android::String16> aliases;
1058 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1059 return ::SYSTEM_ERROR;
1060 }
1061
Kenny Root655b9582013-04-04 08:37:42 -07001062 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001063 for (uint32_t i = 0; i < aliases.size(); i++) {
1064 android::String8 filename(aliases[i]);
1065 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1066 getKeyName(filename).string());
1067 del(filename, ::TYPE_ANY, uid);
1068 }
1069
Kenny Root655b9582013-04-04 08:37:42 -07001070 userState->zeroizeMasterKeysInMemory();
1071 userState->setState(STATE_UNINITIALIZED);
1072 return userState->reset();
1073 }
1074
1075 bool isEmpty(uid_t uid) const {
1076 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001077 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001078 return true;
1079 }
1080
1081 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001082 if (!dir) {
1083 return true;
1084 }
Kenny Root31e27462014-09-10 11:28:03 -07001085
Kenny Roota91203b2012-02-15 15:00:46 -08001086 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001087 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001088 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001089 // We only care about files.
1090 if (file->d_type != DT_REG) {
1091 continue;
1092 }
1093
1094 // Skip anything that starts with a "."
1095 if (file->d_name[0] == '.') {
1096 continue;
1097 }
1098
Kenny Root31e27462014-09-10 11:28:03 -07001099 result = false;
1100 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001101 }
1102 closedir(dir);
1103 return result;
1104 }
1105
Kenny Root655b9582013-04-04 08:37:42 -07001106 void lock(uid_t uid) {
1107 UserState* userState = getUserState(uid);
1108 userState->zeroizeMasterKeysInMemory();
1109 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001110 }
1111
Kenny Root655b9582013-04-04 08:37:42 -07001112 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1113 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001114 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1115 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001116 if (rc != NO_ERROR) {
1117 return rc;
1118 }
1119
1120 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001121 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001122 /* If we upgrade the key, we need to write it to disk again. Then
1123 * it must be read it again since the blob is encrypted each time
1124 * it's written.
1125 */
Kenny Root655b9582013-04-04 08:37:42 -07001126 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1127 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001128 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1129 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001130 return rc;
1131 }
1132 }
Kenny Root822c3a92012-03-23 16:34:39 -07001133 }
1134
Kenny Root17208e02013-09-04 13:56:03 -07001135 /*
1136 * This will upgrade software-backed keys to hardware-backed keys when
1137 * the HAL for the device supports the newer key types.
1138 */
1139 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1140 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1141 && keyBlob->isFallback()) {
1142 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1143 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1144
1145 // The HAL allowed the import, reget the key to have the "fresh"
1146 // version.
1147 if (imported == NO_ERROR) {
1148 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1149 }
1150 }
1151
Kenny Rootd53bc922013-03-21 14:10:15 -07001152 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001153 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1154 return KEY_NOT_FOUND;
1155 }
1156
1157 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001158 }
1159
Kenny Root655b9582013-04-04 08:37:42 -07001160 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1161 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001162 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1163 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001164 }
1165
Robin Lee4b84fdc2014-09-24 11:56:57 +01001166 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1167 Blob keyBlob;
1168 ResponseCode rc = get(filename, &keyBlob, type, uid);
1169 if (rc != ::NO_ERROR) {
1170 return rc;
1171 }
1172
1173 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1174 // A device doesn't have to implement delete_keypair.
1175 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1176 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1177 rc = ::SYSTEM_ERROR;
1178 }
1179 }
1180 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001181 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1182 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1183 if (dev->delete_key) {
1184 keymaster_key_blob_t blob;
1185 blob.key_material = keyBlob.getValue();
1186 blob.key_material_size = keyBlob.getLength();
1187 dev->delete_key(dev, &blob);
1188 }
1189 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001190 if (rc != ::NO_ERROR) {
1191 return rc;
1192 }
1193
1194 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1195 }
1196
1197 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1198 uid_t uid) {
1199
1200 UserState* userState = getUserState(uid);
1201 size_t n = prefix.length();
1202
1203 DIR* dir = opendir(userState->getUserDirName());
1204 if (!dir) {
1205 ALOGW("can't open directory for user: %s", strerror(errno));
1206 return ::SYSTEM_ERROR;
1207 }
1208
1209 struct dirent* file;
1210 while ((file = readdir(dir)) != NULL) {
1211 // We only care about files.
1212 if (file->d_type != DT_REG) {
1213 continue;
1214 }
1215
1216 // Skip anything that starts with a "."
1217 if (file->d_name[0] == '.') {
1218 continue;
1219 }
1220
1221 if (!strncmp(prefix.string(), file->d_name, n)) {
1222 const char* p = &file->d_name[n];
1223 size_t plen = strlen(p);
1224
1225 size_t extra = decode_key_length(p, plen);
1226 char *match = (char*) malloc(extra + 1);
1227 if (match != NULL) {
1228 decode_key(match, p, plen);
1229 matches->push(android::String16(match, extra));
1230 free(match);
1231 } else {
1232 ALOGW("could not allocate match of size %zd", extra);
1233 }
1234 }
1235 }
1236 closedir(dir);
1237 return ::NO_ERROR;
1238 }
1239
Kenny Root07438c82012-11-02 15:41:02 -07001240 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001241 const grant_t* existing = getGrant(filename, granteeUid);
1242 if (existing == NULL) {
1243 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001244 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001245 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001246 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001247 }
1248 }
1249
Kenny Root07438c82012-11-02 15:41:02 -07001250 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001251 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1252 it != mGrants.end(); it++) {
1253 grant_t* grant = *it;
1254 if (grant->uid == granteeUid
1255 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1256 mGrants.erase(it);
1257 return true;
1258 }
Kenny Root70e3a862012-02-15 17:20:23 -08001259 }
Kenny Root70e3a862012-02-15 17:20:23 -08001260 return false;
1261 }
1262
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001263 bool hasGrant(const char* filename, const uid_t uid) const {
1264 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001265 }
1266
Kenny Rootf9119d62013-04-03 09:22:15 -07001267 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1268 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001269 uint8_t* data;
1270 size_t dataLength;
1271 int rc;
1272
1273 if (mDevice->import_keypair == NULL) {
1274 ALOGE("Keymaster doesn't support import!");
1275 return SYSTEM_ERROR;
1276 }
1277
Kenny Root17208e02013-09-04 13:56:03 -07001278 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001279 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001280 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001281 /*
1282 * Maybe the device doesn't support this type of key. Try to use the
1283 * software fallback keymaster implementation. This is a little bit
1284 * lazier than checking the PKCS#8 key type, but the software
1285 * implementation will do that anyway.
1286 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001287 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001288 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001289
1290 if (rc) {
1291 ALOGE("Error while importing keypair: %d", rc);
1292 return SYSTEM_ERROR;
1293 }
Kenny Root822c3a92012-03-23 16:34:39 -07001294 }
1295
1296 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1297 free(data);
1298
Kenny Rootf9119d62013-04-03 09:22:15 -07001299 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001300 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001301
Kenny Root655b9582013-04-04 08:37:42 -07001302 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001303 }
1304
Kenny Root1b0e3932013-09-05 13:06:32 -07001305 bool isHardwareBacked(const android::String16& keyType) const {
1306 if (mDevice == NULL) {
1307 ALOGW("can't get keymaster device");
1308 return false;
1309 }
1310
1311 if (sRSAKeyType == keyType) {
1312 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1313 } else {
1314 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1315 && (mDevice->common.module->module_api_version
1316 >= KEYMASTER_MODULE_API_VERSION_0_2);
1317 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001318 }
1319
Kenny Root655b9582013-04-04 08:37:42 -07001320 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1321 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001322 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001323
1324 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1325 if (responseCode == NO_ERROR) {
1326 return responseCode;
1327 }
1328
1329 // If this is one of the legacy UID->UID mappings, use it.
1330 uid_t euid = get_keystore_euid(uid);
1331 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001332 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001333 responseCode = get(filepath8.string(), keyBlob, type, uid);
1334 if (responseCode == NO_ERROR) {
1335 return responseCode;
1336 }
1337 }
1338
1339 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001340 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001341 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001342 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001343 if (end[0] != '_' || end[1] == 0) {
1344 return KEY_NOT_FOUND;
1345 }
Kenny Root86b16e82013-09-09 11:15:54 -07001346 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1347 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001348 if (!hasGrant(filepath8.string(), uid)) {
1349 return responseCode;
1350 }
1351
1352 // It is a granted key. Try to load it.
1353 return get(filepath8.string(), keyBlob, type, uid);
1354 }
1355
1356 /**
1357 * Returns any existing UserState or creates it if it doesn't exist.
1358 */
1359 UserState* getUserState(uid_t uid) {
1360 uid_t userId = get_user_id(uid);
1361
1362 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1363 it != mMasterKeys.end(); it++) {
1364 UserState* state = *it;
1365 if (state->getUserId() == userId) {
1366 return state;
1367 }
1368 }
1369
1370 UserState* userState = new UserState(userId);
1371 if (!userState->initialize()) {
1372 /* There's not much we can do if initialization fails. Trying to
1373 * unlock the keystore for that user will fail as well, so any
1374 * subsequent request for this user will just return SYSTEM_ERROR.
1375 */
1376 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1377 }
1378 mMasterKeys.add(userState);
1379 return userState;
1380 }
1381
1382 /**
1383 * Returns NULL if the UserState doesn't already exist.
1384 */
1385 const UserState* getUserState(uid_t uid) const {
1386 uid_t userId = get_user_id(uid);
1387
1388 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1389 it != mMasterKeys.end(); it++) {
1390 UserState* state = *it;
1391 if (state->getUserId() == userId) {
1392 return state;
1393 }
1394 }
1395
1396 return NULL;
1397 }
1398
Kenny Roota91203b2012-02-15 15:00:46 -08001399private:
Kenny Root655b9582013-04-04 08:37:42 -07001400 static const char* sOldMasterKey;
1401 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001402 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001403 Entropy* mEntropy;
1404
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001405 keymaster1_device_t* mDevice;
1406 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001407
Kenny Root655b9582013-04-04 08:37:42 -07001408 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001409
Kenny Root655b9582013-04-04 08:37:42 -07001410 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001411
Kenny Root655b9582013-04-04 08:37:42 -07001412 typedef struct {
1413 uint32_t version;
1414 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001415
Kenny Root655b9582013-04-04 08:37:42 -07001416 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001417
Kenny Root655b9582013-04-04 08:37:42 -07001418 const grant_t* getGrant(const char* filename, uid_t uid) const {
1419 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1420 it != mGrants.end(); it++) {
1421 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001422 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001423 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001424 return grant;
1425 }
1426 }
Kenny Root70e3a862012-02-15 17:20:23 -08001427 return NULL;
1428 }
1429
Kenny Root822c3a92012-03-23 16:34:39 -07001430 /**
1431 * Upgrade code. This will upgrade the key from the current version
1432 * to whatever is newest.
1433 */
Kenny Root655b9582013-04-04 08:37:42 -07001434 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1435 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001436 bool updated = false;
1437 uint8_t version = oldVersion;
1438
1439 /* From V0 -> V1: All old types were unknown */
1440 if (version == 0) {
1441 ALOGV("upgrading to version 1 and setting type %d", type);
1442
1443 blob->setType(type);
1444 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001445 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001446 }
1447 version = 1;
1448 updated = true;
1449 }
1450
Kenny Rootf9119d62013-04-03 09:22:15 -07001451 /* From V1 -> V2: All old keys were encrypted */
1452 if (version == 1) {
1453 ALOGV("upgrading to version 2");
1454
1455 blob->setEncrypted(true);
1456 version = 2;
1457 updated = true;
1458 }
1459
Kenny Root822c3a92012-03-23 16:34:39 -07001460 /*
1461 * If we've updated, set the key blob to the right version
1462 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001463 */
Kenny Root822c3a92012-03-23 16:34:39 -07001464 if (updated) {
1465 ALOGV("updated and writing file %s", filename);
1466 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001467 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001468
1469 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001470 }
1471
1472 /**
1473 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1474 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1475 * Then it overwrites the original blob with the new blob
1476 * format that is returned from the keymaster.
1477 */
Kenny Root655b9582013-04-04 08:37:42 -07001478 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001479 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1480 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1481 if (b.get() == NULL) {
1482 ALOGE("Problem instantiating BIO");
1483 return SYSTEM_ERROR;
1484 }
1485
1486 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1487 if (pkey.get() == NULL) {
1488 ALOGE("Couldn't read old PEM file");
1489 return SYSTEM_ERROR;
1490 }
1491
1492 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1493 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1494 if (len < 0) {
1495 ALOGE("Couldn't measure PKCS#8 length");
1496 return SYSTEM_ERROR;
1497 }
1498
Kenny Root70c98892013-02-07 09:10:36 -08001499 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1500 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001501 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1502 ALOGE("Couldn't convert to PKCS#8");
1503 return SYSTEM_ERROR;
1504 }
1505
Kenny Rootf9119d62013-04-03 09:22:15 -07001506 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1507 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001508 if (rc != NO_ERROR) {
1509 return rc;
1510 }
1511
Kenny Root655b9582013-04-04 08:37:42 -07001512 return get(filename, blob, TYPE_KEY_PAIR, uid);
1513 }
1514
1515 void readMetaData() {
1516 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1517 if (in < 0) {
1518 return;
1519 }
1520 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1521 if (fileLength != sizeof(mMetaData)) {
1522 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1523 sizeof(mMetaData));
1524 }
1525 close(in);
1526 }
1527
1528 void writeMetaData() {
1529 const char* tmpFileName = ".metadata.tmp";
1530 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1531 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1532 if (out < 0) {
1533 ALOGE("couldn't write metadata file: %s", strerror(errno));
1534 return;
1535 }
1536 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1537 if (fileLength != sizeof(mMetaData)) {
1538 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1539 sizeof(mMetaData));
1540 }
1541 close(out);
1542 rename(tmpFileName, sMetaDataFile);
1543 }
1544
1545 bool upgradeKeystore() {
1546 bool upgraded = false;
1547
1548 if (mMetaData.version == 0) {
1549 UserState* userState = getUserState(0);
1550
1551 // Initialize first so the directory is made.
1552 userState->initialize();
1553
1554 // Migrate the old .masterkey file to user 0.
1555 if (access(sOldMasterKey, R_OK) == 0) {
1556 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1557 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1558 return false;
1559 }
1560 }
1561
1562 // Initialize again in case we had a key.
1563 userState->initialize();
1564
1565 // Try to migrate existing keys.
1566 DIR* dir = opendir(".");
1567 if (!dir) {
1568 // Give up now; maybe we can upgrade later.
1569 ALOGE("couldn't open keystore's directory; something is wrong");
1570 return false;
1571 }
1572
1573 struct dirent* file;
1574 while ((file = readdir(dir)) != NULL) {
1575 // We only care about files.
1576 if (file->d_type != DT_REG) {
1577 continue;
1578 }
1579
1580 // Skip anything that starts with a "."
1581 if (file->d_name[0] == '.') {
1582 continue;
1583 }
1584
1585 // Find the current file's user.
1586 char* end;
1587 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1588 if (end[0] != '_' || end[1] == 0) {
1589 continue;
1590 }
1591 UserState* otherUser = getUserState(thisUid);
1592 if (otherUser->getUserId() != 0) {
1593 unlinkat(dirfd(dir), file->d_name, 0);
1594 }
1595
1596 // Rename the file into user directory.
1597 DIR* otherdir = opendir(otherUser->getUserDirName());
1598 if (otherdir == NULL) {
1599 ALOGW("couldn't open user directory for rename");
1600 continue;
1601 }
1602 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1603 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1604 }
1605 closedir(otherdir);
1606 }
1607 closedir(dir);
1608
1609 mMetaData.version = 1;
1610 upgraded = true;
1611 }
1612
1613 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001614 }
Kenny Roota91203b2012-02-15 15:00:46 -08001615};
1616
Kenny Root655b9582013-04-04 08:37:42 -07001617const char* KeyStore::sOldMasterKey = ".masterkey";
1618const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001619
Kenny Root1b0e3932013-09-05 13:06:32 -07001620const android::String16 KeyStore::sRSAKeyType("RSA");
1621
Kenny Root07438c82012-11-02 15:41:02 -07001622namespace android {
1623class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1624public:
1625 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001626 : mKeyStore(keyStore),
1627 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001628 {
Kenny Roota91203b2012-02-15 15:00:46 -08001629 }
Kenny Roota91203b2012-02-15 15:00:46 -08001630
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001631 void binderDied(const wp<IBinder>& who) {
1632 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1633 for (auto token: operations) {
1634 abort(token);
1635 }
Kenny Root822c3a92012-03-23 16:34:39 -07001636 }
Kenny Roota91203b2012-02-15 15:00:46 -08001637
Kenny Root07438c82012-11-02 15:41:02 -07001638 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001639 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001640 pid_t spid = IPCThreadState::self()->getCallingPid();
1641 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001642 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001643 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001644 }
Kenny Roota91203b2012-02-15 15:00:46 -08001645
Kenny Root655b9582013-04-04 08:37:42 -07001646 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001647 }
1648
Kenny Root07438c82012-11-02 15:41:02 -07001649 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001650 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001651 pid_t spid = IPCThreadState::self()->getCallingPid();
1652 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001653 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001654 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001655 }
Kenny Root07438c82012-11-02 15:41:02 -07001656
Kenny Root07438c82012-11-02 15:41:02 -07001657 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001658 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001659
Kenny Root655b9582013-04-04 08:37:42 -07001660 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001661 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001662 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001663 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001664 *item = NULL;
1665 *itemLength = 0;
1666 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001667 }
Kenny Roota91203b2012-02-15 15:00:46 -08001668
Kenny Root07438c82012-11-02 15:41:02 -07001669 *item = (uint8_t*) malloc(keyBlob.getLength());
1670 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1671 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001672
Kenny Root07438c82012-11-02 15:41:02 -07001673 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001674 }
1675
Kenny Rootf9119d62013-04-03 09:22:15 -07001676 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1677 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001678 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001679 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001680 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001681 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001682 return ::PERMISSION_DENIED;
1683 }
Kenny Root07438c82012-11-02 15:41:02 -07001684
Kenny Rootf9119d62013-04-03 09:22:15 -07001685 State state = mKeyStore->getState(callingUid);
1686 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1687 ALOGD("calling get in state: %d", state);
1688 return state;
1689 }
1690
Kenny Root49468902013-03-19 13:41:33 -07001691 if (targetUid == -1) {
1692 targetUid = callingUid;
1693 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001694 return ::PERMISSION_DENIED;
1695 }
1696
Kenny Root07438c82012-11-02 15:41:02 -07001697 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001698 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001699
1700 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001701 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1702
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001703 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001704 }
1705
Kenny Root49468902013-03-19 13:41:33 -07001706 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001707 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001708 pid_t spid = IPCThreadState::self()->getCallingPid();
1709 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001710 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001711 return ::PERMISSION_DENIED;
1712 }
Kenny Root70e3a862012-02-15 17:20:23 -08001713
Kenny Root49468902013-03-19 13:41:33 -07001714 if (targetUid == -1) {
1715 targetUid = callingUid;
1716 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001717 return ::PERMISSION_DENIED;
1718 }
1719
Kenny Root07438c82012-11-02 15:41:02 -07001720 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001721 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001722 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001723 }
1724
Kenny Root49468902013-03-19 13:41:33 -07001725 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001726 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001727 pid_t spid = IPCThreadState::self()->getCallingPid();
1728 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001729 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001730 return ::PERMISSION_DENIED;
1731 }
Kenny Root70e3a862012-02-15 17:20:23 -08001732
Kenny Root49468902013-03-19 13:41:33 -07001733 if (targetUid == -1) {
1734 targetUid = callingUid;
1735 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001736 return ::PERMISSION_DENIED;
1737 }
1738
Kenny Root07438c82012-11-02 15:41:02 -07001739 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001740 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001741
Kenny Root655b9582013-04-04 08:37:42 -07001742 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001743 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1744 }
1745 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001746 }
1747
Kenny Root49468902013-03-19 13:41:33 -07001748 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001749 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001750 pid_t spid = IPCThreadState::self()->getCallingPid();
1751 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001752 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001753 return ::PERMISSION_DENIED;
1754 }
Kenny Root70e3a862012-02-15 17:20:23 -08001755
Kenny Root49468902013-03-19 13:41:33 -07001756 if (targetUid == -1) {
1757 targetUid = callingUid;
1758 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001759 return ::PERMISSION_DENIED;
1760 }
1761
Kenny Root07438c82012-11-02 15:41:02 -07001762 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001763 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001764
Robin Lee4b84fdc2014-09-24 11:56:57 +01001765 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1766 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001767 }
Kenny Root07438c82012-11-02 15:41:02 -07001768 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001769 }
1770
Kenny Root07438c82012-11-02 15:41:02 -07001771 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001772 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001773 pid_t spid = IPCThreadState::self()->getCallingPid();
1774 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001775 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001776 return ::PERMISSION_DENIED;
1777 }
1778
Robin Lee4b84fdc2014-09-24 11:56:57 +01001779 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001780 }
1781
Kenny Root07438c82012-11-02 15:41:02 -07001782 /*
1783 * Here is the history. To improve the security, the parameters to generate the
1784 * master key has been changed. To make a seamless transition, we update the
1785 * file using the same password when the user unlock it for the first time. If
1786 * any thing goes wrong during the transition, the new file will not overwrite
1787 * the old one. This avoids permanent damages of the existing data.
1788 */
1789 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001790 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001791 pid_t spid = IPCThreadState::self()->getCallingPid();
1792 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001793 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001794 return ::PERMISSION_DENIED;
1795 }
Kenny Root70e3a862012-02-15 17:20:23 -08001796
Kenny Root07438c82012-11-02 15:41:02 -07001797 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001798
Kenny Root655b9582013-04-04 08:37:42 -07001799 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001800 case ::STATE_UNINITIALIZED: {
1801 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001802 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001803 }
1804 case ::STATE_NO_ERROR: {
1805 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001806 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001807 }
1808 case ::STATE_LOCKED: {
1809 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001810 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001811 }
1812 }
1813 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001814 }
1815
Kenny Root07438c82012-11-02 15:41:02 -07001816 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001817 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001818 pid_t spid = IPCThreadState::self()->getCallingPid();
1819 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001820 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001821 return ::PERMISSION_DENIED;
1822 }
Kenny Root70e3a862012-02-15 17:20:23 -08001823
Kenny Root655b9582013-04-04 08:37:42 -07001824 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001825 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001826 ALOGD("calling lock in state: %d", state);
1827 return state;
1828 }
1829
Kenny Root655b9582013-04-04 08:37:42 -07001830 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001831 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001832 }
1833
Kenny Root07438c82012-11-02 15:41:02 -07001834 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001835 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001836 pid_t spid = IPCThreadState::self()->getCallingPid();
1837 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001838 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001839 return ::PERMISSION_DENIED;
1840 }
1841
Kenny Root655b9582013-04-04 08:37:42 -07001842 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001843 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001844 ALOGD("calling unlock when not locked");
1845 return state;
1846 }
1847
1848 const String8 password8(pw);
1849 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001850 }
1851
Kenny Root07438c82012-11-02 15:41:02 -07001852 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001853 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001854 pid_t spid = IPCThreadState::self()->getCallingPid();
1855 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001856 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001857 return -1;
1858 }
Kenny Root70e3a862012-02-15 17:20:23 -08001859
Kenny Root655b9582013-04-04 08:37:42 -07001860 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001861 }
1862
Kenny Root96427ba2013-08-16 14:02:41 -07001863 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1864 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001865 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001866 pid_t spid = IPCThreadState::self()->getCallingPid();
1867 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001868 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001869 return ::PERMISSION_DENIED;
1870 }
Kenny Root70e3a862012-02-15 17:20:23 -08001871
Kenny Root49468902013-03-19 13:41:33 -07001872 if (targetUid == -1) {
1873 targetUid = callingUid;
1874 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001875 return ::PERMISSION_DENIED;
1876 }
1877
Kenny Root655b9582013-04-04 08:37:42 -07001878 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001879 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1880 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001881 return state;
1882 }
Kenny Root70e3a862012-02-15 17:20:23 -08001883
Kenny Root07438c82012-11-02 15:41:02 -07001884 uint8_t* data;
1885 size_t dataLength;
1886 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001887 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001888
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001889 const keymaster1_device_t* device = mKeyStore->getDevice();
1890 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001891 if (device == NULL) {
1892 return ::SYSTEM_ERROR;
1893 }
1894
1895 if (device->generate_keypair == NULL) {
1896 return ::SYSTEM_ERROR;
1897 }
1898
Kenny Root17208e02013-09-04 13:56:03 -07001899 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001900 keymaster_dsa_keygen_params_t dsa_params;
1901 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001902
Kenny Root96427ba2013-08-16 14:02:41 -07001903 if (keySize == -1) {
1904 keySize = DSA_DEFAULT_KEY_SIZE;
1905 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1906 || keySize > DSA_MAX_KEY_SIZE) {
1907 ALOGI("invalid key size %d", keySize);
1908 return ::SYSTEM_ERROR;
1909 }
1910 dsa_params.key_size = keySize;
1911
1912 if (args->size() == 3) {
1913 sp<KeystoreArg> gArg = args->itemAt(0);
1914 sp<KeystoreArg> pArg = args->itemAt(1);
1915 sp<KeystoreArg> qArg = args->itemAt(2);
1916
1917 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1918 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1919 dsa_params.generator_len = gArg->size();
1920
1921 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1922 dsa_params.prime_p_len = pArg->size();
1923
1924 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1925 dsa_params.prime_q_len = qArg->size();
1926 } else {
1927 ALOGI("not all DSA parameters were read");
1928 return ::SYSTEM_ERROR;
1929 }
1930 } else if (args->size() != 0) {
1931 ALOGI("DSA args must be 3");
1932 return ::SYSTEM_ERROR;
1933 }
1934
Kenny Root1d448c02013-11-21 10:36:53 -08001935 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001936 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1937 } else {
1938 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001939 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1940 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001941 }
1942 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001943 keymaster_ec_keygen_params_t ec_params;
1944 memset(&ec_params, '\0', sizeof(ec_params));
1945
1946 if (keySize == -1) {
1947 keySize = EC_DEFAULT_KEY_SIZE;
1948 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1949 ALOGI("invalid key size %d", keySize);
1950 return ::SYSTEM_ERROR;
1951 }
1952 ec_params.field_size = keySize;
1953
Kenny Root1d448c02013-11-21 10:36:53 -08001954 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001955 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1956 } else {
1957 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001958 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001959 }
Kenny Root96427ba2013-08-16 14:02:41 -07001960 } else if (keyType == EVP_PKEY_RSA) {
1961 keymaster_rsa_keygen_params_t rsa_params;
1962 memset(&rsa_params, '\0', sizeof(rsa_params));
1963 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1964
1965 if (keySize == -1) {
1966 keySize = RSA_DEFAULT_KEY_SIZE;
1967 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1968 ALOGI("invalid key size %d", keySize);
1969 return ::SYSTEM_ERROR;
1970 }
1971 rsa_params.modulus_size = keySize;
1972
1973 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001974 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001975 return ::SYSTEM_ERROR;
1976 } else if (args->size() == 1) {
1977 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1978 if (pubExpBlob != NULL) {
1979 Unique_BIGNUM pubExpBn(
1980 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1981 pubExpBlob->size(), NULL));
1982 if (pubExpBn.get() == NULL) {
1983 ALOGI("Could not convert public exponent to BN");
1984 return ::SYSTEM_ERROR;
1985 }
1986 unsigned long pubExp = BN_get_word(pubExpBn.get());
1987 if (pubExp == 0xFFFFFFFFL) {
1988 ALOGI("cannot represent public exponent as a long value");
1989 return ::SYSTEM_ERROR;
1990 }
1991 rsa_params.public_exponent = pubExp;
1992 }
1993 }
1994
1995 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1996 } else {
1997 ALOGW("Unsupported key type %d", keyType);
1998 rc = -1;
1999 }
2000
Kenny Root07438c82012-11-02 15:41:02 -07002001 if (rc) {
2002 return ::SYSTEM_ERROR;
2003 }
2004
Kenny Root655b9582013-04-04 08:37:42 -07002005 String8 name8(name);
2006 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002007
2008 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2009 free(data);
2010
Kenny Rootee8068b2013-10-07 09:49:15 -07002011 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002012 keyBlob.setFallback(isFallback);
2013
Kenny Root655b9582013-04-04 08:37:42 -07002014 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08002015 }
2016
Kenny Rootf9119d62013-04-03 09:22:15 -07002017 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2018 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002019 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002020 pid_t spid = IPCThreadState::self()->getCallingPid();
2021 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002022 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002023 return ::PERMISSION_DENIED;
2024 }
Kenny Root07438c82012-11-02 15:41:02 -07002025
Kenny Root49468902013-03-19 13:41:33 -07002026 if (targetUid == -1) {
2027 targetUid = callingUid;
2028 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002029 return ::PERMISSION_DENIED;
2030 }
2031
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002032 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002033 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002034 ALOGD("calling import in state: %d", state);
2035 return state;
2036 }
2037
2038 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
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002041 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002042 }
2043
Kenny Root07438c82012-11-02 15:41:02 -07002044 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2045 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002046 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002047 pid_t spid = IPCThreadState::self()->getCallingPid();
2048 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002049 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002050 return ::PERMISSION_DENIED;
2051 }
Kenny Root07438c82012-11-02 15:41:02 -07002052
Kenny Root07438c82012-11-02 15:41:02 -07002053 Blob keyBlob;
2054 String8 name8(name);
2055
Kenny Rootd38a0b02013-02-13 12:59:14 -08002056 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002057 int rc;
2058
Kenny Root655b9582013-04-04 08:37:42 -07002059 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002060 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002061 if (responseCode != ::NO_ERROR) {
2062 return responseCode;
2063 }
2064
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002065 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002066 if (device == NULL) {
2067 ALOGE("no keymaster device; cannot sign");
2068 return ::SYSTEM_ERROR;
2069 }
2070
2071 if (device->sign_data == NULL) {
2072 ALOGE("device doesn't implement signing");
2073 return ::SYSTEM_ERROR;
2074 }
2075
2076 keymaster_rsa_sign_params_t params;
2077 params.digest_type = DIGEST_NONE;
2078 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002079 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2080 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002081 if (rc) {
2082 ALOGW("device couldn't sign data");
2083 return ::SYSTEM_ERROR;
2084 }
2085
2086 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002087 }
2088
Kenny Root07438c82012-11-02 15:41:02 -07002089 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2090 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002091 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002092 pid_t spid = IPCThreadState::self()->getCallingPid();
2093 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002094 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002095 return ::PERMISSION_DENIED;
2096 }
Kenny Root70e3a862012-02-15 17:20:23 -08002097
Kenny Root655b9582013-04-04 08:37:42 -07002098 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002099 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002100 ALOGD("calling verify in state: %d", state);
2101 return state;
2102 }
Kenny Root70e3a862012-02-15 17:20:23 -08002103
Kenny Root07438c82012-11-02 15:41:02 -07002104 Blob keyBlob;
2105 String8 name8(name);
2106 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002107
Kenny Root655b9582013-04-04 08:37:42 -07002108 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002109 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002110 if (responseCode != ::NO_ERROR) {
2111 return responseCode;
2112 }
Kenny Root70e3a862012-02-15 17:20:23 -08002113
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002114 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002115 if (device == NULL) {
2116 return ::SYSTEM_ERROR;
2117 }
Kenny Root70e3a862012-02-15 17:20:23 -08002118
Kenny Root07438c82012-11-02 15:41:02 -07002119 if (device->verify_data == NULL) {
2120 return ::SYSTEM_ERROR;
2121 }
Kenny Root70e3a862012-02-15 17:20:23 -08002122
Kenny Root07438c82012-11-02 15:41:02 -07002123 keymaster_rsa_sign_params_t params;
2124 params.digest_type = DIGEST_NONE;
2125 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002126
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002127 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2128 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002129 if (rc) {
2130 return ::SYSTEM_ERROR;
2131 } else {
2132 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002133 }
2134 }
Kenny Root07438c82012-11-02 15:41:02 -07002135
2136 /*
2137 * TODO: The abstraction between things stored in hardware and regular blobs
2138 * of data stored on the filesystem should be moved down to keystore itself.
2139 * Unfortunately the Java code that calls this has naming conventions that it
2140 * knows about. Ideally keystore shouldn't be used to store random blobs of
2141 * data.
2142 *
2143 * Until that happens, it's necessary to have a separate "get_pubkey" and
2144 * "del_key" since the Java code doesn't really communicate what it's
2145 * intentions are.
2146 */
2147 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002148 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002149 pid_t spid = IPCThreadState::self()->getCallingPid();
2150 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002151 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002152 return ::PERMISSION_DENIED;
2153 }
Kenny Root07438c82012-11-02 15:41:02 -07002154
Kenny Root07438c82012-11-02 15:41:02 -07002155 Blob keyBlob;
2156 String8 name8(name);
2157
Kenny Rootd38a0b02013-02-13 12:59:14 -08002158 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002159
Kenny Root655b9582013-04-04 08:37:42 -07002160 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002161 TYPE_KEY_PAIR);
2162 if (responseCode != ::NO_ERROR) {
2163 return responseCode;
2164 }
2165
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002166 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002167 if (device == NULL) {
2168 return ::SYSTEM_ERROR;
2169 }
2170
2171 if (device->get_keypair_public == NULL) {
2172 ALOGE("device has no get_keypair_public implementation!");
2173 return ::SYSTEM_ERROR;
2174 }
2175
Kenny Root17208e02013-09-04 13:56:03 -07002176 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002177 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2178 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002179 if (rc) {
2180 return ::SYSTEM_ERROR;
2181 }
2182
2183 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002184 }
Kenny Root07438c82012-11-02 15:41:02 -07002185
Kenny Root49468902013-03-19 13:41:33 -07002186 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002187 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002188 pid_t spid = IPCThreadState::self()->getCallingPid();
2189 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002190 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002191 return ::PERMISSION_DENIED;
2192 }
Kenny Root07438c82012-11-02 15:41:02 -07002193
Kenny Root49468902013-03-19 13:41:33 -07002194 if (targetUid == -1) {
2195 targetUid = callingUid;
2196 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002197 return ::PERMISSION_DENIED;
2198 }
2199
Kenny Root07438c82012-11-02 15:41:02 -07002200 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002201 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002202 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002203 }
2204
2205 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002206 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002207 pid_t spid = IPCThreadState::self()->getCallingPid();
2208 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002209 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002210 return ::PERMISSION_DENIED;
2211 }
Kenny Root07438c82012-11-02 15:41:02 -07002212
Kenny Root655b9582013-04-04 08:37:42 -07002213 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002214 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002215 ALOGD("calling grant in state: %d", state);
2216 return state;
2217 }
2218
2219 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002220 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002221
Kenny Root655b9582013-04-04 08:37:42 -07002222 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002223 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2224 }
2225
Kenny Root655b9582013-04-04 08:37:42 -07002226 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002227 return ::NO_ERROR;
2228 }
2229
2230 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002231 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002232 pid_t spid = IPCThreadState::self()->getCallingPid();
2233 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002234 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002235 return ::PERMISSION_DENIED;
2236 }
Kenny Root07438c82012-11-02 15:41:02 -07002237
Kenny Root655b9582013-04-04 08:37:42 -07002238 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002239 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002240 ALOGD("calling ungrant in state: %d", state);
2241 return state;
2242 }
2243
2244 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002245 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002246
Kenny Root655b9582013-04-04 08:37:42 -07002247 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002248 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2249 }
2250
Kenny Root655b9582013-04-04 08:37:42 -07002251 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002252 }
2253
2254 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002255 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002256 pid_t spid = IPCThreadState::self()->getCallingPid();
2257 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002258 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002259 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002260 }
Kenny Root07438c82012-11-02 15:41:02 -07002261
2262 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002263 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002264
Kenny Root655b9582013-04-04 08:37:42 -07002265 if (access(filename.string(), R_OK) == -1) {
2266 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002267 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002268 }
2269
Kenny Root655b9582013-04-04 08:37:42 -07002270 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002271 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002272 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002273 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002274 }
2275
2276 struct stat s;
2277 int ret = fstat(fd, &s);
2278 close(fd);
2279 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002280 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002281 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002282 }
2283
Kenny Root36a9e232013-02-04 14:24:15 -08002284 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002285 }
2286
Kenny Rootd53bc922013-03-21 14:10:15 -07002287 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2288 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002289 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002290 pid_t spid = IPCThreadState::self()->getCallingPid();
2291 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002292 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002293 return -1L;
2294 }
2295
Kenny Root655b9582013-04-04 08:37:42 -07002296 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002297 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002298 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002299 return state;
2300 }
2301
Kenny Rootd53bc922013-03-21 14:10:15 -07002302 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2303 srcUid = callingUid;
2304 } else if (!is_granted_to(callingUid, srcUid)) {
2305 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002306 return ::PERMISSION_DENIED;
2307 }
2308
Kenny Rootd53bc922013-03-21 14:10:15 -07002309 if (destUid == -1) {
2310 destUid = callingUid;
2311 }
2312
2313 if (srcUid != destUid) {
2314 if (static_cast<uid_t>(srcUid) != callingUid) {
2315 ALOGD("can only duplicate from caller to other or to same uid: "
2316 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2317 return ::PERMISSION_DENIED;
2318 }
2319
2320 if (!is_granted_to(callingUid, destUid)) {
2321 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2322 return ::PERMISSION_DENIED;
2323 }
2324 }
2325
2326 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002327 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002328
Kenny Rootd53bc922013-03-21 14:10:15 -07002329 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002330 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002331
Kenny Root655b9582013-04-04 08:37:42 -07002332 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2333 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002334 return ::SYSTEM_ERROR;
2335 }
2336
Kenny Rootd53bc922013-03-21 14:10:15 -07002337 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002338 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002339 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002340 if (responseCode != ::NO_ERROR) {
2341 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002342 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002343
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002344 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002345 }
2346
Kenny Root1b0e3932013-09-05 13:06:32 -07002347 int32_t is_hardware_backed(const String16& keyType) {
2348 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002349 }
2350
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002351 int32_t clear_uid(int64_t targetUid64) {
2352 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002353 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002354 pid_t spid = IPCThreadState::self()->getCallingPid();
2355 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002356 ALOGW("permission denied for %d: clear_uid", callingUid);
2357 return ::PERMISSION_DENIED;
2358 }
2359
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002360 if (targetUid64 == -1) {
2361 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002362 } else if (!is_self_or_system(callingUid, targetUid)) {
2363 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002364 return ::PERMISSION_DENIED;
2365 }
2366
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002367 const keymaster1_device_t* device = mKeyStore->getDevice();
Kenny Roota9bb5492013-04-01 16:29:11 -07002368 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002369 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002370 return ::SYSTEM_ERROR;
2371 }
2372
Robin Lee4b84fdc2014-09-24 11:56:57 +01002373 String8 prefix = String8::format("%u_", targetUid);
2374 Vector<String16> aliases;
2375 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002376 return ::SYSTEM_ERROR;
2377 }
2378
Robin Lee4b84fdc2014-09-24 11:56:57 +01002379 for (uint32_t i = 0; i < aliases.size(); i++) {
2380 String8 name8(aliases[i]);
2381 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2382 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002383 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002384 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002385 }
2386
Robin Lee4b84fdc2014-09-24 11:56:57 +01002387 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002388 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2389 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002390
Robin Lee4e865752014-08-19 17:37:55 +01002391 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002392 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002393 return ::PERMISSION_DENIED;
2394 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002395 if (!is_self_or_system(callingUid, targetUid)) {
2396 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002397 return ::PERMISSION_DENIED;
2398 }
2399
Robin Lee4b84fdc2014-09-24 11:56:57 +01002400 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002401 }
2402
2403 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2404 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2405 pid_t spid = IPCThreadState::self()->getCallingPid();
2406 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2407 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2408 return ::PERMISSION_DENIED;
2409 }
2410 if (callingUid != AID_SYSTEM) {
2411 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2412 return ::PERMISSION_DENIED;
2413 }
2414 if (sourceUid == targetUid) {
2415 return ::SYSTEM_ERROR;
2416 }
2417
2418 // Initialise user keystore with existing master key held in-memory
2419 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2420 }
2421
2422 int32_t password_uid(const String16& pw, int32_t targetUid) {
2423 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2424 pid_t spid = IPCThreadState::self()->getCallingPid();
2425 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2426 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2427 return ::PERMISSION_DENIED;
2428 }
2429 if (callingUid != AID_SYSTEM) {
2430 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2431 return ::PERMISSION_DENIED;
2432 }
2433
2434 const String8 password8(pw);
2435
2436 switch (mKeyStore->getState(targetUid)) {
2437 case ::STATE_UNINITIALIZED: {
2438 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2439 return mKeyStore->initializeUser(password8, targetUid);
2440 }
2441 case ::STATE_NO_ERROR: {
2442 // rewrite master key with new password.
2443 return mKeyStore->writeMasterKey(password8, targetUid);
2444 }
2445 case ::STATE_LOCKED: {
2446 // read master key, decrypt with password, initialize mMasterKey*.
2447 return mKeyStore->readMasterKey(password8, targetUid);
2448 }
2449 }
2450 return ::SYSTEM_ERROR;
2451 }
2452
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002453 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2454 const keymaster1_device_t* device = mKeyStore->getDevice();
2455 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2456 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2457 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2458 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2459 device->add_rng_entropy != NULL) {
2460 devResult = device->add_rng_entropy(device, data, dataLength);
2461 }
2462 if (fallback->add_rng_entropy) {
2463 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2464 }
2465 if (devResult) {
2466 return devResult;
2467 }
2468 if (fallbackResult) {
2469 return fallbackResult;
2470 }
2471 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002472 }
2473
Chad Brubaker17d68b92015-02-05 22:04:16 -08002474 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002475 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2476 KeyCharacteristics* outCharacteristics) {
Chad Brubaker17d68b92015-02-05 22:04:16 -08002477 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2478 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2479 if (!has_permission(callingUid, P_INSERT, callingPid)) {
2480 ALOGW("permission denied for %d: generateKey", callingUid);
2481 return ::PERMISSION_DENIED;
2482 }
2483
2484 State state = mKeyStore->getState(callingUid);
2485 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2486 ALOGW("calling generate in state: %d", state);
2487 return state;
2488 }
2489
2490 if (uid == -1) {
2491 uid = callingUid;
2492 } else if (!is_granted_to(callingUid, uid)) {
2493 return ::PERMISSION_DENIED;
2494 }
2495
Chad Brubaker17d68b92015-02-05 22:04:16 -08002496 int rc = KM_ERROR_UNIMPLEMENTED;
2497 bool isFallback = false;
2498 keymaster_key_blob_t blob;
2499 keymaster_key_characteristics_t *out = NULL;
2500
2501 const keymaster1_device_t* device = mKeyStore->getDevice();
2502 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2503 if (device == NULL) {
2504 return ::SYSTEM_ERROR;
2505 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002506 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002507 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2508 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002509 if (!entropy) {
2510 rc = KM_ERROR_OK;
2511 } else if (device->add_rng_entropy) {
2512 rc = device->add_rng_entropy(device, entropy, entropyLength);
2513 } else {
2514 rc = KM_ERROR_UNIMPLEMENTED;
2515 }
2516 if (rc == KM_ERROR_OK) {
2517 rc = device->generate_key(device, params.params.data(), params.params.size(),
2518 &blob, &out);
2519 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002520 }
2521 // If the HW device didn't support generate_key or generate_key failed
2522 // fall back to the software implementation.
2523 if (rc && fallback->generate_key != NULL) {
2524 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002525 if (!entropy) {
2526 rc = KM_ERROR_OK;
2527 } else if (fallback->add_rng_entropy) {
2528 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2529 } else {
2530 rc = KM_ERROR_UNIMPLEMENTED;
2531 }
2532 if (rc == KM_ERROR_OK) {
2533 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2534 &blob,
2535 &out);
2536 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002537 }
2538
2539 if (out) {
2540 if (outCharacteristics) {
2541 outCharacteristics->characteristics = *out;
2542 } else {
2543 keymaster_free_characteristics(out);
2544 }
2545 free(out);
2546 }
2547
2548 if (rc) {
2549 return rc;
2550 }
2551
2552 String8 name8(name);
2553 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2554
2555 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2556 keyBlob.setFallback(isFallback);
2557 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2558
2559 free(const_cast<uint8_t*>(blob.key_material));
2560
2561 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002562 }
2563
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002564 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002565 const keymaster_blob_t* clientId,
2566 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002567 KeyCharacteristics* outCharacteristics) {
2568
2569 if (!outCharacteristics) {
2570 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2571 }
2572
2573 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2574
2575 Blob keyBlob;
2576 String8 name8(name);
2577 int rc;
2578
2579 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2580 TYPE_KEYMASTER_10);
2581 if (responseCode != ::NO_ERROR) {
2582 return responseCode;
2583 }
2584 keymaster_key_blob_t key;
2585 key.key_material_size = keyBlob.getLength();
2586 key.key_material = keyBlob.getValue();
2587 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2588 keymaster_key_characteristics_t *out = NULL;
2589 if (!dev->get_key_characteristics) {
2590 ALOGW("device does not implement get_key_characteristics");
2591 return KM_ERROR_UNIMPLEMENTED;
2592 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002593 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002594 if (out) {
2595 outCharacteristics->characteristics = *out;
2596 free(out);
2597 }
2598 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002599 }
2600
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002601 int32_t importKey(const String16& name, const KeymasterArguments& params,
2602 keymaster_key_format_t format, const uint8_t *keyData,
2603 size_t keyLength, int uid, int flags,
2604 KeyCharacteristics* outCharacteristics) {
2605 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2606 pid_t spid = IPCThreadState::self()->getCallingPid();
2607 if (!has_permission(callingUid, P_INSERT, spid)) {
2608 ALOGW("permission denied for %d: importKey", callingUid);
2609 return ::PERMISSION_DENIED;
2610 }
2611
2612 State state = mKeyStore->getState(callingUid);
2613 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2614 ALOGW("calling importKey in state: %d", state);
2615 return state;
2616 }
2617
2618 if (uid == -1) {
2619 uid = callingUid;
2620 } else if (!is_granted_to(callingUid, uid)) {
2621 ALOGW("not granted to %d %d", callingUid, uid);
2622 return ::PERMISSION_DENIED;
2623 }
2624
2625 int rc = KM_ERROR_UNIMPLEMENTED;
2626 bool isFallback = false;
2627 keymaster_key_blob_t blob;
2628 keymaster_key_characteristics_t *out = NULL;
2629
2630 const keymaster1_device_t* device = mKeyStore->getDevice();
2631 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2632 if (device == NULL) {
2633 return ::SYSTEM_ERROR;
2634 }
2635 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2636 device->import_key != NULL) {
2637 rc = device->import_key(device, params.params.data(), params.params.size(),
2638 format, keyData, keyLength, &blob, &out);
2639 }
2640 if (rc && fallback->import_key != NULL) {
2641 isFallback = true;
2642 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2643 format, keyData, keyLength, &blob, &out);
2644 }
2645 if (out) {
2646 if (outCharacteristics) {
2647 outCharacteristics->characteristics = *out;
2648 } else {
2649 keymaster_free_characteristics(out);
2650 }
2651 free(out);
2652 }
2653 if (rc) {
2654 return rc;
2655 }
2656
2657 String8 name8(name);
2658 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2659
2660 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2661 keyBlob.setFallback(isFallback);
2662 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2663
2664 free((void*) blob.key_material);
2665
2666 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002667 }
2668
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002669 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002670 const keymaster_blob_t* clientId,
2671 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002672
2673 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2674
2675 Blob keyBlob;
2676 String8 name8(name);
2677 int rc;
2678
2679 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2680 TYPE_KEYMASTER_10);
2681 if (responseCode != ::NO_ERROR) {
2682 result->resultCode = responseCode;
2683 return;
2684 }
2685 keymaster_key_blob_t key;
2686 key.key_material_size = keyBlob.getLength();
2687 key.key_material = keyBlob.getValue();
2688 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2689 if (!dev->export_key) {
2690 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2691 return;
2692 }
2693 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002694 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002695 &ptr, &result->dataLength);
2696 result->exportData.reset(ptr);
2697 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002698 }
2699
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002700 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002701 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2702 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002703 if (!result || !outParams) {
2704 ALOGE("Unexpected null arguments to begin()");
2705 return;
2706 }
2707 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2708 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2709 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2710 result->resultCode = ::PERMISSION_DENIED;
2711 return;
2712 }
2713 Blob keyBlob;
2714 String8 name8(name);
2715 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2716 TYPE_KEYMASTER_10);
2717 if (responseCode != ::NO_ERROR) {
2718 result->resultCode = responseCode;
2719 return;
2720 }
2721 keymaster_key_blob_t key;
2722 key.key_material_size = keyBlob.getLength();
2723 key.key_material = keyBlob.getValue();
2724 keymaster_key_param_t* out;
2725 size_t outSize;
2726 keymaster_operation_handle_t handle;
2727 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002728 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
2729 // Add entropy to the device first.
2730 if (entropy) {
2731 if (dev->add_rng_entropy) {
2732 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2733 } else {
2734 err = KM_ERROR_UNIMPLEMENTED;
2735 }
2736 if (err) {
2737 result->resultCode = err;
2738 return;
2739 }
2740 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002741 // TODO: Check authorization.
Chad Brubaker154d7692015-03-27 13:59:31 -07002742 err = dev->begin(dev, purpose, &key, params.params.data(), params.params.size(), &out,
2743 &outSize, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002744
2745 // If there are too many operations abort the oldest operation that was
2746 // started as pruneable and try again.
2747 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2748 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2749 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2750 if (abort(oldest) != ::NO_ERROR) {
2751 break;
2752 }
2753 err = dev->begin(dev, purpose, &key, params.params.data(),
2754 params.params.size(), &out, &outSize,
2755 &handle);
2756 }
2757 if (err) {
2758 result->resultCode = err;
2759 return;
2760 }
2761 if (out) {
2762 outParams->params.assign(out, out + outSize);
2763 free(out);
2764 }
2765
2766 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken, pruneable);
2767 result->resultCode = ::NO_ERROR;
2768 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002769 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002770 }
2771
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002772 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2773 size_t dataLength, OperationResult* result) {
2774 const keymaster1_device_t* dev;
2775 keymaster_operation_handle_t handle;
2776 if (!mOperationMap.getOperation(token, &handle, &dev)) {
2777 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2778 return;
2779 }
2780 uint8_t* output_buf = NULL;
2781 size_t output_length = 0;
2782 size_t consumed = 0;
2783 // TODO: Check authorization.
2784 keymaster_error_t err = dev->update(dev, handle, params.params.data(),
2785 params.params.size(), data, dataLength,
2786 &consumed, &output_buf, &output_length);
2787 result->data.reset(output_buf);
2788 result->dataLength = output_length;
2789 result->inputConsumed = consumed;
2790 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002791 }
2792
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002793 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2794 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
2795 const keymaster1_device_t* dev;
2796 keymaster_operation_handle_t handle;
2797 if (!mOperationMap.getOperation(token, &handle, &dev)) {
2798 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2799 return;
2800 }
2801 uint8_t* output_buf = NULL;
2802 size_t output_length = 0;
2803 // TODO: Check authorization.
2804 keymaster_error_t err = dev->finish(dev, handle, params.params.data(),
2805 params.params.size(), signature, signatureLength,
2806 &output_buf, &output_length);
2807 // Remove the operation regardless of the result
2808 mOperationMap.removeOperation(token);
2809 result->data.reset(output_buf);
2810 result->dataLength = output_length;
2811 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002812 }
2813
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002814 int32_t abort(const sp<IBinder>& token) {
2815 const keymaster1_device_t* dev;
2816 keymaster_operation_handle_t handle;
2817 if (!mOperationMap.getOperation(token, &handle, &dev)) {
2818 return KM_ERROR_INVALID_OPERATION_HANDLE;
2819 }
2820 mOperationMap.removeOperation(token);
2821 if (!dev->abort) {
2822 return KM_ERROR_UNIMPLEMENTED;
2823 }
2824 int32_t rc = dev->abort(dev, handle);
2825 if (rc) {
2826 return rc;
2827 }
2828 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002829 }
2830
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002831 bool isOperationAuthorized(const sp<IBinder>& token) {
2832 const keymaster1_device_t* dev;
2833 keymaster_operation_handle_t handle;
2834 if(!mOperationMap.getOperation(token, &handle, &dev)) {
2835 return false;
2836 }
2837 // TODO: Check authorization.
2838 return true;
2839 }
2840
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002841 int32_t addAuthToken(const uint8_t* token, size_t length) {
2842 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2843 pid_t spid = IPCThreadState::self()->getCallingPid();
2844 if (!has_permission(callingUid, P_ADD_AUTH, spid)) {
2845 ALOGW("permission denied for %d: addAuthToken", callingUid);
2846 return ::PERMISSION_DENIED;
2847 }
2848 if (length != sizeof(hw_auth_token_t)) {
2849 return KM_ERROR_INVALID_ARGUMENT;
2850 }
2851 hw_auth_token_t* authToken = new hw_auth_token_t;
2852 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2853 // The table takes ownership of authToken.
2854 mAuthTokenTable.AddAuthenticationToken(authToken);
2855 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002856 }
2857
Kenny Root07438c82012-11-02 15:41:02 -07002858private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002859 inline bool isKeystoreUnlocked(State state) {
2860 switch (state) {
2861 case ::STATE_NO_ERROR:
2862 return true;
2863 case ::STATE_UNINITIALIZED:
2864 case ::STATE_LOCKED:
2865 return false;
2866 }
2867 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002868 }
2869
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002870 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002871 const int32_t device_api = device->common.module->module_api_version;
2872 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2873 switch (keyType) {
2874 case TYPE_RSA:
2875 case TYPE_DSA:
2876 case TYPE_EC:
2877 return true;
2878 default:
2879 return false;
2880 }
2881 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2882 switch (keyType) {
2883 case TYPE_RSA:
2884 return true;
2885 case TYPE_DSA:
2886 return device->flags & KEYMASTER_SUPPORTS_DSA;
2887 case TYPE_EC:
2888 return device->flags & KEYMASTER_SUPPORTS_EC;
2889 default:
2890 return false;
2891 }
2892 } else {
2893 return keyType == TYPE_RSA;
2894 }
2895 }
2896
Kenny Root07438c82012-11-02 15:41:02 -07002897 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002898 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002899 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07002900};
2901
2902}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002903
2904int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002905 if (argc < 2) {
2906 ALOGE("A directory must be specified!");
2907 return 1;
2908 }
2909 if (chdir(argv[1]) == -1) {
2910 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2911 return 1;
2912 }
2913
2914 Entropy entropy;
2915 if (!entropy.open()) {
2916 return 1;
2917 }
Kenny Root70e3a862012-02-15 17:20:23 -08002918
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002919 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002920 if (keymaster_device_initialize(&dev)) {
2921 ALOGE("keystore keymaster could not be initialized; exiting");
2922 return 1;
2923 }
2924
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002925 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002926 if (fallback_keymaster_device_initialize(&fallback)) {
2927 ALOGE("software keymaster could not be initialized; exiting");
2928 return 1;
2929 }
2930
Riley Spahneaabae92014-06-30 12:39:52 -07002931 ks_is_selinux_enabled = is_selinux_enabled();
2932 if (ks_is_selinux_enabled) {
2933 union selinux_callback cb;
2934 cb.func_log = selinux_log_callback;
2935 selinux_set_callback(SELINUX_CB_LOG, cb);
2936 if (getcon(&tctx) != 0) {
2937 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2938 return -1;
2939 }
2940 } else {
2941 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2942 }
2943
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002944 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07002945 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002946 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2947 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2948 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2949 if (ret != android::OK) {
2950 ALOGE("Couldn't register binder service!");
2951 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002952 }
Kenny Root07438c82012-11-02 15:41:02 -07002953
2954 /*
2955 * We're the only thread in existence, so we're just going to process
2956 * Binder transaction as a single-threaded program.
2957 */
2958 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002959
2960 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002961 return 1;
2962}