blob: b89ac820ad7719d79d9cf04b740e68e4a771b55f [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Shawn Willden80843db2015-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 Willden80843db2015-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
Shawn Willden04006752015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker67d2a502015-03-11 17:21:18 +0000137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willden80843db2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100155 P_TEST = 1 << 0,
156 P_GET = 1 << 1,
157 P_INSERT = 1 << 2,
158 P_DELETE = 1 << 3,
159 P_EXIST = 1 << 4,
160 P_SAW = 1 << 5,
161 P_RESET = 1 << 6,
162 P_PASSWORD = 1 << 7,
163 P_LOCK = 1 << 8,
164 P_UNLOCK = 1 << 9,
165 P_ZERO = 1 << 10,
166 P_SIGN = 1 << 11,
167 P_VERIFY = 1 << 12,
168 P_GRANT = 1 << 13,
169 P_DUPLICATE = 1 << 14,
170 P_CLEAR_UID = 1 << 15,
171 P_RESET_UID = 1 << 16,
172 P_SYNC_UID = 1 << 17,
173 P_PASSWORD_UID = 1 << 18,
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700174 P_ADD_AUTH = 1 << 19,
Kenny Root07438c82012-11-02 15:41:02 -0700175} perm_t;
176
177static struct user_euid {
178 uid_t uid;
179 uid_t euid;
180} user_euids[] = {
181 {AID_VPN, AID_SYSTEM},
182 {AID_WIFI, AID_SYSTEM},
183 {AID_ROOT, AID_SYSTEM},
184};
185
Riley Spahneaabae92014-06-30 12:39:52 -0700186/* perm_labels associcated with keystore_key SELinux class verbs. */
187const char *perm_labels[] = {
188 "test",
189 "get",
190 "insert",
191 "delete",
192 "exist",
193 "saw",
194 "reset",
195 "password",
196 "lock",
197 "unlock",
198 "zero",
199 "sign",
200 "verify",
201 "grant",
202 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100203 "clear_uid",
204 "reset_uid",
205 "sync_uid",
206 "password_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700207 "add_auth",
Riley Spahneaabae92014-06-30 12:39:52 -0700208};
209
Kenny Root07438c82012-11-02 15:41:02 -0700210static struct user_perm {
211 uid_t uid;
212 perm_t perms;
213} user_perms[] = {
214 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
215 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
216 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
217 {AID_ROOT, static_cast<perm_t>(P_GET) },
218};
219
220static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
221 | P_VERIFY);
222
Riley Spahneaabae92014-06-30 12:39:52 -0700223static char *tctx;
224static int ks_is_selinux_enabled;
225
226static const char *get_perm_label(perm_t perm) {
227 unsigned int index = ffs(perm);
228 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
229 return perm_labels[index - 1];
230 } else {
231 ALOGE("Keystore: Failed to retrieve permission label.\n");
232 abort();
233 }
234}
235
Kenny Root655b9582013-04-04 08:37:42 -0700236/**
237 * Returns the app ID (in the Android multi-user sense) for the current
238 * UNIX UID.
239 */
240static uid_t get_app_id(uid_t uid) {
241 return uid % AID_USER;
242}
243
244/**
245 * Returns the user ID (in the Android multi-user sense) for the current
246 * UNIX UID.
247 */
248static uid_t get_user_id(uid_t uid) {
249 return uid / AID_USER;
250}
251
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700252static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700253 if (!ks_is_selinux_enabled) {
254 return true;
255 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000256
Riley Spahneaabae92014-06-30 12:39:52 -0700257 char *sctx = NULL;
258 const char *selinux_class = "keystore_key";
259 const char *str_perm = get_perm_label(perm);
260
261 if (!str_perm) {
262 return false;
263 }
264
265 if (getpidcon(spid, &sctx) != 0) {
266 ALOGE("SELinux: Failed to get source pid context.\n");
267 return false;
268 }
269
270 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
271 NULL) == 0;
272 freecon(sctx);
273 return allowed;
274}
275
276static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700277 // All system users are equivalent for multi-user support.
278 if (get_app_id(uid) == AID_SYSTEM) {
279 uid = AID_SYSTEM;
280 }
281
Kenny Root07438c82012-11-02 15:41:02 -0700282 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
283 struct user_perm user = user_perms[i];
284 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700285 return (user.perms & perm) &&
286 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700287 }
288 }
289
Riley Spahneaabae92014-06-30 12:39:52 -0700290 return (DEFAULT_PERMS & perm) &&
291 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700292}
293
Kenny Root49468902013-03-19 13:41:33 -0700294/**
295 * Returns the UID that the callingUid should act as. This is here for
296 * legacy support of the WiFi and VPN systems and should be removed
297 * when WiFi can operate in its own namespace.
298 */
Kenny Root07438c82012-11-02 15:41:02 -0700299static uid_t get_keystore_euid(uid_t uid) {
300 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
301 struct user_euid user = user_euids[i];
302 if (user.uid == uid) {
303 return user.euid;
304 }
305 }
306
307 return uid;
308}
309
Kenny Root49468902013-03-19 13:41:33 -0700310/**
311 * Returns true if the callingUid is allowed to interact in the targetUid's
312 * namespace.
313 */
314static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700315 if (callingUid == targetUid) {
316 return true;
317 }
Kenny Root49468902013-03-19 13:41:33 -0700318 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
319 struct user_euid user = user_euids[i];
320 if (user.euid == callingUid && user.uid == targetUid) {
321 return true;
322 }
323 }
324
325 return false;
326}
327
Kenny Roota91203b2012-02-15 15:00:46 -0800328/* Here is the encoding of keys. This is necessary in order to allow arbitrary
329 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
330 * into two bytes. The first byte is one of [+-.] which represents the first
331 * two bits of the character. The second byte encodes the rest of the bits into
332 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
333 * that Base64 cannot be used here due to the need of prefix match on keys. */
334
Kenny Root655b9582013-04-04 08:37:42 -0700335static size_t encode_key_length(const android::String8& keyName) {
336 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
337 size_t length = keyName.length();
338 for (int i = length; i > 0; --i, ++in) {
339 if (*in < '0' || *in > '~') {
340 ++length;
341 }
342 }
343 return length;
344}
345
Kenny Root07438c82012-11-02 15:41:02 -0700346static int encode_key(char* out, const android::String8& keyName) {
347 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
348 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800349 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700350 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800351 *out = '+' + (*in >> 6);
352 *++out = '0' + (*in & 0x3F);
353 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700354 } else {
355 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800356 }
357 }
358 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800359 return length;
360}
361
Kenny Root07438c82012-11-02 15:41:02 -0700362/*
363 * Converts from the "escaped" format on disk to actual name.
364 * This will be smaller than the input string.
365 *
366 * Characters that should combine with the next at the end will be truncated.
367 */
368static size_t decode_key_length(const char* in, size_t length) {
369 size_t outLength = 0;
370
371 for (const char* end = in + length; in < end; in++) {
372 /* This combines with the next character. */
373 if (*in < '0' || *in > '~') {
374 continue;
375 }
376
377 outLength++;
378 }
379 return outLength;
380}
381
382static void decode_key(char* out, const char* in, size_t length) {
383 for (const char* end = in + length; in < end; in++) {
384 if (*in < '0' || *in > '~') {
385 /* Truncate combining characters at the end. */
386 if (in + 1 >= end) {
387 break;
388 }
389
390 *out = (*in++ - '+') << 6;
391 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800392 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700393 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800394 }
395 }
396 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800397}
398
399static size_t readFully(int fd, uint8_t* data, size_t size) {
400 size_t remaining = size;
401 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800402 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800403 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800404 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800405 }
406 data += n;
407 remaining -= n;
408 }
409 return size;
410}
411
412static size_t writeFully(int fd, uint8_t* data, size_t size) {
413 size_t remaining = size;
414 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800415 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
416 if (n < 0) {
417 ALOGW("write failed: %s", strerror(errno));
418 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800419 }
420 data += n;
421 remaining -= n;
422 }
423 return size;
424}
425
426class Entropy {
427public:
428 Entropy() : mRandom(-1) {}
429 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800430 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800431 close(mRandom);
432 }
433 }
434
435 bool open() {
436 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800437 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
438 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800439 ALOGE("open: %s: %s", randomDevice, strerror(errno));
440 return false;
441 }
442 return true;
443 }
444
Kenny Root51878182012-03-13 12:53:19 -0700445 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800446 return (readFully(mRandom, data, size) == size);
447 }
448
449private:
450 int mRandom;
451};
452
453/* Here is the file format. There are two parts in blob.value, the secret and
454 * the description. The secret is stored in ciphertext, and its original size
455 * can be found in blob.length. The description is stored after the secret in
456 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700457 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700458 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800459 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
460 * and decryptBlob(). Thus they should not be accessed from outside. */
461
Kenny Root822c3a92012-03-23 16:34:39 -0700462/* ** Note to future implementors of encryption: **
463 * Currently this is the construction:
464 * metadata || Enc(MD5(data) || data)
465 *
466 * This should be the construction used for encrypting if re-implementing:
467 *
468 * Derive independent keys for encryption and MAC:
469 * Kenc = AES_encrypt(masterKey, "Encrypt")
470 * Kmac = AES_encrypt(masterKey, "MAC")
471 *
472 * Store this:
473 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
474 * HMAC(Kmac, metadata || Enc(data))
475 */
Kenny Roota91203b2012-02-15 15:00:46 -0800476struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700477 uint8_t version;
478 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700479 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800480 uint8_t info;
481 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700482 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800483 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700484 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800485 int32_t length; // in network byte order when encrypted
486 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
487};
488
Kenny Root822c3a92012-03-23 16:34:39 -0700489typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700490 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700491 TYPE_GENERIC = 1,
492 TYPE_MASTER_KEY = 2,
493 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800494 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700495} BlobType;
496
Kenny Rootf9119d62013-04-03 09:22:15 -0700497static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700498
Kenny Roota91203b2012-02-15 15:00:46 -0800499class Blob {
500public:
Kenny Root07438c82012-11-02 15:41:02 -0700501 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
502 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800503 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800504 mBlob.length = valueLength;
505 memcpy(mBlob.value, value, valueLength);
506
507 mBlob.info = infoLength;
508 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700509
Kenny Root07438c82012-11-02 15:41:02 -0700510 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700511 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700512
Kenny Rootee8068b2013-10-07 09:49:15 -0700513 if (type == TYPE_MASTER_KEY) {
514 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
515 } else {
516 mBlob.flags = KEYSTORE_FLAG_NONE;
517 }
Kenny Roota91203b2012-02-15 15:00:46 -0800518 }
519
520 Blob(blob b) {
521 mBlob = b;
522 }
523
Alex Klyubin1773b442015-02-20 12:33:33 -0800524 Blob() {
525 memset(&mBlob, 0, sizeof(mBlob));
526 }
Kenny Roota91203b2012-02-15 15:00:46 -0800527
Kenny Root51878182012-03-13 12:53:19 -0700528 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800529 return mBlob.value;
530 }
531
Kenny Root51878182012-03-13 12:53:19 -0700532 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.length;
534 }
535
Kenny Root51878182012-03-13 12:53:19 -0700536 const uint8_t* getInfo() const {
537 return mBlob.value + mBlob.length;
538 }
539
540 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800541 return mBlob.info;
542 }
543
Kenny Root822c3a92012-03-23 16:34:39 -0700544 uint8_t getVersion() const {
545 return mBlob.version;
546 }
547
Kenny Rootf9119d62013-04-03 09:22:15 -0700548 bool isEncrypted() const {
549 if (mBlob.version < 2) {
550 return true;
551 }
552
553 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
554 }
555
556 void setEncrypted(bool encrypted) {
557 if (encrypted) {
558 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
559 } else {
560 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
561 }
562 }
563
Kenny Root17208e02013-09-04 13:56:03 -0700564 bool isFallback() const {
565 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
566 }
567
568 void setFallback(bool fallback) {
569 if (fallback) {
570 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
571 } else {
572 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
573 }
574 }
575
Kenny Root822c3a92012-03-23 16:34:39 -0700576 void setVersion(uint8_t version) {
577 mBlob.version = version;
578 }
579
580 BlobType getType() const {
581 return BlobType(mBlob.type);
582 }
583
584 void setType(BlobType type) {
585 mBlob.type = uint8_t(type);
586 }
587
Kenny Rootf9119d62013-04-03 09:22:15 -0700588 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
589 ALOGV("writing blob %s", filename);
590 if (isEncrypted()) {
591 if (state != STATE_NO_ERROR) {
592 ALOGD("couldn't insert encrypted blob while not unlocked");
593 return LOCKED;
594 }
595
596 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
597 ALOGW("Could not read random data for: %s", filename);
598 return SYSTEM_ERROR;
599 }
Kenny Roota91203b2012-02-15 15:00:46 -0800600 }
601
602 // data includes the value and the value's length
603 size_t dataLength = mBlob.length + sizeof(mBlob.length);
604 // pad data to the AES_BLOCK_SIZE
605 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
606 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
607 // encrypted data includes the digest value
608 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
609 // move info after space for padding
610 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
611 // zero padding area
612 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
613
614 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800615
Kenny Rootf9119d62013-04-03 09:22:15 -0700616 if (isEncrypted()) {
617 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800618
Kenny Rootf9119d62013-04-03 09:22:15 -0700619 uint8_t vector[AES_BLOCK_SIZE];
620 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
621 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
622 aes_key, vector, AES_ENCRYPT);
623 }
624
Kenny Roota91203b2012-02-15 15:00:46 -0800625 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
626 size_t fileLength = encryptedLength + headerLength + mBlob.info;
627
628 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800629 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
630 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
631 if (out < 0) {
632 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800633 return SYSTEM_ERROR;
634 }
635 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
636 if (close(out) != 0) {
637 return SYSTEM_ERROR;
638 }
639 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800640 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800641 unlink(tmpFileName);
642 return SYSTEM_ERROR;
643 }
Kenny Root150ca932012-11-14 14:29:02 -0800644 if (rename(tmpFileName, filename) == -1) {
645 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
646 return SYSTEM_ERROR;
647 }
648 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800649 }
650
Kenny Rootf9119d62013-04-03 09:22:15 -0700651 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
652 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800653 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
654 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800655 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
656 }
657 // fileLength may be less than sizeof(mBlob) since the in
658 // memory version has extra padding to tolerate rounding up to
659 // the AES_BLOCK_SIZE
660 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
661 if (close(in) != 0) {
662 return SYSTEM_ERROR;
663 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700664
665 if (isEncrypted() && (state != STATE_NO_ERROR)) {
666 return LOCKED;
667 }
668
Kenny Roota91203b2012-02-15 15:00:46 -0800669 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
670 if (fileLength < headerLength) {
671 return VALUE_CORRUPTED;
672 }
673
674 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700675 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800676 return VALUE_CORRUPTED;
677 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700678
679 ssize_t digestedLength;
680 if (isEncrypted()) {
681 if (encryptedLength % AES_BLOCK_SIZE != 0) {
682 return VALUE_CORRUPTED;
683 }
684
685 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
686 mBlob.vector, AES_DECRYPT);
687 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
688 uint8_t computedDigest[MD5_DIGEST_LENGTH];
689 MD5(mBlob.digested, digestedLength, computedDigest);
690 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
691 return VALUE_CORRUPTED;
692 }
693 } else {
694 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800695 }
696
697 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
698 mBlob.length = ntohl(mBlob.length);
699 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
700 return VALUE_CORRUPTED;
701 }
702 if (mBlob.info != 0) {
703 // move info from after padding to after data
704 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
705 }
Kenny Root07438c82012-11-02 15:41:02 -0700706 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800707 }
708
709private:
710 struct blob mBlob;
711};
712
Kenny Root655b9582013-04-04 08:37:42 -0700713class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800714public:
Kenny Root655b9582013-04-04 08:37:42 -0700715 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
716 asprintf(&mUserDir, "user_%u", mUserId);
717 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
718 }
719
720 ~UserState() {
721 free(mUserDir);
722 free(mMasterKeyFile);
723 }
724
725 bool initialize() {
726 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
727 ALOGE("Could not create directory '%s'", mUserDir);
728 return false;
729 }
730
731 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800732 setState(STATE_LOCKED);
733 } else {
734 setState(STATE_UNINITIALIZED);
735 }
Kenny Root70e3a862012-02-15 17:20:23 -0800736
Kenny Root655b9582013-04-04 08:37:42 -0700737 return true;
738 }
739
740 uid_t getUserId() const {
741 return mUserId;
742 }
743
744 const char* getUserDirName() const {
745 return mUserDir;
746 }
747
748 const char* getMasterKeyFileName() const {
749 return mMasterKeyFile;
750 }
751
752 void setState(State state) {
753 mState = state;
754 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
755 mRetry = MAX_RETRY;
756 }
Kenny Roota91203b2012-02-15 15:00:46 -0800757 }
758
Kenny Root51878182012-03-13 12:53:19 -0700759 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800760 return mState;
761 }
762
Kenny Root51878182012-03-13 12:53:19 -0700763 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800764 return mRetry;
765 }
766
Kenny Root655b9582013-04-04 08:37:42 -0700767 void zeroizeMasterKeysInMemory() {
768 memset(mMasterKey, 0, sizeof(mMasterKey));
769 memset(mSalt, 0, sizeof(mSalt));
770 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
771 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800772 }
773
Kenny Root655b9582013-04-04 08:37:42 -0700774 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
775 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800776 return SYSTEM_ERROR;
777 }
Kenny Root655b9582013-04-04 08:37:42 -0700778 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800779 if (response != NO_ERROR) {
780 return response;
781 }
782 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700783 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800784 }
785
Robin Lee4e865752014-08-19 17:37:55 +0100786 ResponseCode copyMasterKey(UserState* src) {
787 if (mState != STATE_UNINITIALIZED) {
788 return ::SYSTEM_ERROR;
789 }
790 if (src->getState() != STATE_NO_ERROR) {
791 return ::SYSTEM_ERROR;
792 }
793 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
794 setupMasterKeys();
795 return ::NO_ERROR;
796 }
797
Kenny Root655b9582013-04-04 08:37:42 -0700798 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800799 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
800 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
801 AES_KEY passwordAesKey;
802 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700803 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700804 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800805 }
806
Kenny Root655b9582013-04-04 08:37:42 -0700807 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
808 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800809 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800810 return SYSTEM_ERROR;
811 }
812
813 // we read the raw blob to just to get the salt to generate
814 // the AES key, then we create the Blob to use with decryptBlob
815 blob rawBlob;
816 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
817 if (close(in) != 0) {
818 return SYSTEM_ERROR;
819 }
820 // find salt at EOF if present, otherwise we have an old file
821 uint8_t* salt;
822 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
823 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
824 } else {
825 salt = NULL;
826 }
827 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
828 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
829 AES_KEY passwordAesKey;
830 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
831 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700832 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
833 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800834 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700835 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800836 }
837 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
838 // if salt was missing, generate one and write a new master key file with the salt.
839 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700840 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800841 return SYSTEM_ERROR;
842 }
Kenny Root655b9582013-04-04 08:37:42 -0700843 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800844 }
845 if (response == NO_ERROR) {
846 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
847 setupMasterKeys();
848 }
849 return response;
850 }
851 if (mRetry <= 0) {
852 reset();
853 return UNINITIALIZED;
854 }
855 --mRetry;
856 switch (mRetry) {
857 case 0: return WRONG_PASSWORD_0;
858 case 1: return WRONG_PASSWORD_1;
859 case 2: return WRONG_PASSWORD_2;
860 case 3: return WRONG_PASSWORD_3;
861 default: return WRONG_PASSWORD_3;
862 }
863 }
864
Kenny Root655b9582013-04-04 08:37:42 -0700865 AES_KEY* getEncryptionKey() {
866 return &mMasterKeyEncryption;
867 }
868
869 AES_KEY* getDecryptionKey() {
870 return &mMasterKeyDecryption;
871 }
872
Kenny Roota91203b2012-02-15 15:00:46 -0800873 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700874 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800875 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700876 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800877 return false;
878 }
Kenny Root655b9582013-04-04 08:37:42 -0700879
880 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800881 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700882 // We only care about files.
883 if (file->d_type != DT_REG) {
884 continue;
885 }
886
887 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700888 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700889 continue;
890 }
891
892 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800893 }
894 closedir(dir);
895 return true;
896 }
897
Kenny Root655b9582013-04-04 08:37:42 -0700898private:
899 static const int MASTER_KEY_SIZE_BYTES = 16;
900 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
901
902 static const int MAX_RETRY = 4;
903 static const size_t SALT_SIZE = 16;
904
905 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
906 uint8_t* salt) {
907 size_t saltSize;
908 if (salt != NULL) {
909 saltSize = SALT_SIZE;
910 } else {
911 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
912 salt = (uint8_t*) "keystore";
913 // sizeof = 9, not strlen = 8
914 saltSize = sizeof("keystore");
915 }
916
917 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
918 saltSize, 8192, keySize, key);
919 }
920
921 bool generateSalt(Entropy* entropy) {
922 return entropy->generate_random_data(mSalt, sizeof(mSalt));
923 }
924
925 bool generateMasterKey(Entropy* entropy) {
926 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
927 return false;
928 }
929 if (!generateSalt(entropy)) {
930 return false;
931 }
932 return true;
933 }
934
935 void setupMasterKeys() {
936 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
937 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
938 setState(STATE_NO_ERROR);
939 }
940
941 uid_t mUserId;
942
943 char* mUserDir;
944 char* mMasterKeyFile;
945
946 State mState;
947 int8_t mRetry;
948
949 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
950 uint8_t mSalt[SALT_SIZE];
951
952 AES_KEY mMasterKeyEncryption;
953 AES_KEY mMasterKeyDecryption;
954};
955
956typedef struct {
957 uint32_t uid;
958 const uint8_t* filename;
959} grant_t;
960
961class KeyStore {
962public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000963 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700964 : mEntropy(entropy)
965 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800966 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700967 {
968 memset(&mMetaData, '\0', sizeof(mMetaData));
969 }
970
971 ~KeyStore() {
972 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
973 it != mGrants.end(); it++) {
974 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700975 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800976 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700977
978 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
979 it != mMasterKeys.end(); it++) {
980 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700981 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800982 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700983 }
984
Chad Brubaker67d2a502015-03-11 17:21:18 +0000985 /**
986 * Depending on the hardware keymaster version is this may return a
987 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
988 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
989 * be guarded by a check on the device's version.
990 */
991 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700992 return mDevice;
993 }
994
Chad Brubaker67d2a502015-03-11 17:21:18 +0000995 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800996 return mFallbackDevice;
997 }
998
Chad Brubaker67d2a502015-03-11 17:21:18 +0000999 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001000 return blob.isFallback() ? mFallbackDevice: mDevice;
1001 }
1002
Kenny Root655b9582013-04-04 08:37:42 -07001003 ResponseCode initialize() {
1004 readMetaData();
1005 if (upgradeKeystore()) {
1006 writeMetaData();
1007 }
1008
1009 return ::NO_ERROR;
1010 }
1011
1012 State getState(uid_t uid) {
1013 return getUserState(uid)->getState();
1014 }
1015
1016 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1017 UserState* userState = getUserState(uid);
1018 return userState->initialize(pw, mEntropy);
1019 }
1020
Robin Lee4e865752014-08-19 17:37:55 +01001021 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1022 UserState *userState = getUserState(uid);
1023 UserState *initState = getUserState(src);
1024 return userState->copyMasterKey(initState);
1025 }
1026
Kenny Root655b9582013-04-04 08:37:42 -07001027 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001028 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001029 return userState->writeMasterKey(pw, mEntropy);
1030 }
1031
1032 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001033 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001034 return userState->readMasterKey(pw, mEntropy);
1035 }
1036
1037 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001038 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001039 encode_key(encoded, keyName);
1040 return android::String8(encoded);
1041 }
1042
1043 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001044 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001045 encode_key(encoded, keyName);
1046 return android::String8::format("%u_%s", uid, encoded);
1047 }
1048
1049 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001050 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001051 encode_key(encoded, keyName);
1052 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1053 encoded);
1054 }
1055
1056 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001057 android::String8 prefix("");
1058 android::Vector<android::String16> aliases;
1059 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1060 return ::SYSTEM_ERROR;
1061 }
1062
Kenny Root655b9582013-04-04 08:37:42 -07001063 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001064 for (uint32_t i = 0; i < aliases.size(); i++) {
1065 android::String8 filename(aliases[i]);
1066 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1067 getKeyName(filename).string());
1068 del(filename, ::TYPE_ANY, uid);
1069 }
1070
Kenny Root655b9582013-04-04 08:37:42 -07001071 userState->zeroizeMasterKeysInMemory();
1072 userState->setState(STATE_UNINITIALIZED);
1073 return userState->reset();
1074 }
1075
1076 bool isEmpty(uid_t uid) const {
1077 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001078 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001079 return true;
1080 }
1081
1082 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001083 if (!dir) {
1084 return true;
1085 }
Kenny Root31e27462014-09-10 11:28:03 -07001086
Kenny Roota91203b2012-02-15 15:00:46 -08001087 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001088 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001089 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001090 // We only care about files.
1091 if (file->d_type != DT_REG) {
1092 continue;
1093 }
1094
1095 // Skip anything that starts with a "."
1096 if (file->d_name[0] == '.') {
1097 continue;
1098 }
1099
Kenny Root31e27462014-09-10 11:28:03 -07001100 result = false;
1101 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001102 }
1103 closedir(dir);
1104 return result;
1105 }
1106
Kenny Root655b9582013-04-04 08:37:42 -07001107 void lock(uid_t uid) {
1108 UserState* userState = getUserState(uid);
1109 userState->zeroizeMasterKeysInMemory();
1110 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001111 }
1112
Kenny Root655b9582013-04-04 08:37:42 -07001113 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1114 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001115 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1116 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001117 if (rc != NO_ERROR) {
1118 return rc;
1119 }
1120
1121 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001122 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001123 /* If we upgrade the key, we need to write it to disk again. Then
1124 * it must be read it again since the blob is encrypted each time
1125 * it's written.
1126 */
Kenny Root655b9582013-04-04 08:37:42 -07001127 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1128 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001129 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1130 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001131 return rc;
1132 }
1133 }
Kenny Root822c3a92012-03-23 16:34:39 -07001134 }
1135
Kenny Root17208e02013-09-04 13:56:03 -07001136 /*
1137 * This will upgrade software-backed keys to hardware-backed keys when
1138 * the HAL for the device supports the newer key types.
1139 */
1140 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1141 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1142 && keyBlob->isFallback()) {
1143 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1144 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1145
1146 // The HAL allowed the import, reget the key to have the "fresh"
1147 // version.
1148 if (imported == NO_ERROR) {
1149 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1150 }
1151 }
1152
Kenny Rootd53bc922013-03-21 14:10:15 -07001153 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001154 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1155 return KEY_NOT_FOUND;
1156 }
1157
1158 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001159 }
1160
Kenny Root655b9582013-04-04 08:37:42 -07001161 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1162 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001163 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1164 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001165 }
1166
Robin Lee4b84fdc2014-09-24 11:56:57 +01001167 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1168 Blob keyBlob;
1169 ResponseCode rc = get(filename, &keyBlob, type, uid);
1170 if (rc != ::NO_ERROR) {
1171 return rc;
1172 }
1173
1174 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1175 // A device doesn't have to implement delete_keypair.
1176 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1177 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1178 rc = ::SYSTEM_ERROR;
1179 }
1180 }
1181 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001182 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1183 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1184 if (dev->delete_key) {
1185 keymaster_key_blob_t blob;
1186 blob.key_material = keyBlob.getValue();
1187 blob.key_material_size = keyBlob.getLength();
1188 dev->delete_key(dev, &blob);
1189 }
1190 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001191 if (rc != ::NO_ERROR) {
1192 return rc;
1193 }
1194
1195 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1196 }
1197
1198 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1199 uid_t uid) {
1200
1201 UserState* userState = getUserState(uid);
1202 size_t n = prefix.length();
1203
1204 DIR* dir = opendir(userState->getUserDirName());
1205 if (!dir) {
1206 ALOGW("can't open directory for user: %s", strerror(errno));
1207 return ::SYSTEM_ERROR;
1208 }
1209
1210 struct dirent* file;
1211 while ((file = readdir(dir)) != NULL) {
1212 // We only care about files.
1213 if (file->d_type != DT_REG) {
1214 continue;
1215 }
1216
1217 // Skip anything that starts with a "."
1218 if (file->d_name[0] == '.') {
1219 continue;
1220 }
1221
1222 if (!strncmp(prefix.string(), file->d_name, n)) {
1223 const char* p = &file->d_name[n];
1224 size_t plen = strlen(p);
1225
1226 size_t extra = decode_key_length(p, plen);
1227 char *match = (char*) malloc(extra + 1);
1228 if (match != NULL) {
1229 decode_key(match, p, plen);
1230 matches->push(android::String16(match, extra));
1231 free(match);
1232 } else {
1233 ALOGW("could not allocate match of size %zd", extra);
1234 }
1235 }
1236 }
1237 closedir(dir);
1238 return ::NO_ERROR;
1239 }
1240
Kenny Root07438c82012-11-02 15:41:02 -07001241 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001242 const grant_t* existing = getGrant(filename, granteeUid);
1243 if (existing == NULL) {
1244 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001245 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001246 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001247 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001248 }
1249 }
1250
Kenny Root07438c82012-11-02 15:41:02 -07001251 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001252 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1253 it != mGrants.end(); it++) {
1254 grant_t* grant = *it;
1255 if (grant->uid == granteeUid
1256 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1257 mGrants.erase(it);
1258 return true;
1259 }
Kenny Root70e3a862012-02-15 17:20:23 -08001260 }
Kenny Root70e3a862012-02-15 17:20:23 -08001261 return false;
1262 }
1263
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001264 bool hasGrant(const char* filename, const uid_t uid) const {
1265 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001266 }
1267
Kenny Rootf9119d62013-04-03 09:22:15 -07001268 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1269 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001270 uint8_t* data;
1271 size_t dataLength;
1272 int rc;
1273
1274 if (mDevice->import_keypair == NULL) {
1275 ALOGE("Keymaster doesn't support import!");
1276 return SYSTEM_ERROR;
1277 }
1278
Kenny Root17208e02013-09-04 13:56:03 -07001279 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001280 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001281 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001282 /*
1283 * Maybe the device doesn't support this type of key. Try to use the
1284 * software fallback keymaster implementation. This is a little bit
1285 * lazier than checking the PKCS#8 key type, but the software
1286 * implementation will do that anyway.
1287 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001288 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001289 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001290
1291 if (rc) {
1292 ALOGE("Error while importing keypair: %d", rc);
1293 return SYSTEM_ERROR;
1294 }
Kenny Root822c3a92012-03-23 16:34:39 -07001295 }
1296
1297 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1298 free(data);
1299
Kenny Rootf9119d62013-04-03 09:22:15 -07001300 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001301 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001302
Kenny Root655b9582013-04-04 08:37:42 -07001303 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001304 }
1305
Kenny Root1b0e3932013-09-05 13:06:32 -07001306 bool isHardwareBacked(const android::String16& keyType) const {
1307 if (mDevice == NULL) {
1308 ALOGW("can't get keymaster device");
1309 return false;
1310 }
1311
1312 if (sRSAKeyType == keyType) {
1313 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1314 } else {
1315 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1316 && (mDevice->common.module->module_api_version
1317 >= KEYMASTER_MODULE_API_VERSION_0_2);
1318 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001319 }
1320
Kenny Root655b9582013-04-04 08:37:42 -07001321 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1322 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001323 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001324
1325 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1326 if (responseCode == NO_ERROR) {
1327 return responseCode;
1328 }
1329
1330 // If this is one of the legacy UID->UID mappings, use it.
1331 uid_t euid = get_keystore_euid(uid);
1332 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001333 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001334 responseCode = get(filepath8.string(), keyBlob, type, uid);
1335 if (responseCode == NO_ERROR) {
1336 return responseCode;
1337 }
1338 }
1339
1340 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001341 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001342 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001343 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001344 if (end[0] != '_' || end[1] == 0) {
1345 return KEY_NOT_FOUND;
1346 }
Kenny Root86b16e82013-09-09 11:15:54 -07001347 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1348 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001349 if (!hasGrant(filepath8.string(), uid)) {
1350 return responseCode;
1351 }
1352
1353 // It is a granted key. Try to load it.
1354 return get(filepath8.string(), keyBlob, type, uid);
1355 }
1356
1357 /**
1358 * Returns any existing UserState or creates it if it doesn't exist.
1359 */
1360 UserState* getUserState(uid_t uid) {
1361 uid_t userId = get_user_id(uid);
1362
1363 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1364 it != mMasterKeys.end(); it++) {
1365 UserState* state = *it;
1366 if (state->getUserId() == userId) {
1367 return state;
1368 }
1369 }
1370
1371 UserState* userState = new UserState(userId);
1372 if (!userState->initialize()) {
1373 /* There's not much we can do if initialization fails. Trying to
1374 * unlock the keystore for that user will fail as well, so any
1375 * subsequent request for this user will just return SYSTEM_ERROR.
1376 */
1377 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1378 }
1379 mMasterKeys.add(userState);
1380 return userState;
1381 }
1382
1383 /**
1384 * Returns NULL if the UserState doesn't already exist.
1385 */
1386 const UserState* getUserState(uid_t uid) const {
1387 uid_t userId = get_user_id(uid);
1388
1389 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1390 it != mMasterKeys.end(); it++) {
1391 UserState* state = *it;
1392 if (state->getUserId() == userId) {
1393 return state;
1394 }
1395 }
1396
1397 return NULL;
1398 }
1399
Kenny Roota91203b2012-02-15 15:00:46 -08001400private:
Kenny Root655b9582013-04-04 08:37:42 -07001401 static const char* sOldMasterKey;
1402 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001403 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001404 Entropy* mEntropy;
1405
Chad Brubaker67d2a502015-03-11 17:21:18 +00001406 keymaster1_device_t* mDevice;
1407 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001408
Kenny Root655b9582013-04-04 08:37:42 -07001409 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001410
Kenny Root655b9582013-04-04 08:37:42 -07001411 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001412
Kenny Root655b9582013-04-04 08:37:42 -07001413 typedef struct {
1414 uint32_t version;
1415 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001416
Kenny Root655b9582013-04-04 08:37:42 -07001417 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001418
Kenny Root655b9582013-04-04 08:37:42 -07001419 const grant_t* getGrant(const char* filename, uid_t uid) const {
1420 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1421 it != mGrants.end(); it++) {
1422 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001423 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001424 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001425 return grant;
1426 }
1427 }
Kenny Root70e3a862012-02-15 17:20:23 -08001428 return NULL;
1429 }
1430
Kenny Root822c3a92012-03-23 16:34:39 -07001431 /**
1432 * Upgrade code. This will upgrade the key from the current version
1433 * to whatever is newest.
1434 */
Kenny Root655b9582013-04-04 08:37:42 -07001435 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1436 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001437 bool updated = false;
1438 uint8_t version = oldVersion;
1439
1440 /* From V0 -> V1: All old types were unknown */
1441 if (version == 0) {
1442 ALOGV("upgrading to version 1 and setting type %d", type);
1443
1444 blob->setType(type);
1445 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001446 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001447 }
1448 version = 1;
1449 updated = true;
1450 }
1451
Kenny Rootf9119d62013-04-03 09:22:15 -07001452 /* From V1 -> V2: All old keys were encrypted */
1453 if (version == 1) {
1454 ALOGV("upgrading to version 2");
1455
1456 blob->setEncrypted(true);
1457 version = 2;
1458 updated = true;
1459 }
1460
Kenny Root822c3a92012-03-23 16:34:39 -07001461 /*
1462 * If we've updated, set the key blob to the right version
1463 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001464 */
Kenny Root822c3a92012-03-23 16:34:39 -07001465 if (updated) {
1466 ALOGV("updated and writing file %s", filename);
1467 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001468 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001469
1470 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001471 }
1472
1473 /**
1474 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1475 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1476 * Then it overwrites the original blob with the new blob
1477 * format that is returned from the keymaster.
1478 */
Kenny Root655b9582013-04-04 08:37:42 -07001479 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001480 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1481 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1482 if (b.get() == NULL) {
1483 ALOGE("Problem instantiating BIO");
1484 return SYSTEM_ERROR;
1485 }
1486
1487 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1488 if (pkey.get() == NULL) {
1489 ALOGE("Couldn't read old PEM file");
1490 return SYSTEM_ERROR;
1491 }
1492
1493 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1494 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1495 if (len < 0) {
1496 ALOGE("Couldn't measure PKCS#8 length");
1497 return SYSTEM_ERROR;
1498 }
1499
Kenny Root70c98892013-02-07 09:10:36 -08001500 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1501 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001502 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1503 ALOGE("Couldn't convert to PKCS#8");
1504 return SYSTEM_ERROR;
1505 }
1506
Kenny Rootf9119d62013-04-03 09:22:15 -07001507 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1508 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001509 if (rc != NO_ERROR) {
1510 return rc;
1511 }
1512
Kenny Root655b9582013-04-04 08:37:42 -07001513 return get(filename, blob, TYPE_KEY_PAIR, uid);
1514 }
1515
1516 void readMetaData() {
1517 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1518 if (in < 0) {
1519 return;
1520 }
1521 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1522 if (fileLength != sizeof(mMetaData)) {
1523 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1524 sizeof(mMetaData));
1525 }
1526 close(in);
1527 }
1528
1529 void writeMetaData() {
1530 const char* tmpFileName = ".metadata.tmp";
1531 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1532 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1533 if (out < 0) {
1534 ALOGE("couldn't write metadata file: %s", strerror(errno));
1535 return;
1536 }
1537 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1538 if (fileLength != sizeof(mMetaData)) {
1539 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1540 sizeof(mMetaData));
1541 }
1542 close(out);
1543 rename(tmpFileName, sMetaDataFile);
1544 }
1545
1546 bool upgradeKeystore() {
1547 bool upgraded = false;
1548
1549 if (mMetaData.version == 0) {
1550 UserState* userState = getUserState(0);
1551
1552 // Initialize first so the directory is made.
1553 userState->initialize();
1554
1555 // Migrate the old .masterkey file to user 0.
1556 if (access(sOldMasterKey, R_OK) == 0) {
1557 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1558 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1559 return false;
1560 }
1561 }
1562
1563 // Initialize again in case we had a key.
1564 userState->initialize();
1565
1566 // Try to migrate existing keys.
1567 DIR* dir = opendir(".");
1568 if (!dir) {
1569 // Give up now; maybe we can upgrade later.
1570 ALOGE("couldn't open keystore's directory; something is wrong");
1571 return false;
1572 }
1573
1574 struct dirent* file;
1575 while ((file = readdir(dir)) != NULL) {
1576 // We only care about files.
1577 if (file->d_type != DT_REG) {
1578 continue;
1579 }
1580
1581 // Skip anything that starts with a "."
1582 if (file->d_name[0] == '.') {
1583 continue;
1584 }
1585
1586 // Find the current file's user.
1587 char* end;
1588 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1589 if (end[0] != '_' || end[1] == 0) {
1590 continue;
1591 }
1592 UserState* otherUser = getUserState(thisUid);
1593 if (otherUser->getUserId() != 0) {
1594 unlinkat(dirfd(dir), file->d_name, 0);
1595 }
1596
1597 // Rename the file into user directory.
1598 DIR* otherdir = opendir(otherUser->getUserDirName());
1599 if (otherdir == NULL) {
1600 ALOGW("couldn't open user directory for rename");
1601 continue;
1602 }
1603 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1604 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1605 }
1606 closedir(otherdir);
1607 }
1608 closedir(dir);
1609
1610 mMetaData.version = 1;
1611 upgraded = true;
1612 }
1613
1614 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001615 }
Kenny Roota91203b2012-02-15 15:00:46 -08001616};
1617
Kenny Root655b9582013-04-04 08:37:42 -07001618const char* KeyStore::sOldMasterKey = ".masterkey";
1619const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001620
Kenny Root1b0e3932013-09-05 13:06:32 -07001621const android::String16 KeyStore::sRSAKeyType("RSA");
1622
Kenny Root07438c82012-11-02 15:41:02 -07001623namespace android {
1624class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1625public:
1626 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001627 : mKeyStore(keyStore),
1628 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001629 {
Kenny Roota91203b2012-02-15 15:00:46 -08001630 }
Kenny Roota91203b2012-02-15 15:00:46 -08001631
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001632 void binderDied(const wp<IBinder>& who) {
1633 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1634 for (auto token: operations) {
1635 abort(token);
1636 }
Kenny Root822c3a92012-03-23 16:34:39 -07001637 }
Kenny Roota91203b2012-02-15 15:00:46 -08001638
Kenny Root07438c82012-11-02 15:41:02 -07001639 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001640 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001641 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001642 }
Kenny Roota91203b2012-02-15 15:00:46 -08001643
Chad Brubaker9489b792015-04-14 11:01:45 -07001644 return mKeyStore->getState(IPCThreadState::self()->getCallingUid());
Kenny Root298e7b12012-03-26 13:54:44 -07001645 }
1646
Kenny Root07438c82012-11-02 15:41:02 -07001647 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001648 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001649 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001650 }
Kenny Root07438c82012-11-02 15:41:02 -07001651
Chad Brubaker9489b792015-04-14 11:01:45 -07001652 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001653 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001654 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001655
Kenny Root655b9582013-04-04 08:37:42 -07001656 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001657 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001658 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001659 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001660 *item = NULL;
1661 *itemLength = 0;
1662 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001663 }
Kenny Roota91203b2012-02-15 15:00:46 -08001664
Kenny Root07438c82012-11-02 15:41:02 -07001665 *item = (uint8_t*) malloc(keyBlob.getLength());
1666 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1667 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001668
Kenny Root07438c82012-11-02 15:41:02 -07001669 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001670 }
1671
Kenny Rootf9119d62013-04-03 09:22:15 -07001672 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1673 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001674 targetUid = getEffectiveUid(targetUid);
1675 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1676 flags & KEYSTORE_FLAG_ENCRYPTED);
1677 if (result != ::NO_ERROR) {
1678 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001679 }
1680
Kenny Root07438c82012-11-02 15:41:02 -07001681 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001682 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001683
1684 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001685 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1686
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001687 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001688 }
1689
Kenny Root49468902013-03-19 13:41:33 -07001690 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001691 targetUid = getEffectiveUid(targetUid);
1692 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001693 return ::PERMISSION_DENIED;
1694 }
Kenny Root07438c82012-11-02 15:41:02 -07001695 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001696 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001697 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001698 }
1699
Kenny Root49468902013-03-19 13:41:33 -07001700 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001701 targetUid = getEffectiveUid(targetUid);
1702 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001703 return ::PERMISSION_DENIED;
1704 }
1705
Kenny Root07438c82012-11-02 15:41:02 -07001706 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001707 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001708
Kenny Root655b9582013-04-04 08:37:42 -07001709 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001710 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1711 }
1712 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001713 }
1714
Kenny Root49468902013-03-19 13:41:33 -07001715 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001716 targetUid = getEffectiveUid(targetUid);
1717 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001718 return ::PERMISSION_DENIED;
1719 }
Kenny Root07438c82012-11-02 15:41:02 -07001720 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001721 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001722
Robin Lee4b84fdc2014-09-24 11:56:57 +01001723 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1724 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001725 }
Kenny Root07438c82012-11-02 15:41:02 -07001726 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001727 }
1728
Kenny Root07438c82012-11-02 15:41:02 -07001729 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001730 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001731 return ::PERMISSION_DENIED;
1732 }
1733
Chad Brubaker9489b792015-04-14 11:01:45 -07001734 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01001735 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001736 }
1737
Kenny Root07438c82012-11-02 15:41:02 -07001738 /*
1739 * Here is the history. To improve the security, the parameters to generate the
1740 * master key has been changed. To make a seamless transition, we update the
1741 * file using the same password when the user unlock it for the first time. If
1742 * any thing goes wrong during the transition, the new file will not overwrite
1743 * the old one. This avoids permanent damages of the existing data.
1744 */
1745 int32_t password(const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001746 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001747 return ::PERMISSION_DENIED;
1748 }
Kenny Root70e3a862012-02-15 17:20:23 -08001749
Kenny Root07438c82012-11-02 15:41:02 -07001750 const String8 password8(password);
Chad Brubaker9489b792015-04-14 11:01:45 -07001751 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root70e3a862012-02-15 17:20:23 -08001752
Kenny Root655b9582013-04-04 08:37:42 -07001753 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001754 case ::STATE_UNINITIALIZED: {
1755 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001756 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001757 }
1758 case ::STATE_NO_ERROR: {
1759 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001760 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001761 }
1762 case ::STATE_LOCKED: {
1763 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001764 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001765 }
1766 }
1767 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001768 }
1769
Kenny Root07438c82012-11-02 15:41:02 -07001770 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001771 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001772 return ::PERMISSION_DENIED;
1773 }
Kenny Root70e3a862012-02-15 17:20:23 -08001774
Chad Brubaker9489b792015-04-14 11:01:45 -07001775 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001776 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001777 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001778 ALOGD("calling lock in state: %d", state);
1779 return state;
1780 }
1781
Kenny Root655b9582013-04-04 08:37:42 -07001782 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001783 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001784 }
1785
Kenny Root07438c82012-11-02 15:41:02 -07001786 int32_t unlock(const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001787 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001788 return ::PERMISSION_DENIED;
1789 }
1790
Chad Brubaker9489b792015-04-14 11:01:45 -07001791 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001792 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001793 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001794 ALOGD("calling unlock when not locked");
1795 return state;
1796 }
1797
1798 const String8 password8(pw);
1799 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001800 }
1801
Kenny Root07438c82012-11-02 15:41:02 -07001802 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001803 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001804 return -1;
1805 }
Kenny Root70e3a862012-02-15 17:20:23 -08001806
Chad Brubaker9489b792015-04-14 11:01:45 -07001807 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001808 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001809 }
1810
Kenny Root96427ba2013-08-16 14:02:41 -07001811 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1812 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001813 targetUid = getEffectiveUid(targetUid);
1814 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1815 flags & KEYSTORE_FLAG_ENCRYPTED);
1816 if (result != ::NO_ERROR) {
1817 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001818 }
Kenny Root07438c82012-11-02 15:41:02 -07001819 uint8_t* data;
1820 size_t dataLength;
1821 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001822 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001823
Chad Brubaker67d2a502015-03-11 17:21:18 +00001824 const keymaster1_device_t* device = mKeyStore->getDevice();
1825 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001826 if (device == NULL) {
1827 return ::SYSTEM_ERROR;
1828 }
1829
1830 if (device->generate_keypair == NULL) {
1831 return ::SYSTEM_ERROR;
1832 }
1833
Kenny Root17208e02013-09-04 13:56:03 -07001834 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001835 keymaster_dsa_keygen_params_t dsa_params;
1836 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001837
Kenny Root96427ba2013-08-16 14:02:41 -07001838 if (keySize == -1) {
1839 keySize = DSA_DEFAULT_KEY_SIZE;
1840 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1841 || keySize > DSA_MAX_KEY_SIZE) {
1842 ALOGI("invalid key size %d", keySize);
1843 return ::SYSTEM_ERROR;
1844 }
1845 dsa_params.key_size = keySize;
1846
1847 if (args->size() == 3) {
1848 sp<KeystoreArg> gArg = args->itemAt(0);
1849 sp<KeystoreArg> pArg = args->itemAt(1);
1850 sp<KeystoreArg> qArg = args->itemAt(2);
1851
1852 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1853 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1854 dsa_params.generator_len = gArg->size();
1855
1856 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1857 dsa_params.prime_p_len = pArg->size();
1858
1859 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1860 dsa_params.prime_q_len = qArg->size();
1861 } else {
1862 ALOGI("not all DSA parameters were read");
1863 return ::SYSTEM_ERROR;
1864 }
1865 } else if (args->size() != 0) {
1866 ALOGI("DSA args must be 3");
1867 return ::SYSTEM_ERROR;
1868 }
1869
Kenny Root1d448c02013-11-21 10:36:53 -08001870 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001871 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1872 } else {
1873 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001874 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1875 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001876 }
1877 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001878 keymaster_ec_keygen_params_t ec_params;
1879 memset(&ec_params, '\0', sizeof(ec_params));
1880
1881 if (keySize == -1) {
1882 keySize = EC_DEFAULT_KEY_SIZE;
1883 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1884 ALOGI("invalid key size %d", keySize);
1885 return ::SYSTEM_ERROR;
1886 }
1887 ec_params.field_size = keySize;
1888
Kenny Root1d448c02013-11-21 10:36:53 -08001889 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001890 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1891 } else {
1892 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001893 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001894 }
Kenny Root96427ba2013-08-16 14:02:41 -07001895 } else if (keyType == EVP_PKEY_RSA) {
1896 keymaster_rsa_keygen_params_t rsa_params;
1897 memset(&rsa_params, '\0', sizeof(rsa_params));
1898 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1899
1900 if (keySize == -1) {
1901 keySize = RSA_DEFAULT_KEY_SIZE;
1902 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1903 ALOGI("invalid key size %d", keySize);
1904 return ::SYSTEM_ERROR;
1905 }
1906 rsa_params.modulus_size = keySize;
1907
1908 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001909 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001910 return ::SYSTEM_ERROR;
1911 } else if (args->size() == 1) {
1912 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1913 if (pubExpBlob != NULL) {
1914 Unique_BIGNUM pubExpBn(
1915 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1916 pubExpBlob->size(), NULL));
1917 if (pubExpBn.get() == NULL) {
1918 ALOGI("Could not convert public exponent to BN");
1919 return ::SYSTEM_ERROR;
1920 }
1921 unsigned long pubExp = BN_get_word(pubExpBn.get());
1922 if (pubExp == 0xFFFFFFFFL) {
1923 ALOGI("cannot represent public exponent as a long value");
1924 return ::SYSTEM_ERROR;
1925 }
1926 rsa_params.public_exponent = pubExp;
1927 }
1928 }
1929
1930 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1931 } else {
1932 ALOGW("Unsupported key type %d", keyType);
1933 rc = -1;
1934 }
1935
Kenny Root07438c82012-11-02 15:41:02 -07001936 if (rc) {
1937 return ::SYSTEM_ERROR;
1938 }
1939
Kenny Root655b9582013-04-04 08:37:42 -07001940 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07001941 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001942
1943 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1944 free(data);
1945
Kenny Rootee8068b2013-10-07 09:49:15 -07001946 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001947 keyBlob.setFallback(isFallback);
1948
Chad Brubaker9489b792015-04-14 11:01:45 -07001949 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001950 }
1951
Kenny Rootf9119d62013-04-03 09:22:15 -07001952 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1953 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001954 targetUid = getEffectiveUid(targetUid);
1955 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1956 flags & KEYSTORE_FLAG_ENCRYPTED);
1957 if (result != ::NO_ERROR) {
1958 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001959 }
Kenny Root07438c82012-11-02 15:41:02 -07001960 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001961 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001962
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001963 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001964 }
1965
Kenny Root07438c82012-11-02 15:41:02 -07001966 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1967 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001968 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07001969 return ::PERMISSION_DENIED;
1970 }
Kenny Root07438c82012-11-02 15:41:02 -07001971
Chad Brubaker9489b792015-04-14 11:01:45 -07001972 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001973 Blob keyBlob;
1974 String8 name8(name);
1975
Kenny Rootd38a0b02013-02-13 12:59:14 -08001976 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001977
Kenny Root655b9582013-04-04 08:37:42 -07001978 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001979 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001980 if (responseCode != ::NO_ERROR) {
1981 return responseCode;
1982 }
1983
Chad Brubaker67d2a502015-03-11 17:21:18 +00001984 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07001985 if (device == NULL) {
1986 ALOGE("no keymaster device; cannot sign");
1987 return ::SYSTEM_ERROR;
1988 }
1989
1990 if (device->sign_data == NULL) {
1991 ALOGE("device doesn't implement signing");
1992 return ::SYSTEM_ERROR;
1993 }
1994
1995 keymaster_rsa_sign_params_t params;
1996 params.digest_type = DIGEST_NONE;
1997 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07001998 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001999 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002000 if (rc) {
2001 ALOGW("device couldn't sign data");
2002 return ::SYSTEM_ERROR;
2003 }
2004
2005 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002006 }
2007
Kenny Root07438c82012-11-02 15:41:02 -07002008 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2009 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002010 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002011 return ::PERMISSION_DENIED;
2012 }
Kenny Root70e3a862012-02-15 17:20:23 -08002013
Chad Brubaker9489b792015-04-14 11:01:45 -07002014 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002015 Blob keyBlob;
2016 String8 name8(name);
2017 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002018
Kenny Root655b9582013-04-04 08:37:42 -07002019 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002020 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002021 if (responseCode != ::NO_ERROR) {
2022 return responseCode;
2023 }
Kenny Root70e3a862012-02-15 17:20:23 -08002024
Chad Brubaker67d2a502015-03-11 17:21:18 +00002025 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002026 if (device == NULL) {
2027 return ::SYSTEM_ERROR;
2028 }
Kenny Root70e3a862012-02-15 17:20:23 -08002029
Kenny Root07438c82012-11-02 15:41:02 -07002030 if (device->verify_data == NULL) {
2031 return ::SYSTEM_ERROR;
2032 }
Kenny Root70e3a862012-02-15 17:20:23 -08002033
Kenny Root07438c82012-11-02 15:41:02 -07002034 keymaster_rsa_sign_params_t params;
2035 params.digest_type = DIGEST_NONE;
2036 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002037
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002038 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2039 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002040 if (rc) {
2041 return ::SYSTEM_ERROR;
2042 } else {
2043 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002044 }
2045 }
Kenny Root07438c82012-11-02 15:41:02 -07002046
2047 /*
2048 * TODO: The abstraction between things stored in hardware and regular blobs
2049 * of data stored on the filesystem should be moved down to keystore itself.
2050 * Unfortunately the Java code that calls this has naming conventions that it
2051 * knows about. Ideally keystore shouldn't be used to store random blobs of
2052 * data.
2053 *
2054 * Until that happens, it's necessary to have a separate "get_pubkey" and
2055 * "del_key" since the Java code doesn't really communicate what it's
2056 * intentions are.
2057 */
2058 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002059 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002060 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002061 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002062 return ::PERMISSION_DENIED;
2063 }
Kenny Root07438c82012-11-02 15:41:02 -07002064
Kenny Root07438c82012-11-02 15:41:02 -07002065 Blob keyBlob;
2066 String8 name8(name);
2067
Kenny Rootd38a0b02013-02-13 12:59:14 -08002068 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002069
Kenny Root655b9582013-04-04 08:37:42 -07002070 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002071 TYPE_KEY_PAIR);
2072 if (responseCode != ::NO_ERROR) {
2073 return responseCode;
2074 }
2075
Chad Brubaker67d2a502015-03-11 17:21:18 +00002076 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002077 if (device == NULL) {
2078 return ::SYSTEM_ERROR;
2079 }
2080
2081 if (device->get_keypair_public == NULL) {
2082 ALOGE("device has no get_keypair_public implementation!");
2083 return ::SYSTEM_ERROR;
2084 }
2085
Kenny Root17208e02013-09-04 13:56:03 -07002086 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002087 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2088 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002089 if (rc) {
2090 return ::SYSTEM_ERROR;
2091 }
2092
2093 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002094 }
Kenny Root07438c82012-11-02 15:41:02 -07002095
Kenny Root49468902013-03-19 13:41:33 -07002096 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002097 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002098 }
2099
2100 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002101 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002102 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2103 if (result != ::NO_ERROR) {
2104 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002105 }
2106
2107 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002108 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002109
Kenny Root655b9582013-04-04 08:37:42 -07002110 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002111 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2112 }
2113
Kenny Root655b9582013-04-04 08:37:42 -07002114 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002115 return ::NO_ERROR;
2116 }
2117
2118 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002119 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002120 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2121 if (result != ::NO_ERROR) {
2122 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002123 }
2124
2125 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002126 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002127
Kenny Root655b9582013-04-04 08:37:42 -07002128 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002129 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2130 }
2131
Kenny Root655b9582013-04-04 08:37:42 -07002132 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002133 }
2134
2135 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002136 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002137 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002138 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002139 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002140 }
Kenny Root07438c82012-11-02 15:41:02 -07002141
2142 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002143 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002144
Kenny Root655b9582013-04-04 08:37:42 -07002145 if (access(filename.string(), R_OK) == -1) {
2146 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002147 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002148 }
2149
Kenny Root655b9582013-04-04 08:37:42 -07002150 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002151 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002152 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002153 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002154 }
2155
2156 struct stat s;
2157 int ret = fstat(fd, &s);
2158 close(fd);
2159 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002160 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002161 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002162 }
2163
Kenny Root36a9e232013-02-04 14:24:15 -08002164 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002165 }
2166
Kenny Rootd53bc922013-03-21 14:10:15 -07002167 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2168 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002169 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002170 pid_t spid = IPCThreadState::self()->getCallingPid();
2171 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002172 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002173 return -1L;
2174 }
2175
Kenny Root655b9582013-04-04 08:37:42 -07002176 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002177 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002178 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002179 return state;
2180 }
2181
Kenny Rootd53bc922013-03-21 14:10:15 -07002182 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2183 srcUid = callingUid;
2184 } else if (!is_granted_to(callingUid, srcUid)) {
2185 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002186 return ::PERMISSION_DENIED;
2187 }
2188
Kenny Rootd53bc922013-03-21 14:10:15 -07002189 if (destUid == -1) {
2190 destUid = callingUid;
2191 }
2192
2193 if (srcUid != destUid) {
2194 if (static_cast<uid_t>(srcUid) != callingUid) {
2195 ALOGD("can only duplicate from caller to other or to same uid: "
2196 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2197 return ::PERMISSION_DENIED;
2198 }
2199
2200 if (!is_granted_to(callingUid, destUid)) {
2201 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2202 return ::PERMISSION_DENIED;
2203 }
2204 }
2205
2206 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002207 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002208
Kenny Rootd53bc922013-03-21 14:10:15 -07002209 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002210 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002211
Kenny Root655b9582013-04-04 08:37:42 -07002212 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2213 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002214 return ::SYSTEM_ERROR;
2215 }
2216
Kenny Rootd53bc922013-03-21 14:10:15 -07002217 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002218 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002219 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002220 if (responseCode != ::NO_ERROR) {
2221 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002222 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002223
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002224 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002225 }
2226
Kenny Root1b0e3932013-09-05 13:06:32 -07002227 int32_t is_hardware_backed(const String16& keyType) {
2228 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002229 }
2230
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002231 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002232 uid_t targetUid = getEffectiveUid(targetUid64);
2233 if (!checkBinderPermission(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002234 return ::PERMISSION_DENIED;
2235 }
2236
Robin Lee4b84fdc2014-09-24 11:56:57 +01002237 String8 prefix = String8::format("%u_", targetUid);
2238 Vector<String16> aliases;
2239 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002240 return ::SYSTEM_ERROR;
2241 }
2242
Robin Lee4b84fdc2014-09-24 11:56:57 +01002243 for (uint32_t i = 0; i < aliases.size(); i++) {
2244 String8 name8(aliases[i]);
2245 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2246 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002247 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002248 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002249 }
2250
Robin Lee4b84fdc2014-09-24 11:56:57 +01002251 int32_t reset_uid(int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002252 targetUid = getEffectiveUid(targetUid);
2253 if (!checkBinderPermission(P_RESET_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002254 return ::PERMISSION_DENIED;
2255 }
Chad Brubakerbbc76482015-04-16 15:16:44 -07002256 // Flush the auth token table to prevent stale tokens from sticking
2257 // around.
2258 mAuthTokenTable.Clear();
Robin Lee4e865752014-08-19 17:37:55 +01002259
Robin Lee4b84fdc2014-09-24 11:56:57 +01002260 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002261 }
2262
2263 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002264 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002265 return ::PERMISSION_DENIED;
2266 }
Chad Brubaker9489b792015-04-14 11:01:45 -07002267
Robin Lee4e865752014-08-19 17:37:55 +01002268 if (sourceUid == targetUid) {
2269 return ::SYSTEM_ERROR;
2270 }
2271
2272 // Initialise user keystore with existing master key held in-memory
2273 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2274 }
2275
2276 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002277 targetUid = getEffectiveUid(targetUid);
2278 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002279 return ::PERMISSION_DENIED;
2280 }
Robin Lee4e865752014-08-19 17:37:55 +01002281 const String8 password8(pw);
2282
2283 switch (mKeyStore->getState(targetUid)) {
2284 case ::STATE_UNINITIALIZED: {
2285 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2286 return mKeyStore->initializeUser(password8, targetUid);
2287 }
2288 case ::STATE_NO_ERROR: {
2289 // rewrite master key with new password.
2290 return mKeyStore->writeMasterKey(password8, targetUid);
2291 }
2292 case ::STATE_LOCKED: {
2293 // read master key, decrypt with password, initialize mMasterKey*.
2294 return mKeyStore->readMasterKey(password8, targetUid);
2295 }
2296 }
2297 return ::SYSTEM_ERROR;
2298 }
2299
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002300 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2301 const keymaster1_device_t* device = mKeyStore->getDevice();
2302 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2303 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2304 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2305 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2306 device->add_rng_entropy != NULL) {
2307 devResult = device->add_rng_entropy(device, data, dataLength);
2308 }
2309 if (fallback->add_rng_entropy) {
2310 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2311 }
2312 if (devResult) {
2313 return devResult;
2314 }
2315 if (fallbackResult) {
2316 return fallbackResult;
2317 }
2318 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002319 }
2320
Chad Brubaker17d68b92015-02-05 22:04:16 -08002321 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002322 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2323 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002324 uid = getEffectiveUid(uid);
2325 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2326 flags & KEYSTORE_FLAG_ENCRYPTED);
2327 if (rc != ::NO_ERROR) {
2328 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002329 }
2330
Chad Brubaker9489b792015-04-14 11:01:45 -07002331 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002332 bool isFallback = false;
2333 keymaster_key_blob_t blob;
2334 keymaster_key_characteristics_t *out = NULL;
2335
2336 const keymaster1_device_t* device = mKeyStore->getDevice();
2337 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2338 if (device == NULL) {
2339 return ::SYSTEM_ERROR;
2340 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002341 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002342 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2343 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002344 if (!entropy) {
2345 rc = KM_ERROR_OK;
2346 } else if (device->add_rng_entropy) {
2347 rc = device->add_rng_entropy(device, entropy, entropyLength);
2348 } else {
2349 rc = KM_ERROR_UNIMPLEMENTED;
2350 }
2351 if (rc == KM_ERROR_OK) {
2352 rc = device->generate_key(device, params.params.data(), params.params.size(),
2353 &blob, &out);
2354 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002355 }
2356 // If the HW device didn't support generate_key or generate_key failed
2357 // fall back to the software implementation.
2358 if (rc && fallback->generate_key != NULL) {
2359 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002360 if (!entropy) {
2361 rc = KM_ERROR_OK;
2362 } else if (fallback->add_rng_entropy) {
2363 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2364 } else {
2365 rc = KM_ERROR_UNIMPLEMENTED;
2366 }
2367 if (rc == KM_ERROR_OK) {
2368 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2369 &blob,
2370 &out);
2371 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002372 }
2373
2374 if (out) {
2375 if (outCharacteristics) {
2376 outCharacteristics->characteristics = *out;
2377 } else {
2378 keymaster_free_characteristics(out);
2379 }
2380 free(out);
2381 }
2382
2383 if (rc) {
2384 return rc;
2385 }
2386
2387 String8 name8(name);
2388 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2389
2390 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2391 keyBlob.setFallback(isFallback);
2392 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2393
2394 free(const_cast<uint8_t*>(blob.key_material));
2395
2396 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002397 }
2398
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002399 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002400 const keymaster_blob_t* clientId,
2401 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002402 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002403 if (!outCharacteristics) {
2404 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2405 }
2406
2407 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2408
2409 Blob keyBlob;
2410 String8 name8(name);
2411 int rc;
2412
2413 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2414 TYPE_KEYMASTER_10);
2415 if (responseCode != ::NO_ERROR) {
2416 return responseCode;
2417 }
2418 keymaster_key_blob_t key;
2419 key.key_material_size = keyBlob.getLength();
2420 key.key_material = keyBlob.getValue();
2421 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2422 keymaster_key_characteristics_t *out = NULL;
2423 if (!dev->get_key_characteristics) {
2424 ALOGW("device does not implement get_key_characteristics");
2425 return KM_ERROR_UNIMPLEMENTED;
2426 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002427 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002428 if (out) {
2429 outCharacteristics->characteristics = *out;
2430 free(out);
2431 }
2432 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002433 }
2434
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002435 int32_t importKey(const String16& name, const KeymasterArguments& params,
2436 keymaster_key_format_t format, const uint8_t *keyData,
2437 size_t keyLength, int uid, int flags,
2438 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002439 uid = getEffectiveUid(uid);
2440 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2441 flags & KEYSTORE_FLAG_ENCRYPTED);
2442 if (rc != ::NO_ERROR) {
2443 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002444 }
2445
Chad Brubaker9489b792015-04-14 11:01:45 -07002446 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002447 bool isFallback = false;
2448 keymaster_key_blob_t blob;
2449 keymaster_key_characteristics_t *out = NULL;
2450
2451 const keymaster1_device_t* device = mKeyStore->getDevice();
2452 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2453 if (device == NULL) {
2454 return ::SYSTEM_ERROR;
2455 }
2456 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2457 device->import_key != NULL) {
2458 rc = device->import_key(device, params.params.data(), params.params.size(),
2459 format, keyData, keyLength, &blob, &out);
2460 }
2461 if (rc && fallback->import_key != NULL) {
2462 isFallback = true;
2463 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2464 format, keyData, keyLength, &blob, &out);
2465 }
2466 if (out) {
2467 if (outCharacteristics) {
2468 outCharacteristics->characteristics = *out;
2469 } else {
2470 keymaster_free_characteristics(out);
2471 }
2472 free(out);
2473 }
2474 if (rc) {
2475 return rc;
2476 }
2477
2478 String8 name8(name);
2479 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2480
2481 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2482 keyBlob.setFallback(isFallback);
2483 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2484
2485 free((void*) blob.key_material);
2486
2487 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002488 }
2489
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002490 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002491 const keymaster_blob_t* clientId,
2492 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002493
2494 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2495
2496 Blob keyBlob;
2497 String8 name8(name);
2498 int rc;
2499
2500 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2501 TYPE_KEYMASTER_10);
2502 if (responseCode != ::NO_ERROR) {
2503 result->resultCode = responseCode;
2504 return;
2505 }
2506 keymaster_key_blob_t key;
2507 key.key_material_size = keyBlob.getLength();
2508 key.key_material = keyBlob.getValue();
2509 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2510 if (!dev->export_key) {
2511 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2512 return;
2513 }
2514 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002515 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002516 &ptr, &result->dataLength);
2517 result->exportData.reset(ptr);
2518 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002519 }
2520
Chad Brubakerad6514a2015-04-09 14:00:26 -07002521
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002522 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002523 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2524 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002525 if (!result || !outParams) {
2526 ALOGE("Unexpected null arguments to begin()");
2527 return;
2528 }
2529 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2530 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2531 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2532 result->resultCode = ::PERMISSION_DENIED;
2533 return;
2534 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002535 if (!checkAllowedOperationParams(params.params)) {
2536 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2537 return;
2538 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002539 Blob keyBlob;
2540 String8 name8(name);
2541 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2542 TYPE_KEYMASTER_10);
2543 if (responseCode != ::NO_ERROR) {
2544 result->resultCode = responseCode;
2545 return;
2546 }
2547 keymaster_key_blob_t key;
2548 key.key_material_size = keyBlob.getLength();
2549 key.key_material = keyBlob.getValue();
2550 keymaster_key_param_t* out;
2551 size_t outSize;
2552 keymaster_operation_handle_t handle;
2553 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002554 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002555 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002556 Unique_keymaster_key_characteristics characteristics;
2557 characteristics.reset(new keymaster_key_characteristics_t);
2558 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2559 if (err) {
2560 result->resultCode = err;
2561 return;
2562 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002563 const hw_auth_token_t* authToken = NULL;
2564 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002565 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002566 // If per-operation auth is needed we need to begin the operation and
2567 // the client will need to authorize that operation before calling
2568 // update. Any other auth issues stop here.
2569 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2570 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002571 return;
2572 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002573 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002574 // Add entropy to the device first.
2575 if (entropy) {
2576 if (dev->add_rng_entropy) {
2577 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2578 } else {
2579 err = KM_ERROR_UNIMPLEMENTED;
2580 }
2581 if (err) {
2582 result->resultCode = err;
2583 return;
2584 }
2585 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002586 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2587 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002588
2589 // If there are too many operations abort the oldest operation that was
2590 // started as pruneable and try again.
2591 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2592 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2593 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2594 if (abort(oldest) != ::NO_ERROR) {
2595 break;
2596 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002597 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002598 &handle);
2599 }
2600 if (err) {
2601 result->resultCode = err;
2602 return;
2603 }
2604 if (out) {
2605 outParams->params.assign(out, out + outSize);
2606 free(out);
2607 }
2608
Chad Brubakerad6514a2015-04-09 14:00:26 -07002609 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2610 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002611 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002612 if (authToken) {
2613 mOperationMap.setOperationAuthToken(operationToken, authToken);
2614 }
2615 // Return the authentication lookup result. If this is a per operation
2616 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2617 // application should get an auth token using the handle before the
2618 // first call to update, which will fail if keystore hasn't received the
2619 // auth token.
2620 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002621 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002622 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002623 }
2624
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002625 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2626 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002627 if (!checkAllowedOperationParams(params.params)) {
2628 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2629 return;
2630 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002631 const keymaster1_device_t* dev;
2632 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002633 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002634 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2635 return;
2636 }
2637 uint8_t* output_buf = NULL;
2638 size_t output_length = 0;
2639 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002640 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002641 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2642 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002643 result->resultCode = authResult;
2644 return;
2645 }
2646 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2647 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002648 result->data.reset(output_buf);
2649 result->dataLength = output_length;
2650 result->inputConsumed = consumed;
2651 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002652 }
2653
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002654 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2655 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002656 if (!checkAllowedOperationParams(params.params)) {
2657 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2658 return;
2659 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002660 const keymaster1_device_t* dev;
2661 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002662 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002663 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2664 return;
2665 }
2666 uint8_t* output_buf = NULL;
2667 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002668 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002669 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2670 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002671 result->resultCode = authResult;
2672 return;
2673 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002674
Chad Brubaker06801e02015-03-31 15:13:13 -07002675 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2676 signature, signatureLength, &output_buf,
2677 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002678 // Remove the operation regardless of the result
2679 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002680 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002681 result->data.reset(output_buf);
2682 result->dataLength = output_length;
2683 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002684 }
2685
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002686 int32_t abort(const sp<IBinder>& token) {
2687 const keymaster1_device_t* dev;
2688 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002689 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002690 return KM_ERROR_INVALID_OPERATION_HANDLE;
2691 }
2692 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002693 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002694 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002695 rc = KM_ERROR_UNIMPLEMENTED;
2696 } else {
2697 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002698 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002699 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002700 if (rc) {
2701 return rc;
2702 }
2703 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002704 }
2705
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002706 bool isOperationAuthorized(const sp<IBinder>& token) {
2707 const keymaster1_device_t* dev;
2708 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002709 const keymaster_key_characteristics_t* characteristics;
2710 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002711 return false;
2712 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002713 const hw_auth_token_t* authToken = NULL;
2714 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002715 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002716 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2717 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002718 }
2719
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002720 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002721 if (!checkBinderPermission(P_ADD_AUTH)) {
2722 ALOGW("addAuthToken: permission denied for %d",
2723 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002724 return ::PERMISSION_DENIED;
2725 }
2726 if (length != sizeof(hw_auth_token_t)) {
2727 return KM_ERROR_INVALID_ARGUMENT;
2728 }
2729 hw_auth_token_t* authToken = new hw_auth_token_t;
2730 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2731 // The table takes ownership of authToken.
2732 mAuthTokenTable.AddAuthenticationToken(authToken);
2733 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002734 }
2735
Kenny Root07438c82012-11-02 15:41:02 -07002736private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002737 static const int32_t UID_SELF = -1;
2738
2739 /**
2740 * Get the effective target uid for a binder operation that takes an
2741 * optional uid as the target.
2742 */
2743 inline uid_t getEffectiveUid(int32_t targetUid) {
2744 if (targetUid == UID_SELF) {
2745 return IPCThreadState::self()->getCallingUid();
2746 }
2747 return static_cast<uid_t>(targetUid);
2748 }
2749
2750 /**
2751 * Check if the caller of the current binder method has the required
2752 * permission and if acting on other uids the grants to do so.
2753 */
2754 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2755 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2756 pid_t spid = IPCThreadState::self()->getCallingPid();
2757 if (!has_permission(callingUid, permission, spid)) {
2758 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2759 return false;
2760 }
2761 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2762 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2763 return false;
2764 }
2765 return true;
2766 }
2767
2768 /**
2769 * Check if the caller of the current binder method has the required
2770 * permission or the target of the operation is the caller's uid. This is
2771 * for operation where the permission is only for cross-uid activity and all
2772 * uids are allowed to act on their own (ie: clearing all entries for a
2773 * given uid).
2774 */
2775 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2776 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2777 if (getEffectiveUid(targetUid) == callingUid) {
2778 return true;
2779 } else {
2780 return checkBinderPermission(permission, targetUid);
2781 }
2782 }
2783
2784 /**
2785 * Helper method to check that the caller has the required permission as
2786 * well as the keystore is in the unlocked state if checkUnlocked is true.
2787 *
2788 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2789 * otherwise the state of keystore when not unlocked and checkUnlocked is
2790 * true.
2791 */
2792 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2793 bool checkUnlocked = true) {
2794 if (!checkBinderPermission(permission, targetUid)) {
2795 return ::PERMISSION_DENIED;
2796 }
2797 State state = mKeyStore->getState(getEffectiveUid(targetUid));
2798 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2799 return state;
2800 }
2801
2802 return ::NO_ERROR;
2803
2804 }
2805
Kenny Root9d45d1c2013-02-14 10:32:30 -08002806 inline bool isKeystoreUnlocked(State state) {
2807 switch (state) {
2808 case ::STATE_NO_ERROR:
2809 return true;
2810 case ::STATE_UNINITIALIZED:
2811 case ::STATE_LOCKED:
2812 return false;
2813 }
2814 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002815 }
2816
Chad Brubaker67d2a502015-03-11 17:21:18 +00002817 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002818 const int32_t device_api = device->common.module->module_api_version;
2819 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2820 switch (keyType) {
2821 case TYPE_RSA:
2822 case TYPE_DSA:
2823 case TYPE_EC:
2824 return true;
2825 default:
2826 return false;
2827 }
2828 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2829 switch (keyType) {
2830 case TYPE_RSA:
2831 return true;
2832 case TYPE_DSA:
2833 return device->flags & KEYMASTER_SUPPORTS_DSA;
2834 case TYPE_EC:
2835 return device->flags & KEYMASTER_SUPPORTS_EC;
2836 default:
2837 return false;
2838 }
2839 } else {
2840 return keyType == TYPE_RSA;
2841 }
2842 }
2843
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002844 /**
2845 * Check that all keymaster_key_param_t's provided by the application are
2846 * allowed. Any parameter that keystore adds itself should be disallowed here.
2847 */
2848 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2849 for (auto param: params) {
2850 switch (param.tag) {
2851 case KM_TAG_AUTH_TOKEN:
2852 return false;
2853 default:
2854 break;
2855 }
2856 }
2857 return true;
2858 }
2859
2860 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2861 const keymaster1_device_t* dev,
2862 const std::vector<keymaster_key_param_t>& params,
2863 keymaster_key_characteristics_t* out) {
2864 UniquePtr<keymaster_blob_t> appId;
2865 UniquePtr<keymaster_blob_t> appData;
2866 for (auto param : params) {
2867 if (param.tag == KM_TAG_APPLICATION_ID) {
2868 appId.reset(new keymaster_blob_t);
2869 appId->data = param.blob.data;
2870 appId->data_length = param.blob.data_length;
2871 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2872 appData.reset(new keymaster_blob_t);
2873 appData->data = param.blob.data;
2874 appData->data_length = param.blob.data_length;
2875 }
2876 }
2877 keymaster_key_characteristics_t* result = NULL;
2878 if (!dev->get_key_characteristics) {
2879 return KM_ERROR_UNIMPLEMENTED;
2880 }
2881 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2882 appData.get(), &result);
2883 if (result) {
2884 *out = *result;
2885 free(result);
2886 }
2887 return error;
2888 }
2889
2890 /**
2891 * Get the auth token for this operation from the auth token table.
2892 *
2893 * Returns ::NO_ERROR if the auth token was set or none was required.
2894 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2895 * authorization token exists for that operation and
2896 * failOnTokenMissing is false.
2897 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2898 * token for the operation
2899 */
2900 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2901 keymaster_operation_handle_t handle,
2902 const hw_auth_token_t** authToken,
2903 bool failOnTokenMissing = true) {
2904
2905 std::vector<keymaster_key_param_t> allCharacteristics;
2906 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2907 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2908 }
2909 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2910 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2911 }
2912 keymaster::AuthTokenTable::Error err =
2913 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2914 allCharacteristics.size(), handle, authToken);
2915 switch (err) {
2916 case keymaster::AuthTokenTable::OK:
2917 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2918 return ::NO_ERROR;
2919 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2920 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2921 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2922 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2923 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2924 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2925 (int32_t) ::OP_AUTH_NEEDED;
2926 default:
2927 ALOGE("Unexpected FindAuthorization return value %d", err);
2928 return KM_ERROR_INVALID_ARGUMENT;
2929 }
2930 }
2931
2932 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2933 const hw_auth_token_t* token) {
2934 if (token) {
2935 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2936 reinterpret_cast<const uint8_t*>(token),
2937 sizeof(hw_auth_token_t)));
2938 }
2939 }
2940
2941 /**
2942 * Add the auth token for the operation to the param list if the operation
2943 * requires authorization. Uses the cached result in the OperationMap if available
2944 * otherwise gets the token from the AuthTokenTable and caches the result.
2945 *
2946 * Returns ::NO_ERROR if the auth token was added or not needed.
2947 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2948 * authenticated.
2949 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2950 * operation token.
2951 */
2952 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2953 std::vector<keymaster_key_param_t>* params) {
2954 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002955 mOperationMap.getOperationAuthToken(token, &authToken);
2956 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002957 const keymaster1_device_t* dev;
2958 keymaster_operation_handle_t handle;
2959 const keymaster_key_characteristics_t* characteristics = NULL;
2960 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
2961 return KM_ERROR_INVALID_OPERATION_HANDLE;
2962 }
2963 int32_t result = getAuthToken(characteristics, handle, &authToken);
2964 if (result != ::NO_ERROR) {
2965 return result;
2966 }
2967 if (authToken) {
2968 mOperationMap.setOperationAuthToken(token, authToken);
2969 }
2970 }
2971 addAuthToParams(params, authToken);
2972 return ::NO_ERROR;
2973 }
2974
Kenny Root07438c82012-11-02 15:41:02 -07002975 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002976 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002977 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07002978};
2979
2980}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002981
2982int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002983 if (argc < 2) {
2984 ALOGE("A directory must be specified!");
2985 return 1;
2986 }
2987 if (chdir(argv[1]) == -1) {
2988 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2989 return 1;
2990 }
2991
2992 Entropy entropy;
2993 if (!entropy.open()) {
2994 return 1;
2995 }
Kenny Root70e3a862012-02-15 17:20:23 -08002996
Shawn Willden80843db2015-02-24 09:31:25 -07002997 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002998 if (keymaster_device_initialize(&dev)) {
2999 ALOGE("keystore keymaster could not be initialized; exiting");
3000 return 1;
3001 }
3002
Chad Brubaker67d2a502015-03-11 17:21:18 +00003003 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003004 if (fallback_keymaster_device_initialize(&fallback)) {
3005 ALOGE("software keymaster could not be initialized; exiting");
3006 return 1;
3007 }
3008
Riley Spahneaabae92014-06-30 12:39:52 -07003009 ks_is_selinux_enabled = is_selinux_enabled();
3010 if (ks_is_selinux_enabled) {
3011 union selinux_callback cb;
3012 cb.func_log = selinux_log_callback;
3013 selinux_set_callback(SELINUX_CB_LOG, cb);
3014 if (getcon(&tctx) != 0) {
3015 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3016 return -1;
3017 }
3018 } else {
3019 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3020 }
3021
Chad Brubaker67d2a502015-03-11 17:21:18 +00003022 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003023 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003024 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3025 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3026 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3027 if (ret != android::OK) {
3028 ALOGE("Couldn't register binder service!");
3029 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003030 }
Kenny Root07438c82012-11-02 15:41:02 -07003031
3032 /*
3033 * We're the only thread in existence, so we're just going to process
3034 * Binder transaction as a single-threaded program.
3035 */
3036 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003037
3038 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003039 return 1;
3040}