blob: f1553cc089ee331f73e1cd048c4c2c58206c43c7 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Kenny Root17208e02013-09-04 13:56:03 -070046#include <keymaster/softkeymaster.h>
Chad Brubaker919cb2a2015-02-05 21:58:25 -080047#include <keymaster/soft_keymaster_device.h>
Kenny Root17208e02013-09-04 13:56:03 -070048
Kenny Root26cfc082013-09-11 14:38:56 -070049#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070050#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080052
Kenny Root07438c82012-11-02 15:41:02 -070053#include <keystore/IKeystoreService.h>
54#include <binder/IPCThreadState.h>
55#include <binder/IServiceManager.h>
56
Kenny Roota91203b2012-02-15 15:00:46 -080057#include <cutils/log.h>
58#include <cutils/sockets.h>
59#include <private/android_filesystem_config.h>
60
Kenny Root07438c82012-11-02 15:41:02 -070061#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080062
Riley Spahneaabae92014-06-30 12:39:52 -070063#include <selinux/android.h>
64
Chad Brubakerd80c7b42015-03-31 11:04:28 -070065#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070066#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080067#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070068
Kenny Roota91203b2012-02-15 15:00:46 -080069/* KeyStore is a secured storage for key-value pairs. In this implementation,
70 * each file stores one key-value pair. Keys are encoded in file names, and
71 * values are encrypted with checksums. The encryption key is protected by a
72 * user-defined password. To keep things simple, buffers are always larger than
73 * the maximum space we needed, so boundary checks on buffers are omitted. */
74
75#define KEY_SIZE ((NAME_MAX - 15) / 2)
76#define VALUE_SIZE 32768
77#define PASSWORD_SIZE VALUE_SIZE
78
Kenny Root822c3a92012-03-23 16:34:39 -070079
Kenny Root96427ba2013-08-16 14:02:41 -070080struct BIGNUM_Delete {
81 void operator()(BIGNUM* p) const {
82 BN_free(p);
83 }
84};
85typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
86
Kenny Root822c3a92012-03-23 16:34:39 -070087struct BIO_Delete {
88 void operator()(BIO* p) const {
89 BIO_free(p);
90 }
91};
92typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
93
94struct EVP_PKEY_Delete {
95 void operator()(EVP_PKEY* p) const {
96 EVP_PKEY_free(p);
97 }
98};
99typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
100
101struct PKCS8_PRIV_KEY_INFO_Delete {
102 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
103 PKCS8_PRIV_KEY_INFO_free(p);
104 }
105};
106typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
107
Chad Brubaker06801e02015-03-31 15:13:13 -0700108struct keymaster_key_blob_t_Delete {
109 void operator()(keymaster_key_blob_t* blob) const {
110 if (blob) {
111 delete[] blob->key_material;
112 }
113 delete blob;
114 }
115};
116typedef UniquePtr<keymaster_key_blob_t, keymaster_key_blob_t_Delete> Unique_keymaster_key_blob;
Kenny Root822c3a92012-03-23 16:34:39 -0700117
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700118static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800119 int rc;
120
121 const hw_module_t* mod;
122 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
123 if (rc) {
124 ALOGE("could not find any keystore module");
125 goto out;
126 }
127
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700128 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800129 if (rc) {
130 ALOGE("could not open keymaster device in %s (%s)",
131 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
132 goto out;
133 }
134
135 return 0;
136
137out:
138 *dev = NULL;
139 return rc;
140}
141
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800142static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
143 keymaster::SoftKeymasterDevice* softkeymaster =
144 new keymaster::SoftKeymasterDevice();
145 // SoftKeymasterDevice is designed to make this cast safe.
146 *dev = reinterpret_cast<keymaster1_device_t*>(softkeymaster);
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800147 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800148}
149
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700150static void keymaster_device_release(keymaster0_device_t* dev) {
151 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800152}
153
Kenny Root07438c82012-11-02 15:41:02 -0700154/***************
155 * PERMISSIONS *
156 ***************/
157
158/* Here are the permissions, actions, users, and the main function. */
159typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100160 P_TEST = 1 << 0,
161 P_GET = 1 << 1,
162 P_INSERT = 1 << 2,
163 P_DELETE = 1 << 3,
164 P_EXIST = 1 << 4,
165 P_SAW = 1 << 5,
166 P_RESET = 1 << 6,
167 P_PASSWORD = 1 << 7,
168 P_LOCK = 1 << 8,
169 P_UNLOCK = 1 << 9,
170 P_ZERO = 1 << 10,
171 P_SIGN = 1 << 11,
172 P_VERIFY = 1 << 12,
173 P_GRANT = 1 << 13,
174 P_DUPLICATE = 1 << 14,
175 P_CLEAR_UID = 1 << 15,
176 P_RESET_UID = 1 << 16,
177 P_SYNC_UID = 1 << 17,
178 P_PASSWORD_UID = 1 << 18,
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700179 P_ADD_AUTH = 1 << 19,
Kenny Root07438c82012-11-02 15:41:02 -0700180} perm_t;
181
182static struct user_euid {
183 uid_t uid;
184 uid_t euid;
185} user_euids[] = {
186 {AID_VPN, AID_SYSTEM},
187 {AID_WIFI, AID_SYSTEM},
188 {AID_ROOT, AID_SYSTEM},
189};
190
Riley Spahneaabae92014-06-30 12:39:52 -0700191/* perm_labels associcated with keystore_key SELinux class verbs. */
192const char *perm_labels[] = {
193 "test",
194 "get",
195 "insert",
196 "delete",
197 "exist",
198 "saw",
199 "reset",
200 "password",
201 "lock",
202 "unlock",
203 "zero",
204 "sign",
205 "verify",
206 "grant",
207 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100208 "clear_uid",
209 "reset_uid",
210 "sync_uid",
211 "password_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700212 "add_auth",
Riley Spahneaabae92014-06-30 12:39:52 -0700213};
214
Kenny Root07438c82012-11-02 15:41:02 -0700215static struct user_perm {
216 uid_t uid;
217 perm_t perms;
218} user_perms[] = {
219 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
220 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
221 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
222 {AID_ROOT, static_cast<perm_t>(P_GET) },
223};
224
225static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
226 | P_VERIFY);
227
Riley Spahneaabae92014-06-30 12:39:52 -0700228static char *tctx;
229static int ks_is_selinux_enabled;
230
231static const char *get_perm_label(perm_t perm) {
232 unsigned int index = ffs(perm);
233 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
234 return perm_labels[index - 1];
235 } else {
236 ALOGE("Keystore: Failed to retrieve permission label.\n");
237 abort();
238 }
239}
240
Kenny Root655b9582013-04-04 08:37:42 -0700241/**
242 * Returns the app ID (in the Android multi-user sense) for the current
243 * UNIX UID.
244 */
245static uid_t get_app_id(uid_t uid) {
246 return uid % AID_USER;
247}
248
249/**
250 * Returns the user ID (in the Android multi-user sense) for the current
251 * UNIX UID.
252 */
253static uid_t get_user_id(uid_t uid) {
254 return uid / AID_USER;
255}
256
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700257static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700258 if (!ks_is_selinux_enabled) {
259 return true;
260 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000261
Riley Spahneaabae92014-06-30 12:39:52 -0700262 char *sctx = NULL;
263 const char *selinux_class = "keystore_key";
264 const char *str_perm = get_perm_label(perm);
265
266 if (!str_perm) {
267 return false;
268 }
269
270 if (getpidcon(spid, &sctx) != 0) {
271 ALOGE("SELinux: Failed to get source pid context.\n");
272 return false;
273 }
274
275 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
276 NULL) == 0;
277 freecon(sctx);
278 return allowed;
279}
280
281static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700282 // All system users are equivalent for multi-user support.
283 if (get_app_id(uid) == AID_SYSTEM) {
284 uid = AID_SYSTEM;
285 }
286
Kenny Root07438c82012-11-02 15:41:02 -0700287 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
288 struct user_perm user = user_perms[i];
289 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700290 return (user.perms & perm) &&
291 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700292 }
293 }
294
Riley Spahneaabae92014-06-30 12:39:52 -0700295 return (DEFAULT_PERMS & perm) &&
296 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700297}
298
Kenny Root49468902013-03-19 13:41:33 -0700299/**
300 * Returns the UID that the callingUid should act as. This is here for
301 * legacy support of the WiFi and VPN systems and should be removed
302 * when WiFi can operate in its own namespace.
303 */
Kenny Root07438c82012-11-02 15:41:02 -0700304static uid_t get_keystore_euid(uid_t uid) {
305 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
306 struct user_euid user = user_euids[i];
307 if (user.uid == uid) {
308 return user.euid;
309 }
310 }
311
312 return uid;
313}
314
Kenny Root49468902013-03-19 13:41:33 -0700315/**
316 * Returns true if the callingUid is allowed to interact in the targetUid's
317 * namespace.
318 */
319static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
320 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
321 struct user_euid user = user_euids[i];
322 if (user.euid == callingUid && user.uid == targetUid) {
323 return true;
324 }
325 }
326
327 return false;
328}
329
Kenny Root007cb232014-07-30 16:59:42 -0700330/**
331 * Allow the system to perform some privileged tasks that have to do with
332 * system maintenance. This should not be used for any function that uses
333 * the keys in any way (e.g., signing).
334 */
335static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
336 return callingUid == targetUid || callingUid == AID_SYSTEM;
337}
338
Kenny Roota91203b2012-02-15 15:00:46 -0800339/* Here is the encoding of keys. This is necessary in order to allow arbitrary
340 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
341 * into two bytes. The first byte is one of [+-.] which represents the first
342 * two bits of the character. The second byte encodes the rest of the bits into
343 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
344 * that Base64 cannot be used here due to the need of prefix match on keys. */
345
Kenny Root655b9582013-04-04 08:37:42 -0700346static size_t encode_key_length(const android::String8& keyName) {
347 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
348 size_t length = keyName.length();
349 for (int i = length; i > 0; --i, ++in) {
350 if (*in < '0' || *in > '~') {
351 ++length;
352 }
353 }
354 return length;
355}
356
Kenny Root07438c82012-11-02 15:41:02 -0700357static int encode_key(char* out, const android::String8& keyName) {
358 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
359 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800360 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700361 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800362 *out = '+' + (*in >> 6);
363 *++out = '0' + (*in & 0x3F);
364 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700365 } else {
366 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800367 }
368 }
369 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800370 return length;
371}
372
Kenny Root07438c82012-11-02 15:41:02 -0700373/*
374 * Converts from the "escaped" format on disk to actual name.
375 * This will be smaller than the input string.
376 *
377 * Characters that should combine with the next at the end will be truncated.
378 */
379static size_t decode_key_length(const char* in, size_t length) {
380 size_t outLength = 0;
381
382 for (const char* end = in + length; in < end; in++) {
383 /* This combines with the next character. */
384 if (*in < '0' || *in > '~') {
385 continue;
386 }
387
388 outLength++;
389 }
390 return outLength;
391}
392
393static void decode_key(char* out, const char* in, size_t length) {
394 for (const char* end = in + length; in < end; in++) {
395 if (*in < '0' || *in > '~') {
396 /* Truncate combining characters at the end. */
397 if (in + 1 >= end) {
398 break;
399 }
400
401 *out = (*in++ - '+') << 6;
402 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800403 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700404 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800405 }
406 }
407 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800408}
409
410static size_t readFully(int fd, uint8_t* data, size_t size) {
411 size_t remaining = size;
412 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800413 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800414 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800415 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800416 }
417 data += n;
418 remaining -= n;
419 }
420 return size;
421}
422
423static size_t writeFully(int fd, uint8_t* data, size_t size) {
424 size_t remaining = size;
425 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800426 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
427 if (n < 0) {
428 ALOGW("write failed: %s", strerror(errno));
429 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800430 }
431 data += n;
432 remaining -= n;
433 }
434 return size;
435}
436
437class Entropy {
438public:
439 Entropy() : mRandom(-1) {}
440 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800441 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800442 close(mRandom);
443 }
444 }
445
446 bool open() {
447 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800448 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
449 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800450 ALOGE("open: %s: %s", randomDevice, strerror(errno));
451 return false;
452 }
453 return true;
454 }
455
Kenny Root51878182012-03-13 12:53:19 -0700456 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800457 return (readFully(mRandom, data, size) == size);
458 }
459
460private:
461 int mRandom;
462};
463
464/* Here is the file format. There are two parts in blob.value, the secret and
465 * the description. The secret is stored in ciphertext, and its original size
466 * can be found in blob.length. The description is stored after the secret in
467 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700468 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700469 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800470 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
471 * and decryptBlob(). Thus they should not be accessed from outside. */
472
Kenny Root822c3a92012-03-23 16:34:39 -0700473/* ** Note to future implementors of encryption: **
474 * Currently this is the construction:
475 * metadata || Enc(MD5(data) || data)
476 *
477 * This should be the construction used for encrypting if re-implementing:
478 *
479 * Derive independent keys for encryption and MAC:
480 * Kenc = AES_encrypt(masterKey, "Encrypt")
481 * Kmac = AES_encrypt(masterKey, "MAC")
482 *
483 * Store this:
484 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
485 * HMAC(Kmac, metadata || Enc(data))
486 */
Kenny Roota91203b2012-02-15 15:00:46 -0800487struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700488 uint8_t version;
489 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700490 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800491 uint8_t info;
492 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700493 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800494 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700495 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800496 int32_t length; // in network byte order when encrypted
497 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
498};
499
Kenny Root822c3a92012-03-23 16:34:39 -0700500typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700501 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700502 TYPE_GENERIC = 1,
503 TYPE_MASTER_KEY = 2,
504 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800505 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700506} BlobType;
507
Kenny Rootf9119d62013-04-03 09:22:15 -0700508static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700509
Kenny Roota91203b2012-02-15 15:00:46 -0800510class Blob {
511public:
Kenny Root07438c82012-11-02 15:41:02 -0700512 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
513 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800514 mBlob.length = valueLength;
515 memcpy(mBlob.value, value, valueLength);
516
517 mBlob.info = infoLength;
518 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700519
Kenny Root07438c82012-11-02 15:41:02 -0700520 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700521 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700522
Kenny Rootee8068b2013-10-07 09:49:15 -0700523 if (type == TYPE_MASTER_KEY) {
524 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
525 } else {
526 mBlob.flags = KEYSTORE_FLAG_NONE;
527 }
Kenny Roota91203b2012-02-15 15:00:46 -0800528 }
529
530 Blob(blob b) {
531 mBlob = b;
532 }
533
534 Blob() {}
535
Kenny Root51878182012-03-13 12:53:19 -0700536 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 return mBlob.value;
538 }
539
Kenny Root51878182012-03-13 12:53:19 -0700540 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800541 return mBlob.length;
542 }
543
Kenny Root51878182012-03-13 12:53:19 -0700544 const uint8_t* getInfo() const {
545 return mBlob.value + mBlob.length;
546 }
547
548 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800549 return mBlob.info;
550 }
551
Kenny Root822c3a92012-03-23 16:34:39 -0700552 uint8_t getVersion() const {
553 return mBlob.version;
554 }
555
Kenny Rootf9119d62013-04-03 09:22:15 -0700556 bool isEncrypted() const {
557 if (mBlob.version < 2) {
558 return true;
559 }
560
561 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
562 }
563
564 void setEncrypted(bool encrypted) {
565 if (encrypted) {
566 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
567 } else {
568 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
569 }
570 }
571
Kenny Root17208e02013-09-04 13:56:03 -0700572 bool isFallback() const {
573 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
574 }
575
576 void setFallback(bool fallback) {
577 if (fallback) {
578 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
579 } else {
580 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
581 }
582 }
583
Kenny Root822c3a92012-03-23 16:34:39 -0700584 void setVersion(uint8_t version) {
585 mBlob.version = version;
586 }
587
588 BlobType getType() const {
589 return BlobType(mBlob.type);
590 }
591
592 void setType(BlobType type) {
593 mBlob.type = uint8_t(type);
594 }
595
Kenny Rootf9119d62013-04-03 09:22:15 -0700596 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
597 ALOGV("writing blob %s", filename);
598 if (isEncrypted()) {
599 if (state != STATE_NO_ERROR) {
600 ALOGD("couldn't insert encrypted blob while not unlocked");
601 return LOCKED;
602 }
603
604 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
605 ALOGW("Could not read random data for: %s", filename);
606 return SYSTEM_ERROR;
607 }
Kenny Roota91203b2012-02-15 15:00:46 -0800608 }
609
610 // data includes the value and the value's length
611 size_t dataLength = mBlob.length + sizeof(mBlob.length);
612 // pad data to the AES_BLOCK_SIZE
613 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
614 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
615 // encrypted data includes the digest value
616 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
617 // move info after space for padding
618 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
619 // zero padding area
620 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
621
622 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800623
Kenny Rootf9119d62013-04-03 09:22:15 -0700624 if (isEncrypted()) {
625 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800626
Kenny Rootf9119d62013-04-03 09:22:15 -0700627 uint8_t vector[AES_BLOCK_SIZE];
628 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
629 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
630 aes_key, vector, AES_ENCRYPT);
631 }
632
Kenny Roota91203b2012-02-15 15:00:46 -0800633 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
634 size_t fileLength = encryptedLength + headerLength + mBlob.info;
635
636 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800637 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
638 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
639 if (out < 0) {
640 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800641 return SYSTEM_ERROR;
642 }
643 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
644 if (close(out) != 0) {
645 return SYSTEM_ERROR;
646 }
647 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800648 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800649 unlink(tmpFileName);
650 return SYSTEM_ERROR;
651 }
Kenny Root150ca932012-11-14 14:29:02 -0800652 if (rename(tmpFileName, filename) == -1) {
653 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
654 return SYSTEM_ERROR;
655 }
656 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800657 }
658
Kenny Rootf9119d62013-04-03 09:22:15 -0700659 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
660 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800661 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
662 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800663 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
664 }
665 // fileLength may be less than sizeof(mBlob) since the in
666 // memory version has extra padding to tolerate rounding up to
667 // the AES_BLOCK_SIZE
668 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
669 if (close(in) != 0) {
670 return SYSTEM_ERROR;
671 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700672
673 if (isEncrypted() && (state != STATE_NO_ERROR)) {
674 return LOCKED;
675 }
676
Kenny Roota91203b2012-02-15 15:00:46 -0800677 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
678 if (fileLength < headerLength) {
679 return VALUE_CORRUPTED;
680 }
681
682 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700683 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800684 return VALUE_CORRUPTED;
685 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700686
687 ssize_t digestedLength;
688 if (isEncrypted()) {
689 if (encryptedLength % AES_BLOCK_SIZE != 0) {
690 return VALUE_CORRUPTED;
691 }
692
693 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
694 mBlob.vector, AES_DECRYPT);
695 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
696 uint8_t computedDigest[MD5_DIGEST_LENGTH];
697 MD5(mBlob.digested, digestedLength, computedDigest);
698 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
699 return VALUE_CORRUPTED;
700 }
701 } else {
702 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800703 }
704
705 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
706 mBlob.length = ntohl(mBlob.length);
707 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
708 return VALUE_CORRUPTED;
709 }
710 if (mBlob.info != 0) {
711 // move info from after padding to after data
712 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
713 }
Kenny Root07438c82012-11-02 15:41:02 -0700714 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800715 }
716
717private:
718 struct blob mBlob;
719};
720
Kenny Root655b9582013-04-04 08:37:42 -0700721class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800722public:
Kenny Root655b9582013-04-04 08:37:42 -0700723 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
724 asprintf(&mUserDir, "user_%u", mUserId);
725 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
726 }
727
728 ~UserState() {
729 free(mUserDir);
730 free(mMasterKeyFile);
731 }
732
733 bool initialize() {
734 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
735 ALOGE("Could not create directory '%s'", mUserDir);
736 return false;
737 }
738
739 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800740 setState(STATE_LOCKED);
741 } else {
742 setState(STATE_UNINITIALIZED);
743 }
Kenny Root70e3a862012-02-15 17:20:23 -0800744
Kenny Root655b9582013-04-04 08:37:42 -0700745 return true;
746 }
747
748 uid_t getUserId() const {
749 return mUserId;
750 }
751
752 const char* getUserDirName() const {
753 return mUserDir;
754 }
755
756 const char* getMasterKeyFileName() const {
757 return mMasterKeyFile;
758 }
759
760 void setState(State state) {
761 mState = state;
762 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
763 mRetry = MAX_RETRY;
764 }
Kenny Roota91203b2012-02-15 15:00:46 -0800765 }
766
Kenny Root51878182012-03-13 12:53:19 -0700767 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800768 return mState;
769 }
770
Kenny Root51878182012-03-13 12:53:19 -0700771 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800772 return mRetry;
773 }
774
Kenny Root655b9582013-04-04 08:37:42 -0700775 void zeroizeMasterKeysInMemory() {
776 memset(mMasterKey, 0, sizeof(mMasterKey));
777 memset(mSalt, 0, sizeof(mSalt));
778 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
779 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800780 }
781
Kenny Root655b9582013-04-04 08:37:42 -0700782 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
783 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800784 return SYSTEM_ERROR;
785 }
Kenny Root655b9582013-04-04 08:37:42 -0700786 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800787 if (response != NO_ERROR) {
788 return response;
789 }
790 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700791 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800792 }
793
Robin Lee4e865752014-08-19 17:37:55 +0100794 ResponseCode copyMasterKey(UserState* src) {
795 if (mState != STATE_UNINITIALIZED) {
796 return ::SYSTEM_ERROR;
797 }
798 if (src->getState() != STATE_NO_ERROR) {
799 return ::SYSTEM_ERROR;
800 }
801 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
802 setupMasterKeys();
803 return ::NO_ERROR;
804 }
805
Kenny Root655b9582013-04-04 08:37:42 -0700806 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800807 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
808 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
809 AES_KEY passwordAesKey;
810 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700811 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700812 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800813 }
814
Kenny Root655b9582013-04-04 08:37:42 -0700815 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
816 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800817 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800818 return SYSTEM_ERROR;
819 }
820
821 // we read the raw blob to just to get the salt to generate
822 // the AES key, then we create the Blob to use with decryptBlob
823 blob rawBlob;
824 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
825 if (close(in) != 0) {
826 return SYSTEM_ERROR;
827 }
828 // find salt at EOF if present, otherwise we have an old file
829 uint8_t* salt;
830 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
831 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
832 } else {
833 salt = NULL;
834 }
835 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
836 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
837 AES_KEY passwordAesKey;
838 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
839 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700840 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
841 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800842 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700843 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800844 }
845 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
846 // if salt was missing, generate one and write a new master key file with the salt.
847 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700848 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800849 return SYSTEM_ERROR;
850 }
Kenny Root655b9582013-04-04 08:37:42 -0700851 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800852 }
853 if (response == NO_ERROR) {
854 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
855 setupMasterKeys();
856 }
857 return response;
858 }
859 if (mRetry <= 0) {
860 reset();
861 return UNINITIALIZED;
862 }
863 --mRetry;
864 switch (mRetry) {
865 case 0: return WRONG_PASSWORD_0;
866 case 1: return WRONG_PASSWORD_1;
867 case 2: return WRONG_PASSWORD_2;
868 case 3: return WRONG_PASSWORD_3;
869 default: return WRONG_PASSWORD_3;
870 }
871 }
872
Kenny Root655b9582013-04-04 08:37:42 -0700873 AES_KEY* getEncryptionKey() {
874 return &mMasterKeyEncryption;
875 }
876
877 AES_KEY* getDecryptionKey() {
878 return &mMasterKeyDecryption;
879 }
880
Kenny Roota91203b2012-02-15 15:00:46 -0800881 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700882 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800883 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700884 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800885 return false;
886 }
Kenny Root655b9582013-04-04 08:37:42 -0700887
888 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800889 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700890 // We only care about files.
891 if (file->d_type != DT_REG) {
892 continue;
893 }
894
895 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700896 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700897 continue;
898 }
899
900 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800901 }
902 closedir(dir);
903 return true;
904 }
905
Kenny Root655b9582013-04-04 08:37:42 -0700906private:
907 static const int MASTER_KEY_SIZE_BYTES = 16;
908 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
909
910 static const int MAX_RETRY = 4;
911 static const size_t SALT_SIZE = 16;
912
913 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
914 uint8_t* salt) {
915 size_t saltSize;
916 if (salt != NULL) {
917 saltSize = SALT_SIZE;
918 } else {
919 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
920 salt = (uint8_t*) "keystore";
921 // sizeof = 9, not strlen = 8
922 saltSize = sizeof("keystore");
923 }
924
925 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
926 saltSize, 8192, keySize, key);
927 }
928
929 bool generateSalt(Entropy* entropy) {
930 return entropy->generate_random_data(mSalt, sizeof(mSalt));
931 }
932
933 bool generateMasterKey(Entropy* entropy) {
934 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
935 return false;
936 }
937 if (!generateSalt(entropy)) {
938 return false;
939 }
940 return true;
941 }
942
943 void setupMasterKeys() {
944 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
945 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
946 setState(STATE_NO_ERROR);
947 }
948
949 uid_t mUserId;
950
951 char* mUserDir;
952 char* mMasterKeyFile;
953
954 State mState;
955 int8_t mRetry;
956
957 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
958 uint8_t mSalt[SALT_SIZE];
959
960 AES_KEY mMasterKeyEncryption;
961 AES_KEY mMasterKeyDecryption;
962};
963
964typedef struct {
965 uint32_t uid;
966 const uint8_t* filename;
967} grant_t;
968
969class KeyStore {
970public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800971 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700972 : mEntropy(entropy)
973 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800974 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700975 {
976 memset(&mMetaData, '\0', sizeof(mMetaData));
977 }
978
979 ~KeyStore() {
980 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
981 it != mGrants.end(); it++) {
982 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700983 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800984 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700985
986 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
987 it != mMasterKeys.end(); it++) {
988 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700989 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800990 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700991 }
992
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800993 /**
994 * Depending on the hardware keymaster version is this may return a
995 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
996 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
997 * be guarded by a check on the device's version.
998 */
999 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001000 return mDevice;
1001 }
1002
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001003 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001004 return mFallbackDevice;
1005 }
1006
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001007 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001008 return blob.isFallback() ? mFallbackDevice: mDevice;
1009 }
1010
Kenny Root655b9582013-04-04 08:37:42 -07001011 ResponseCode initialize() {
1012 readMetaData();
1013 if (upgradeKeystore()) {
1014 writeMetaData();
1015 }
1016
1017 return ::NO_ERROR;
1018 }
1019
1020 State getState(uid_t uid) {
1021 return getUserState(uid)->getState();
1022 }
1023
1024 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1025 UserState* userState = getUserState(uid);
1026 return userState->initialize(pw, mEntropy);
1027 }
1028
Robin Lee4e865752014-08-19 17:37:55 +01001029 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1030 UserState *userState = getUserState(uid);
1031 UserState *initState = getUserState(src);
1032 return userState->copyMasterKey(initState);
1033 }
1034
Kenny Root655b9582013-04-04 08:37:42 -07001035 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001036 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001037 return userState->writeMasterKey(pw, mEntropy);
1038 }
1039
1040 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001041 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001042 return userState->readMasterKey(pw, mEntropy);
1043 }
1044
1045 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001046 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001047 encode_key(encoded, keyName);
1048 return android::String8(encoded);
1049 }
1050
1051 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001052 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001053 encode_key(encoded, keyName);
1054 return android::String8::format("%u_%s", uid, encoded);
1055 }
1056
1057 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001058 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001059 encode_key(encoded, keyName);
1060 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1061 encoded);
1062 }
1063
1064 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001065 android::String8 prefix("");
1066 android::Vector<android::String16> aliases;
1067 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1068 return ::SYSTEM_ERROR;
1069 }
1070
Kenny Root655b9582013-04-04 08:37:42 -07001071 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001072 for (uint32_t i = 0; i < aliases.size(); i++) {
1073 android::String8 filename(aliases[i]);
1074 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1075 getKeyName(filename).string());
1076 del(filename, ::TYPE_ANY, uid);
1077 }
1078
Kenny Root655b9582013-04-04 08:37:42 -07001079 userState->zeroizeMasterKeysInMemory();
1080 userState->setState(STATE_UNINITIALIZED);
1081 return userState->reset();
1082 }
1083
1084 bool isEmpty(uid_t uid) const {
1085 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001086 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001087 return true;
1088 }
1089
1090 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001091 if (!dir) {
1092 return true;
1093 }
Kenny Root31e27462014-09-10 11:28:03 -07001094
Kenny Roota91203b2012-02-15 15:00:46 -08001095 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001096 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001097 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001098 // We only care about files.
1099 if (file->d_type != DT_REG) {
1100 continue;
1101 }
1102
1103 // Skip anything that starts with a "."
1104 if (file->d_name[0] == '.') {
1105 continue;
1106 }
1107
Kenny Root31e27462014-09-10 11:28:03 -07001108 result = false;
1109 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001110 }
1111 closedir(dir);
1112 return result;
1113 }
1114
Kenny Root655b9582013-04-04 08:37:42 -07001115 void lock(uid_t uid) {
1116 UserState* userState = getUserState(uid);
1117 userState->zeroizeMasterKeysInMemory();
1118 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001119 }
1120
Kenny Root655b9582013-04-04 08:37:42 -07001121 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1122 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001123 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1124 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001125 if (rc != NO_ERROR) {
1126 return rc;
1127 }
1128
1129 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001130 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001131 /* If we upgrade the key, we need to write it to disk again. Then
1132 * it must be read it again since the blob is encrypted each time
1133 * it's written.
1134 */
Kenny Root655b9582013-04-04 08:37:42 -07001135 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1136 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001137 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1138 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001139 return rc;
1140 }
1141 }
Kenny Root822c3a92012-03-23 16:34:39 -07001142 }
1143
Kenny Root17208e02013-09-04 13:56:03 -07001144 /*
1145 * This will upgrade software-backed keys to hardware-backed keys when
1146 * the HAL for the device supports the newer key types.
1147 */
1148 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1149 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1150 && keyBlob->isFallback()) {
1151 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1152 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1153
1154 // The HAL allowed the import, reget the key to have the "fresh"
1155 // version.
1156 if (imported == NO_ERROR) {
1157 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1158 }
1159 }
1160
Kenny Rootd53bc922013-03-21 14:10:15 -07001161 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001162 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1163 return KEY_NOT_FOUND;
1164 }
1165
1166 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001167 }
1168
Kenny Root655b9582013-04-04 08:37:42 -07001169 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1170 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001171 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1172 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001173 }
1174
Robin Lee4b84fdc2014-09-24 11:56:57 +01001175 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1176 Blob keyBlob;
1177 ResponseCode rc = get(filename, &keyBlob, type, uid);
1178 if (rc != ::NO_ERROR) {
1179 return rc;
1180 }
1181
1182 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1183 // A device doesn't have to implement delete_keypair.
1184 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1185 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1186 rc = ::SYSTEM_ERROR;
1187 }
1188 }
1189 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001190 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1191 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1192 if (dev->delete_key) {
1193 keymaster_key_blob_t blob;
1194 blob.key_material = keyBlob.getValue();
1195 blob.key_material_size = keyBlob.getLength();
1196 dev->delete_key(dev, &blob);
1197 }
1198 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001199 if (rc != ::NO_ERROR) {
1200 return rc;
1201 }
1202
1203 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1204 }
1205
1206 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1207 uid_t uid) {
1208
1209 UserState* userState = getUserState(uid);
1210 size_t n = prefix.length();
1211
1212 DIR* dir = opendir(userState->getUserDirName());
1213 if (!dir) {
1214 ALOGW("can't open directory for user: %s", strerror(errno));
1215 return ::SYSTEM_ERROR;
1216 }
1217
1218 struct dirent* file;
1219 while ((file = readdir(dir)) != NULL) {
1220 // We only care about files.
1221 if (file->d_type != DT_REG) {
1222 continue;
1223 }
1224
1225 // Skip anything that starts with a "."
1226 if (file->d_name[0] == '.') {
1227 continue;
1228 }
1229
1230 if (!strncmp(prefix.string(), file->d_name, n)) {
1231 const char* p = &file->d_name[n];
1232 size_t plen = strlen(p);
1233
1234 size_t extra = decode_key_length(p, plen);
1235 char *match = (char*) malloc(extra + 1);
1236 if (match != NULL) {
1237 decode_key(match, p, plen);
1238 matches->push(android::String16(match, extra));
1239 free(match);
1240 } else {
1241 ALOGW("could not allocate match of size %zd", extra);
1242 }
1243 }
1244 }
1245 closedir(dir);
1246 return ::NO_ERROR;
1247 }
1248
Kenny Root07438c82012-11-02 15:41:02 -07001249 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001250 const grant_t* existing = getGrant(filename, granteeUid);
1251 if (existing == NULL) {
1252 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001253 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001254 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001255 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001256 }
1257 }
1258
Kenny Root07438c82012-11-02 15:41:02 -07001259 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001260 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1261 it != mGrants.end(); it++) {
1262 grant_t* grant = *it;
1263 if (grant->uid == granteeUid
1264 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1265 mGrants.erase(it);
1266 return true;
1267 }
Kenny Root70e3a862012-02-15 17:20:23 -08001268 }
Kenny Root70e3a862012-02-15 17:20:23 -08001269 return false;
1270 }
1271
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001272 bool hasGrant(const char* filename, const uid_t uid) const {
1273 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001274 }
1275
Kenny Rootf9119d62013-04-03 09:22:15 -07001276 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1277 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001278 uint8_t* data;
1279 size_t dataLength;
1280 int rc;
1281
1282 if (mDevice->import_keypair == NULL) {
1283 ALOGE("Keymaster doesn't support import!");
1284 return SYSTEM_ERROR;
1285 }
1286
Kenny Root17208e02013-09-04 13:56:03 -07001287 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001288 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001289 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001290 /*
1291 * Maybe the device doesn't support this type of key. Try to use the
1292 * software fallback keymaster implementation. This is a little bit
1293 * lazier than checking the PKCS#8 key type, but the software
1294 * implementation will do that anyway.
1295 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001296 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001297 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001298
1299 if (rc) {
1300 ALOGE("Error while importing keypair: %d", rc);
1301 return SYSTEM_ERROR;
1302 }
Kenny Root822c3a92012-03-23 16:34:39 -07001303 }
1304
1305 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1306 free(data);
1307
Kenny Rootf9119d62013-04-03 09:22:15 -07001308 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001309 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001310
Kenny Root655b9582013-04-04 08:37:42 -07001311 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001312 }
1313
Kenny Root1b0e3932013-09-05 13:06:32 -07001314 bool isHardwareBacked(const android::String16& keyType) const {
1315 if (mDevice == NULL) {
1316 ALOGW("can't get keymaster device");
1317 return false;
1318 }
1319
1320 if (sRSAKeyType == keyType) {
1321 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1322 } else {
1323 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1324 && (mDevice->common.module->module_api_version
1325 >= KEYMASTER_MODULE_API_VERSION_0_2);
1326 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001327 }
1328
Kenny Root655b9582013-04-04 08:37:42 -07001329 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1330 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001331 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001332
1333 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1334 if (responseCode == NO_ERROR) {
1335 return responseCode;
1336 }
1337
1338 // If this is one of the legacy UID->UID mappings, use it.
1339 uid_t euid = get_keystore_euid(uid);
1340 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001341 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001342 responseCode = get(filepath8.string(), keyBlob, type, uid);
1343 if (responseCode == NO_ERROR) {
1344 return responseCode;
1345 }
1346 }
1347
1348 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001349 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001350 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001351 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001352 if (end[0] != '_' || end[1] == 0) {
1353 return KEY_NOT_FOUND;
1354 }
Kenny Root86b16e82013-09-09 11:15:54 -07001355 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1356 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001357 if (!hasGrant(filepath8.string(), uid)) {
1358 return responseCode;
1359 }
1360
1361 // It is a granted key. Try to load it.
1362 return get(filepath8.string(), keyBlob, type, uid);
1363 }
1364
1365 /**
1366 * Returns any existing UserState or creates it if it doesn't exist.
1367 */
1368 UserState* getUserState(uid_t uid) {
1369 uid_t userId = get_user_id(uid);
1370
1371 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1372 it != mMasterKeys.end(); it++) {
1373 UserState* state = *it;
1374 if (state->getUserId() == userId) {
1375 return state;
1376 }
1377 }
1378
1379 UserState* userState = new UserState(userId);
1380 if (!userState->initialize()) {
1381 /* There's not much we can do if initialization fails. Trying to
1382 * unlock the keystore for that user will fail as well, so any
1383 * subsequent request for this user will just return SYSTEM_ERROR.
1384 */
1385 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1386 }
1387 mMasterKeys.add(userState);
1388 return userState;
1389 }
1390
1391 /**
1392 * Returns NULL if the UserState doesn't already exist.
1393 */
1394 const UserState* getUserState(uid_t uid) const {
1395 uid_t userId = get_user_id(uid);
1396
1397 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1398 it != mMasterKeys.end(); it++) {
1399 UserState* state = *it;
1400 if (state->getUserId() == userId) {
1401 return state;
1402 }
1403 }
1404
1405 return NULL;
1406 }
1407
Kenny Roota91203b2012-02-15 15:00:46 -08001408private:
Kenny Root655b9582013-04-04 08:37:42 -07001409 static const char* sOldMasterKey;
1410 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001411 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001412 Entropy* mEntropy;
1413
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001414 keymaster1_device_t* mDevice;
1415 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001416
Kenny Root655b9582013-04-04 08:37:42 -07001417 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001418
Kenny Root655b9582013-04-04 08:37:42 -07001419 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001420
Kenny Root655b9582013-04-04 08:37:42 -07001421 typedef struct {
1422 uint32_t version;
1423 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001424
Kenny Root655b9582013-04-04 08:37:42 -07001425 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001426
Kenny Root655b9582013-04-04 08:37:42 -07001427 const grant_t* getGrant(const char* filename, uid_t uid) const {
1428 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1429 it != mGrants.end(); it++) {
1430 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001431 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001432 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001433 return grant;
1434 }
1435 }
Kenny Root70e3a862012-02-15 17:20:23 -08001436 return NULL;
1437 }
1438
Kenny Root822c3a92012-03-23 16:34:39 -07001439 /**
1440 * Upgrade code. This will upgrade the key from the current version
1441 * to whatever is newest.
1442 */
Kenny Root655b9582013-04-04 08:37:42 -07001443 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1444 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001445 bool updated = false;
1446 uint8_t version = oldVersion;
1447
1448 /* From V0 -> V1: All old types were unknown */
1449 if (version == 0) {
1450 ALOGV("upgrading to version 1 and setting type %d", type);
1451
1452 blob->setType(type);
1453 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001454 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001455 }
1456 version = 1;
1457 updated = true;
1458 }
1459
Kenny Rootf9119d62013-04-03 09:22:15 -07001460 /* From V1 -> V2: All old keys were encrypted */
1461 if (version == 1) {
1462 ALOGV("upgrading to version 2");
1463
1464 blob->setEncrypted(true);
1465 version = 2;
1466 updated = true;
1467 }
1468
Kenny Root822c3a92012-03-23 16:34:39 -07001469 /*
1470 * If we've updated, set the key blob to the right version
1471 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001472 */
Kenny Root822c3a92012-03-23 16:34:39 -07001473 if (updated) {
1474 ALOGV("updated and writing file %s", filename);
1475 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001476 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001477
1478 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001479 }
1480
1481 /**
1482 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1483 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1484 * Then it overwrites the original blob with the new blob
1485 * format that is returned from the keymaster.
1486 */
Kenny Root655b9582013-04-04 08:37:42 -07001487 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001488 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1489 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1490 if (b.get() == NULL) {
1491 ALOGE("Problem instantiating BIO");
1492 return SYSTEM_ERROR;
1493 }
1494
1495 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1496 if (pkey.get() == NULL) {
1497 ALOGE("Couldn't read old PEM file");
1498 return SYSTEM_ERROR;
1499 }
1500
1501 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1502 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1503 if (len < 0) {
1504 ALOGE("Couldn't measure PKCS#8 length");
1505 return SYSTEM_ERROR;
1506 }
1507
Kenny Root70c98892013-02-07 09:10:36 -08001508 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1509 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001510 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1511 ALOGE("Couldn't convert to PKCS#8");
1512 return SYSTEM_ERROR;
1513 }
1514
Kenny Rootf9119d62013-04-03 09:22:15 -07001515 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1516 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001517 if (rc != NO_ERROR) {
1518 return rc;
1519 }
1520
Kenny Root655b9582013-04-04 08:37:42 -07001521 return get(filename, blob, TYPE_KEY_PAIR, uid);
1522 }
1523
1524 void readMetaData() {
1525 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1526 if (in < 0) {
1527 return;
1528 }
1529 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1530 if (fileLength != sizeof(mMetaData)) {
1531 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1532 sizeof(mMetaData));
1533 }
1534 close(in);
1535 }
1536
1537 void writeMetaData() {
1538 const char* tmpFileName = ".metadata.tmp";
1539 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1540 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1541 if (out < 0) {
1542 ALOGE("couldn't write metadata file: %s", strerror(errno));
1543 return;
1544 }
1545 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1546 if (fileLength != sizeof(mMetaData)) {
1547 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1548 sizeof(mMetaData));
1549 }
1550 close(out);
1551 rename(tmpFileName, sMetaDataFile);
1552 }
1553
1554 bool upgradeKeystore() {
1555 bool upgraded = false;
1556
1557 if (mMetaData.version == 0) {
1558 UserState* userState = getUserState(0);
1559
1560 // Initialize first so the directory is made.
1561 userState->initialize();
1562
1563 // Migrate the old .masterkey file to user 0.
1564 if (access(sOldMasterKey, R_OK) == 0) {
1565 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1566 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1567 return false;
1568 }
1569 }
1570
1571 // Initialize again in case we had a key.
1572 userState->initialize();
1573
1574 // Try to migrate existing keys.
1575 DIR* dir = opendir(".");
1576 if (!dir) {
1577 // Give up now; maybe we can upgrade later.
1578 ALOGE("couldn't open keystore's directory; something is wrong");
1579 return false;
1580 }
1581
1582 struct dirent* file;
1583 while ((file = readdir(dir)) != NULL) {
1584 // We only care about files.
1585 if (file->d_type != DT_REG) {
1586 continue;
1587 }
1588
1589 // Skip anything that starts with a "."
1590 if (file->d_name[0] == '.') {
1591 continue;
1592 }
1593
1594 // Find the current file's user.
1595 char* end;
1596 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1597 if (end[0] != '_' || end[1] == 0) {
1598 continue;
1599 }
1600 UserState* otherUser = getUserState(thisUid);
1601 if (otherUser->getUserId() != 0) {
1602 unlinkat(dirfd(dir), file->d_name, 0);
1603 }
1604
1605 // Rename the file into user directory.
1606 DIR* otherdir = opendir(otherUser->getUserDirName());
1607 if (otherdir == NULL) {
1608 ALOGW("couldn't open user directory for rename");
1609 continue;
1610 }
1611 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1612 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1613 }
1614 closedir(otherdir);
1615 }
1616 closedir(dir);
1617
1618 mMetaData.version = 1;
1619 upgraded = true;
1620 }
1621
1622 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001623 }
Kenny Roota91203b2012-02-15 15:00:46 -08001624};
1625
Kenny Root655b9582013-04-04 08:37:42 -07001626const char* KeyStore::sOldMasterKey = ".masterkey";
1627const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001628
Kenny Root1b0e3932013-09-05 13:06:32 -07001629const android::String16 KeyStore::sRSAKeyType("RSA");
1630
Kenny Root07438c82012-11-02 15:41:02 -07001631namespace android {
1632class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1633public:
1634 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001635 : mKeyStore(keyStore),
1636 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001637 {
Kenny Roota91203b2012-02-15 15:00:46 -08001638 }
Kenny Roota91203b2012-02-15 15:00:46 -08001639
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001640 void binderDied(const wp<IBinder>& who) {
1641 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1642 for (auto token: operations) {
1643 abort(token);
1644 }
Kenny Root822c3a92012-03-23 16:34:39 -07001645 }
Kenny Roota91203b2012-02-15 15:00:46 -08001646
Kenny Root07438c82012-11-02 15:41:02 -07001647 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001648 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001649 pid_t spid = IPCThreadState::self()->getCallingPid();
1650 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001651 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001652 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001653 }
Kenny Roota91203b2012-02-15 15:00:46 -08001654
Kenny Root655b9582013-04-04 08:37:42 -07001655 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001656 }
1657
Kenny Root07438c82012-11-02 15:41:02 -07001658 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001659 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001660 pid_t spid = IPCThreadState::self()->getCallingPid();
1661 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001662 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001663 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001664 }
Kenny Root07438c82012-11-02 15:41:02 -07001665
Kenny Root07438c82012-11-02 15:41:02 -07001666 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001667 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001668
Kenny Root655b9582013-04-04 08:37:42 -07001669 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001670 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001671 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001672 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001673 *item = NULL;
1674 *itemLength = 0;
1675 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001676 }
Kenny Roota91203b2012-02-15 15:00:46 -08001677
Kenny Root07438c82012-11-02 15:41:02 -07001678 *item = (uint8_t*) malloc(keyBlob.getLength());
1679 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1680 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001681
Kenny Root07438c82012-11-02 15:41:02 -07001682 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001683 }
1684
Kenny Rootf9119d62013-04-03 09:22:15 -07001685 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1686 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001687 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001688 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001689 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001690 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001691 return ::PERMISSION_DENIED;
1692 }
Kenny Root07438c82012-11-02 15:41:02 -07001693
Kenny Rootf9119d62013-04-03 09:22:15 -07001694 State state = mKeyStore->getState(callingUid);
1695 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1696 ALOGD("calling get in state: %d", state);
1697 return state;
1698 }
1699
Kenny Root49468902013-03-19 13:41:33 -07001700 if (targetUid == -1) {
1701 targetUid = callingUid;
1702 } else if (!is_granted_to(callingUid, 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 Root07438c82012-11-02 15:41:02 -07001708
1709 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001710 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1711
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001712 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001713 }
1714
Kenny Root49468902013-03-19 13:41:33 -07001715 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001716 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001717 pid_t spid = IPCThreadState::self()->getCallingPid();
1718 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001719 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001720 return ::PERMISSION_DENIED;
1721 }
Kenny Root70e3a862012-02-15 17:20:23 -08001722
Kenny Root49468902013-03-19 13:41:33 -07001723 if (targetUid == -1) {
1724 targetUid = callingUid;
1725 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001726 return ::PERMISSION_DENIED;
1727 }
1728
Kenny Root07438c82012-11-02 15:41:02 -07001729 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001730 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001731 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001732 }
1733
Kenny Root49468902013-03-19 13:41:33 -07001734 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001735 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001736 pid_t spid = IPCThreadState::self()->getCallingPid();
1737 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001738 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001739 return ::PERMISSION_DENIED;
1740 }
Kenny Root70e3a862012-02-15 17:20:23 -08001741
Kenny Root49468902013-03-19 13:41:33 -07001742 if (targetUid == -1) {
1743 targetUid = callingUid;
1744 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001745 return ::PERMISSION_DENIED;
1746 }
1747
Kenny Root07438c82012-11-02 15:41:02 -07001748 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001749 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001750
Kenny Root655b9582013-04-04 08:37:42 -07001751 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001752 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1753 }
1754 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001755 }
1756
Kenny Root49468902013-03-19 13:41:33 -07001757 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001758 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001759 pid_t spid = IPCThreadState::self()->getCallingPid();
1760 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001761 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001762 return ::PERMISSION_DENIED;
1763 }
Kenny Root70e3a862012-02-15 17:20:23 -08001764
Kenny Root49468902013-03-19 13:41:33 -07001765 if (targetUid == -1) {
1766 targetUid = callingUid;
1767 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001768 return ::PERMISSION_DENIED;
1769 }
1770
Kenny Root07438c82012-11-02 15:41:02 -07001771 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001772 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001773
Robin Lee4b84fdc2014-09-24 11:56:57 +01001774 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1775 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001776 }
Kenny Root07438c82012-11-02 15:41:02 -07001777 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001778 }
1779
Kenny Root07438c82012-11-02 15:41:02 -07001780 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001781 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001782 pid_t spid = IPCThreadState::self()->getCallingPid();
1783 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001784 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001785 return ::PERMISSION_DENIED;
1786 }
1787
Robin Lee4b84fdc2014-09-24 11:56:57 +01001788 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001789 }
1790
Kenny Root07438c82012-11-02 15:41:02 -07001791 /*
1792 * Here is the history. To improve the security, the parameters to generate the
1793 * master key has been changed. To make a seamless transition, we update the
1794 * file using the same password when the user unlock it for the first time. If
1795 * any thing goes wrong during the transition, the new file will not overwrite
1796 * the old one. This avoids permanent damages of the existing data.
1797 */
1798 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001799 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001800 pid_t spid = IPCThreadState::self()->getCallingPid();
1801 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001802 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001803 return ::PERMISSION_DENIED;
1804 }
Kenny Root70e3a862012-02-15 17:20:23 -08001805
Kenny Root07438c82012-11-02 15:41:02 -07001806 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001807
Kenny Root655b9582013-04-04 08:37:42 -07001808 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001809 case ::STATE_UNINITIALIZED: {
1810 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001811 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001812 }
1813 case ::STATE_NO_ERROR: {
1814 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001815 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001816 }
1817 case ::STATE_LOCKED: {
1818 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001819 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001820 }
1821 }
1822 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001823 }
1824
Kenny Root07438c82012-11-02 15:41:02 -07001825 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001826 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001827 pid_t spid = IPCThreadState::self()->getCallingPid();
1828 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001829 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001830 return ::PERMISSION_DENIED;
1831 }
Kenny Root70e3a862012-02-15 17:20:23 -08001832
Kenny Root655b9582013-04-04 08:37:42 -07001833 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001834 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001835 ALOGD("calling lock in state: %d", state);
1836 return state;
1837 }
1838
Kenny Root655b9582013-04-04 08:37:42 -07001839 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001840 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001841 }
1842
Kenny Root07438c82012-11-02 15:41:02 -07001843 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001844 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001845 pid_t spid = IPCThreadState::self()->getCallingPid();
1846 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001847 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001848 return ::PERMISSION_DENIED;
1849 }
1850
Kenny Root655b9582013-04-04 08:37:42 -07001851 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001852 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001853 ALOGD("calling unlock when not locked");
1854 return state;
1855 }
1856
1857 const String8 password8(pw);
1858 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001859 }
1860
Kenny Root07438c82012-11-02 15:41:02 -07001861 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001862 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001863 pid_t spid = IPCThreadState::self()->getCallingPid();
1864 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001865 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001866 return -1;
1867 }
Kenny Root70e3a862012-02-15 17:20:23 -08001868
Kenny Root655b9582013-04-04 08:37:42 -07001869 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001870 }
1871
Kenny Root96427ba2013-08-16 14:02:41 -07001872 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1873 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001874 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001875 pid_t spid = IPCThreadState::self()->getCallingPid();
1876 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001877 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001878 return ::PERMISSION_DENIED;
1879 }
Kenny Root70e3a862012-02-15 17:20:23 -08001880
Kenny Root49468902013-03-19 13:41:33 -07001881 if (targetUid == -1) {
1882 targetUid = callingUid;
1883 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001884 return ::PERMISSION_DENIED;
1885 }
1886
Kenny Root655b9582013-04-04 08:37:42 -07001887 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001888 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1889 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001890 return state;
1891 }
Kenny Root70e3a862012-02-15 17:20:23 -08001892
Kenny Root07438c82012-11-02 15:41:02 -07001893 uint8_t* data;
1894 size_t dataLength;
1895 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001896 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001897
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001898 const keymaster1_device_t* device = mKeyStore->getDevice();
1899 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001900 if (device == NULL) {
1901 return ::SYSTEM_ERROR;
1902 }
1903
1904 if (device->generate_keypair == NULL) {
1905 return ::SYSTEM_ERROR;
1906 }
1907
Kenny Root17208e02013-09-04 13:56:03 -07001908 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001909 keymaster_dsa_keygen_params_t dsa_params;
1910 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001911
Kenny Root96427ba2013-08-16 14:02:41 -07001912 if (keySize == -1) {
1913 keySize = DSA_DEFAULT_KEY_SIZE;
1914 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1915 || keySize > DSA_MAX_KEY_SIZE) {
1916 ALOGI("invalid key size %d", keySize);
1917 return ::SYSTEM_ERROR;
1918 }
1919 dsa_params.key_size = keySize;
1920
1921 if (args->size() == 3) {
1922 sp<KeystoreArg> gArg = args->itemAt(0);
1923 sp<KeystoreArg> pArg = args->itemAt(1);
1924 sp<KeystoreArg> qArg = args->itemAt(2);
1925
1926 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1927 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1928 dsa_params.generator_len = gArg->size();
1929
1930 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1931 dsa_params.prime_p_len = pArg->size();
1932
1933 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1934 dsa_params.prime_q_len = qArg->size();
1935 } else {
1936 ALOGI("not all DSA parameters were read");
1937 return ::SYSTEM_ERROR;
1938 }
1939 } else if (args->size() != 0) {
1940 ALOGI("DSA args must be 3");
1941 return ::SYSTEM_ERROR;
1942 }
1943
Kenny Root1d448c02013-11-21 10:36:53 -08001944 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001945 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1946 } else {
1947 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001948 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1949 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001950 }
1951 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001952 keymaster_ec_keygen_params_t ec_params;
1953 memset(&ec_params, '\0', sizeof(ec_params));
1954
1955 if (keySize == -1) {
1956 keySize = EC_DEFAULT_KEY_SIZE;
1957 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1958 ALOGI("invalid key size %d", keySize);
1959 return ::SYSTEM_ERROR;
1960 }
1961 ec_params.field_size = keySize;
1962
Kenny Root1d448c02013-11-21 10:36:53 -08001963 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001964 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1965 } else {
1966 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001967 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001968 }
Kenny Root96427ba2013-08-16 14:02:41 -07001969 } else if (keyType == EVP_PKEY_RSA) {
1970 keymaster_rsa_keygen_params_t rsa_params;
1971 memset(&rsa_params, '\0', sizeof(rsa_params));
1972 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1973
1974 if (keySize == -1) {
1975 keySize = RSA_DEFAULT_KEY_SIZE;
1976 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1977 ALOGI("invalid key size %d", keySize);
1978 return ::SYSTEM_ERROR;
1979 }
1980 rsa_params.modulus_size = keySize;
1981
1982 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001983 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001984 return ::SYSTEM_ERROR;
1985 } else if (args->size() == 1) {
1986 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1987 if (pubExpBlob != NULL) {
1988 Unique_BIGNUM pubExpBn(
1989 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1990 pubExpBlob->size(), NULL));
1991 if (pubExpBn.get() == NULL) {
1992 ALOGI("Could not convert public exponent to BN");
1993 return ::SYSTEM_ERROR;
1994 }
1995 unsigned long pubExp = BN_get_word(pubExpBn.get());
1996 if (pubExp == 0xFFFFFFFFL) {
1997 ALOGI("cannot represent public exponent as a long value");
1998 return ::SYSTEM_ERROR;
1999 }
2000 rsa_params.public_exponent = pubExp;
2001 }
2002 }
2003
2004 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
2005 } else {
2006 ALOGW("Unsupported key type %d", keyType);
2007 rc = -1;
2008 }
2009
Kenny Root07438c82012-11-02 15:41:02 -07002010 if (rc) {
2011 return ::SYSTEM_ERROR;
2012 }
2013
Kenny Root655b9582013-04-04 08:37:42 -07002014 String8 name8(name);
2015 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002016
2017 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2018 free(data);
2019
Kenny Rootee8068b2013-10-07 09:49:15 -07002020 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002021 keyBlob.setFallback(isFallback);
2022
Kenny Root655b9582013-04-04 08:37:42 -07002023 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08002024 }
2025
Kenny Rootf9119d62013-04-03 09:22:15 -07002026 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2027 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002028 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002029 pid_t spid = IPCThreadState::self()->getCallingPid();
2030 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002031 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002032 return ::PERMISSION_DENIED;
2033 }
Kenny Root07438c82012-11-02 15:41:02 -07002034
Kenny Root49468902013-03-19 13:41:33 -07002035 if (targetUid == -1) {
2036 targetUid = callingUid;
2037 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002038 return ::PERMISSION_DENIED;
2039 }
2040
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002041 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002042 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002043 ALOGD("calling import in state: %d", state);
2044 return state;
2045 }
2046
2047 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002048 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002049
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002050 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002051 }
2052
Kenny Root07438c82012-11-02 15:41:02 -07002053 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2054 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002055 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002056 pid_t spid = IPCThreadState::self()->getCallingPid();
2057 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002058 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002059 return ::PERMISSION_DENIED;
2060 }
Kenny Root07438c82012-11-02 15:41:02 -07002061
Kenny Root07438c82012-11-02 15:41:02 -07002062 Blob keyBlob;
2063 String8 name8(name);
2064
Kenny Rootd38a0b02013-02-13 12:59:14 -08002065 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002066 int rc;
2067
Kenny Root655b9582013-04-04 08:37:42 -07002068 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002069 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002070 if (responseCode != ::NO_ERROR) {
2071 return responseCode;
2072 }
2073
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002074 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002075 if (device == NULL) {
2076 ALOGE("no keymaster device; cannot sign");
2077 return ::SYSTEM_ERROR;
2078 }
2079
2080 if (device->sign_data == NULL) {
2081 ALOGE("device doesn't implement signing");
2082 return ::SYSTEM_ERROR;
2083 }
2084
2085 keymaster_rsa_sign_params_t params;
2086 params.digest_type = DIGEST_NONE;
2087 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002088 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2089 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002090 if (rc) {
2091 ALOGW("device couldn't sign data");
2092 return ::SYSTEM_ERROR;
2093 }
2094
2095 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002096 }
2097
Kenny Root07438c82012-11-02 15:41:02 -07002098 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2099 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002100 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002101 pid_t spid = IPCThreadState::self()->getCallingPid();
2102 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002103 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002104 return ::PERMISSION_DENIED;
2105 }
Kenny Root70e3a862012-02-15 17:20:23 -08002106
Kenny Root655b9582013-04-04 08:37:42 -07002107 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002108 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002109 ALOGD("calling verify in state: %d", state);
2110 return state;
2111 }
Kenny Root70e3a862012-02-15 17:20:23 -08002112
Kenny Root07438c82012-11-02 15:41:02 -07002113 Blob keyBlob;
2114 String8 name8(name);
2115 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002116
Kenny Root655b9582013-04-04 08:37:42 -07002117 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002118 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002119 if (responseCode != ::NO_ERROR) {
2120 return responseCode;
2121 }
Kenny Root70e3a862012-02-15 17:20:23 -08002122
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002123 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002124 if (device == NULL) {
2125 return ::SYSTEM_ERROR;
2126 }
Kenny Root70e3a862012-02-15 17:20:23 -08002127
Kenny Root07438c82012-11-02 15:41:02 -07002128 if (device->verify_data == NULL) {
2129 return ::SYSTEM_ERROR;
2130 }
Kenny Root70e3a862012-02-15 17:20:23 -08002131
Kenny Root07438c82012-11-02 15:41:02 -07002132 keymaster_rsa_sign_params_t params;
2133 params.digest_type = DIGEST_NONE;
2134 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002135
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002136 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2137 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002138 if (rc) {
2139 return ::SYSTEM_ERROR;
2140 } else {
2141 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002142 }
2143 }
Kenny Root07438c82012-11-02 15:41:02 -07002144
2145 /*
2146 * TODO: The abstraction between things stored in hardware and regular blobs
2147 * of data stored on the filesystem should be moved down to keystore itself.
2148 * Unfortunately the Java code that calls this has naming conventions that it
2149 * knows about. Ideally keystore shouldn't be used to store random blobs of
2150 * data.
2151 *
2152 * Until that happens, it's necessary to have a separate "get_pubkey" and
2153 * "del_key" since the Java code doesn't really communicate what it's
2154 * intentions are.
2155 */
2156 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002157 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002158 pid_t spid = IPCThreadState::self()->getCallingPid();
2159 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002160 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002161 return ::PERMISSION_DENIED;
2162 }
Kenny Root07438c82012-11-02 15:41:02 -07002163
Kenny Root07438c82012-11-02 15:41:02 -07002164 Blob keyBlob;
2165 String8 name8(name);
2166
Kenny Rootd38a0b02013-02-13 12:59:14 -08002167 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002168
Kenny Root655b9582013-04-04 08:37:42 -07002169 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002170 TYPE_KEY_PAIR);
2171 if (responseCode != ::NO_ERROR) {
2172 return responseCode;
2173 }
2174
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002175 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002176 if (device == NULL) {
2177 return ::SYSTEM_ERROR;
2178 }
2179
2180 if (device->get_keypair_public == NULL) {
2181 ALOGE("device has no get_keypair_public implementation!");
2182 return ::SYSTEM_ERROR;
2183 }
2184
Kenny Root17208e02013-09-04 13:56:03 -07002185 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002186 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2187 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002188 if (rc) {
2189 return ::SYSTEM_ERROR;
2190 }
2191
2192 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002193 }
Kenny Root07438c82012-11-02 15:41:02 -07002194
Kenny Root49468902013-03-19 13:41:33 -07002195 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002196 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002197 pid_t spid = IPCThreadState::self()->getCallingPid();
2198 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002199 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002200 return ::PERMISSION_DENIED;
2201 }
Kenny Root07438c82012-11-02 15:41:02 -07002202
Kenny Root49468902013-03-19 13:41:33 -07002203 if (targetUid == -1) {
2204 targetUid = callingUid;
2205 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002206 return ::PERMISSION_DENIED;
2207 }
2208
Kenny Root07438c82012-11-02 15:41:02 -07002209 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002210 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002211 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002212 }
2213
2214 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002215 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002216 pid_t spid = IPCThreadState::self()->getCallingPid();
2217 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002218 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002219 return ::PERMISSION_DENIED;
2220 }
Kenny Root07438c82012-11-02 15:41:02 -07002221
Kenny Root655b9582013-04-04 08:37:42 -07002222 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002223 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002224 ALOGD("calling grant in state: %d", state);
2225 return state;
2226 }
2227
2228 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002229 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002230
Kenny Root655b9582013-04-04 08:37:42 -07002231 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002232 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2233 }
2234
Kenny Root655b9582013-04-04 08:37:42 -07002235 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002236 return ::NO_ERROR;
2237 }
2238
2239 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002240 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002241 pid_t spid = IPCThreadState::self()->getCallingPid();
2242 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002243 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002244 return ::PERMISSION_DENIED;
2245 }
Kenny Root07438c82012-11-02 15:41:02 -07002246
Kenny Root655b9582013-04-04 08:37:42 -07002247 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002248 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002249 ALOGD("calling ungrant in state: %d", state);
2250 return state;
2251 }
2252
2253 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002254 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002255
Kenny Root655b9582013-04-04 08:37:42 -07002256 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002257 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2258 }
2259
Kenny Root655b9582013-04-04 08:37:42 -07002260 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002261 }
2262
2263 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002264 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002265 pid_t spid = IPCThreadState::self()->getCallingPid();
2266 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002267 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002268 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002269 }
Kenny Root07438c82012-11-02 15:41:02 -07002270
2271 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002272 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002273
Kenny Root655b9582013-04-04 08:37:42 -07002274 if (access(filename.string(), R_OK) == -1) {
2275 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002276 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002277 }
2278
Kenny Root655b9582013-04-04 08:37:42 -07002279 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002280 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002281 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002282 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002283 }
2284
2285 struct stat s;
2286 int ret = fstat(fd, &s);
2287 close(fd);
2288 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002289 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002290 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002291 }
2292
Kenny Root36a9e232013-02-04 14:24:15 -08002293 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002294 }
2295
Kenny Rootd53bc922013-03-21 14:10:15 -07002296 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2297 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002298 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002299 pid_t spid = IPCThreadState::self()->getCallingPid();
2300 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002301 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002302 return -1L;
2303 }
2304
Kenny Root655b9582013-04-04 08:37:42 -07002305 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002306 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002307 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002308 return state;
2309 }
2310
Kenny Rootd53bc922013-03-21 14:10:15 -07002311 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2312 srcUid = callingUid;
2313 } else if (!is_granted_to(callingUid, srcUid)) {
2314 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002315 return ::PERMISSION_DENIED;
2316 }
2317
Kenny Rootd53bc922013-03-21 14:10:15 -07002318 if (destUid == -1) {
2319 destUid = callingUid;
2320 }
2321
2322 if (srcUid != destUid) {
2323 if (static_cast<uid_t>(srcUid) != callingUid) {
2324 ALOGD("can only duplicate from caller to other or to same uid: "
2325 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2326 return ::PERMISSION_DENIED;
2327 }
2328
2329 if (!is_granted_to(callingUid, destUid)) {
2330 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2331 return ::PERMISSION_DENIED;
2332 }
2333 }
2334
2335 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002336 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002337
Kenny Rootd53bc922013-03-21 14:10:15 -07002338 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002339 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002340
Kenny Root655b9582013-04-04 08:37:42 -07002341 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2342 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002343 return ::SYSTEM_ERROR;
2344 }
2345
Kenny Rootd53bc922013-03-21 14:10:15 -07002346 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002347 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002348 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002349 if (responseCode != ::NO_ERROR) {
2350 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002351 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002352
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002353 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002354 }
2355
Kenny Root1b0e3932013-09-05 13:06:32 -07002356 int32_t is_hardware_backed(const String16& keyType) {
2357 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002358 }
2359
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002360 int32_t clear_uid(int64_t targetUid64) {
2361 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002362 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002363 pid_t spid = IPCThreadState::self()->getCallingPid();
2364 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002365 ALOGW("permission denied for %d: clear_uid", callingUid);
2366 return ::PERMISSION_DENIED;
2367 }
2368
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002369 if (targetUid64 == -1) {
2370 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002371 } else if (!is_self_or_system(callingUid, targetUid)) {
2372 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002373 return ::PERMISSION_DENIED;
2374 }
2375
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002376 const keymaster1_device_t* device = mKeyStore->getDevice();
Kenny Roota9bb5492013-04-01 16:29:11 -07002377 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002378 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002379 return ::SYSTEM_ERROR;
2380 }
2381
Robin Lee4b84fdc2014-09-24 11:56:57 +01002382 String8 prefix = String8::format("%u_", targetUid);
2383 Vector<String16> aliases;
2384 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002385 return ::SYSTEM_ERROR;
2386 }
2387
Robin Lee4b84fdc2014-09-24 11:56:57 +01002388 for (uint32_t i = 0; i < aliases.size(); i++) {
2389 String8 name8(aliases[i]);
2390 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2391 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002392 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002393 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002394 }
2395
Robin Lee4b84fdc2014-09-24 11:56:57 +01002396 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002397 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2398 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002399
Robin Lee4e865752014-08-19 17:37:55 +01002400 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002401 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002402 return ::PERMISSION_DENIED;
2403 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002404 if (!is_self_or_system(callingUid, targetUid)) {
2405 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002406 return ::PERMISSION_DENIED;
2407 }
2408
Robin Lee4b84fdc2014-09-24 11:56:57 +01002409 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002410 }
2411
2412 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2413 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2414 pid_t spid = IPCThreadState::self()->getCallingPid();
2415 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2416 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2417 return ::PERMISSION_DENIED;
2418 }
2419 if (callingUid != AID_SYSTEM) {
2420 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2421 return ::PERMISSION_DENIED;
2422 }
2423 if (sourceUid == targetUid) {
2424 return ::SYSTEM_ERROR;
2425 }
2426
2427 // Initialise user keystore with existing master key held in-memory
2428 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2429 }
2430
2431 int32_t password_uid(const String16& pw, int32_t targetUid) {
2432 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2433 pid_t spid = IPCThreadState::self()->getCallingPid();
2434 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2435 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2436 return ::PERMISSION_DENIED;
2437 }
2438 if (callingUid != AID_SYSTEM) {
2439 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2440 return ::PERMISSION_DENIED;
2441 }
2442
2443 const String8 password8(pw);
2444
2445 switch (mKeyStore->getState(targetUid)) {
2446 case ::STATE_UNINITIALIZED: {
2447 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2448 return mKeyStore->initializeUser(password8, targetUid);
2449 }
2450 case ::STATE_NO_ERROR: {
2451 // rewrite master key with new password.
2452 return mKeyStore->writeMasterKey(password8, targetUid);
2453 }
2454 case ::STATE_LOCKED: {
2455 // read master key, decrypt with password, initialize mMasterKey*.
2456 return mKeyStore->readMasterKey(password8, targetUid);
2457 }
2458 }
2459 return ::SYSTEM_ERROR;
2460 }
2461
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002462 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2463 const keymaster1_device_t* device = mKeyStore->getDevice();
2464 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2465 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2466 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2467 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2468 device->add_rng_entropy != NULL) {
2469 devResult = device->add_rng_entropy(device, data, dataLength);
2470 }
2471 if (fallback->add_rng_entropy) {
2472 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2473 }
2474 if (devResult) {
2475 return devResult;
2476 }
2477 if (fallbackResult) {
2478 return fallbackResult;
2479 }
2480 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002481 }
2482
Chad Brubaker17d68b92015-02-05 22:04:16 -08002483 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002484 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2485 KeyCharacteristics* outCharacteristics) {
Chad Brubaker17d68b92015-02-05 22:04:16 -08002486 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2487 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2488 if (!has_permission(callingUid, P_INSERT, callingPid)) {
2489 ALOGW("permission denied for %d: generateKey", callingUid);
2490 return ::PERMISSION_DENIED;
2491 }
2492
2493 State state = mKeyStore->getState(callingUid);
2494 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2495 ALOGW("calling generate in state: %d", state);
2496 return state;
2497 }
2498
2499 if (uid == -1) {
2500 uid = callingUid;
2501 } else if (!is_granted_to(callingUid, uid)) {
2502 return ::PERMISSION_DENIED;
2503 }
2504
Chad Brubaker17d68b92015-02-05 22:04:16 -08002505 int rc = KM_ERROR_UNIMPLEMENTED;
2506 bool isFallback = false;
2507 keymaster_key_blob_t blob;
2508 keymaster_key_characteristics_t *out = NULL;
2509
2510 const keymaster1_device_t* device = mKeyStore->getDevice();
2511 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2512 if (device == NULL) {
2513 return ::SYSTEM_ERROR;
2514 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002515 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002516 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2517 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002518 if (!entropy) {
2519 rc = KM_ERROR_OK;
2520 } else if (device->add_rng_entropy) {
2521 rc = device->add_rng_entropy(device, entropy, entropyLength);
2522 } else {
2523 rc = KM_ERROR_UNIMPLEMENTED;
2524 }
2525 if (rc == KM_ERROR_OK) {
2526 rc = device->generate_key(device, params.params.data(), params.params.size(),
2527 &blob, &out);
2528 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002529 }
2530 // If the HW device didn't support generate_key or generate_key failed
2531 // fall back to the software implementation.
2532 if (rc && fallback->generate_key != NULL) {
2533 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002534 if (!entropy) {
2535 rc = KM_ERROR_OK;
2536 } else if (fallback->add_rng_entropy) {
2537 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2538 } else {
2539 rc = KM_ERROR_UNIMPLEMENTED;
2540 }
2541 if (rc == KM_ERROR_OK) {
2542 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2543 &blob,
2544 &out);
2545 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002546 }
2547
2548 if (out) {
2549 if (outCharacteristics) {
2550 outCharacteristics->characteristics = *out;
2551 } else {
2552 keymaster_free_characteristics(out);
2553 }
2554 free(out);
2555 }
2556
2557 if (rc) {
2558 return rc;
2559 }
2560
2561 String8 name8(name);
2562 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2563
2564 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2565 keyBlob.setFallback(isFallback);
2566 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2567
2568 free(const_cast<uint8_t*>(blob.key_material));
2569
2570 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002571 }
2572
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002573 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002574 const keymaster_blob_t* clientId,
2575 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002576 KeyCharacteristics* outCharacteristics) {
2577
2578 if (!outCharacteristics) {
2579 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2580 }
2581
2582 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2583
2584 Blob keyBlob;
2585 String8 name8(name);
2586 int rc;
2587
2588 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2589 TYPE_KEYMASTER_10);
2590 if (responseCode != ::NO_ERROR) {
2591 return responseCode;
2592 }
2593 keymaster_key_blob_t key;
2594 key.key_material_size = keyBlob.getLength();
2595 key.key_material = keyBlob.getValue();
2596 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2597 keymaster_key_characteristics_t *out = NULL;
2598 if (!dev->get_key_characteristics) {
2599 ALOGW("device does not implement get_key_characteristics");
2600 return KM_ERROR_UNIMPLEMENTED;
2601 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002602 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002603 if (out) {
2604 outCharacteristics->characteristics = *out;
2605 free(out);
2606 }
2607 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002608 }
2609
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002610 int32_t importKey(const String16& name, const KeymasterArguments& params,
2611 keymaster_key_format_t format, const uint8_t *keyData,
2612 size_t keyLength, int uid, int flags,
2613 KeyCharacteristics* outCharacteristics) {
2614 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2615 pid_t spid = IPCThreadState::self()->getCallingPid();
2616 if (!has_permission(callingUid, P_INSERT, spid)) {
2617 ALOGW("permission denied for %d: importKey", callingUid);
2618 return ::PERMISSION_DENIED;
2619 }
2620
2621 State state = mKeyStore->getState(callingUid);
2622 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2623 ALOGW("calling importKey in state: %d", state);
2624 return state;
2625 }
2626
2627 if (uid == -1) {
2628 uid = callingUid;
2629 } else if (!is_granted_to(callingUid, uid)) {
2630 ALOGW("not granted to %d %d", callingUid, uid);
2631 return ::PERMISSION_DENIED;
2632 }
2633
2634 int rc = KM_ERROR_UNIMPLEMENTED;
2635 bool isFallback = false;
2636 keymaster_key_blob_t blob;
2637 keymaster_key_characteristics_t *out = NULL;
2638
2639 const keymaster1_device_t* device = mKeyStore->getDevice();
2640 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2641 if (device == NULL) {
2642 return ::SYSTEM_ERROR;
2643 }
2644 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2645 device->import_key != NULL) {
2646 rc = device->import_key(device, params.params.data(), params.params.size(),
2647 format, keyData, keyLength, &blob, &out);
2648 }
2649 if (rc && fallback->import_key != NULL) {
2650 isFallback = true;
2651 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2652 format, keyData, keyLength, &blob, &out);
2653 }
2654 if (out) {
2655 if (outCharacteristics) {
2656 outCharacteristics->characteristics = *out;
2657 } else {
2658 keymaster_free_characteristics(out);
2659 }
2660 free(out);
2661 }
2662 if (rc) {
2663 return rc;
2664 }
2665
2666 String8 name8(name);
2667 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2668
2669 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2670 keyBlob.setFallback(isFallback);
2671 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2672
2673 free((void*) blob.key_material);
2674
2675 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002676 }
2677
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002678 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002679 const keymaster_blob_t* clientId,
2680 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002681
2682 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2683
2684 Blob keyBlob;
2685 String8 name8(name);
2686 int rc;
2687
2688 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2689 TYPE_KEYMASTER_10);
2690 if (responseCode != ::NO_ERROR) {
2691 result->resultCode = responseCode;
2692 return;
2693 }
2694 keymaster_key_blob_t key;
2695 key.key_material_size = keyBlob.getLength();
2696 key.key_material = keyBlob.getValue();
2697 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2698 if (!dev->export_key) {
2699 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2700 return;
2701 }
2702 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002703 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002704 &ptr, &result->dataLength);
2705 result->exportData.reset(ptr);
2706 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002707 }
2708
Chad Brubaker06801e02015-03-31 15:13:13 -07002709 /**
2710 * Check that all keymaster_key_param_t's provided by the application are
2711 * allowed. Any parameter that keystore adds itself should be disallowed here.
2712 */
2713 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2714 for (auto param: params) {
2715 switch (param.tag) {
2716 case KM_TAG_AUTH_TOKEN:
2717 return false;
2718 default:
2719 break;
2720 }
2721 }
2722 return true;
2723 }
2724
2725 int authorizeOperation(const keymaster_key_blob_t& key,
2726 keymaster_operation_handle_t handle,
2727 std::vector<keymaster_key_param_t>* params,
2728 bool failOnTokenMissing=true) {
2729 if (!checkAllowedOperationParams(*params)) {
2730 return KM_ERROR_INVALID_ARGUMENT;
2731 }
2732 // Check for auth token and add it to the param list if present.
2733 const hw_auth_token_t* authToken;
2734 switch (mAuthTokenTable.FindAuthorization(key, handle, &authToken)) {
2735 case keymaster::AuthTokenTable::OK:
2736 // Auth token found.
2737 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2738 reinterpret_cast<const uint8_t*>(authToken),
2739 sizeof(hw_auth_token_t)));
2740 break;
2741 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2742 return KM_ERROR_OK;
2743 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2744 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2745 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2746 if (failOnTokenMissing) {
2747 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2748 }
2749 break;
2750 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2751 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2752 default:
2753 return KM_ERROR_INVALID_ARGUMENT;
2754 }
2755 // TODO: Enforce the rest of authorization
2756 return KM_ERROR_OK;
2757 }
2758
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002759 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002760 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2761 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002762 if (!result || !outParams) {
2763 ALOGE("Unexpected null arguments to begin()");
2764 return;
2765 }
2766 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2767 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2768 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2769 result->resultCode = ::PERMISSION_DENIED;
2770 return;
2771 }
2772 Blob keyBlob;
2773 String8 name8(name);
2774 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2775 TYPE_KEYMASTER_10);
2776 if (responseCode != ::NO_ERROR) {
2777 result->resultCode = responseCode;
2778 return;
2779 }
2780 keymaster_key_blob_t key;
2781 key.key_material_size = keyBlob.getLength();
2782 key.key_material = keyBlob.getValue();
2783 keymaster_key_param_t* out;
2784 size_t outSize;
2785 keymaster_operation_handle_t handle;
2786 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002787 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002788 std::vector<keymaster_key_param_t> opParams(params.params);
2789 // Don't require an auth token for the call to begin, authentication can
2790 // require an operation handle. Update and finish will require the token
2791 // be present and valid.
2792 int32_t authResult = authorizeOperation(key, 0, &opParams,
2793 /*failOnTokenMissing*/ false);
2794 if (authResult) {
2795 result->resultCode = err;
2796 return;
2797 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002798 // Add entropy to the device first.
2799 if (entropy) {
2800 if (dev->add_rng_entropy) {
2801 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2802 } else {
2803 err = KM_ERROR_UNIMPLEMENTED;
2804 }
2805 if (err) {
2806 result->resultCode = err;
2807 return;
2808 }
2809 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002810 // Don't do an auth check here, we need begin to succeed for
2811 // per-operation auth. update/finish will be doing the auth checks.
2812 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2813 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002814
2815 // If there are too many operations abort the oldest operation that was
2816 // started as pruneable and try again.
2817 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2818 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2819 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2820 if (abort(oldest) != ::NO_ERROR) {
2821 break;
2822 }
2823 err = dev->begin(dev, purpose, &key, params.params.data(),
2824 params.params.size(), &out, &outSize,
2825 &handle);
2826 }
2827 if (err) {
2828 result->resultCode = err;
2829 return;
2830 }
2831 if (out) {
2832 outParams->params.assign(out, out + outSize);
2833 free(out);
2834 }
2835
Chad Brubaker06801e02015-03-31 15:13:13 -07002836 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken, key,
2837 pruneable);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002838 result->resultCode = ::NO_ERROR;
2839 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002840 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002841 }
2842
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002843 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2844 size_t dataLength, OperationResult* result) {
2845 const keymaster1_device_t* dev;
2846 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002847 Unique_keymaster_key_blob key(new keymaster_key_blob_t);
2848 *key = {NULL, 0};
2849 if (!mOperationMap.getOperation(token, &handle, &dev, key.get())) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002850 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2851 return;
2852 }
2853 uint8_t* output_buf = NULL;
2854 size_t output_length = 0;
2855 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002856 std::vector<keymaster_key_param_t> opParams(params.params);
2857 int32_t authResult = authorizeOperation(*key, handle, &opParams);
2858 if (authResult) {
2859 result->resultCode = authResult;
2860 return;
2861 }
2862 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2863 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002864 result->data.reset(output_buf);
2865 result->dataLength = output_length;
2866 result->inputConsumed = consumed;
2867 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002868 }
2869
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002870 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2871 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
2872 const keymaster1_device_t* dev;
2873 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002874 Unique_keymaster_key_blob key(new keymaster_key_blob_t);
2875 *key = {NULL, 0};
2876 if (!mOperationMap.getOperation(token, &handle, &dev, key.get())) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002877 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2878 return;
2879 }
2880 uint8_t* output_buf = NULL;
2881 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002882 std::vector<keymaster_key_param_t> opParams(params.params);
2883 int32_t authResult = authorizeOperation(*key, handle, &opParams);
2884 if (authResult) {
2885 result->resultCode = authResult;
2886 return;
2887 }
2888 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2889 signature, signatureLength, &output_buf,
2890 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002891 // Remove the operation regardless of the result
2892 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002893 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002894 result->data.reset(output_buf);
2895 result->dataLength = output_length;
2896 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002897 }
2898
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002899 int32_t abort(const sp<IBinder>& token) {
2900 const keymaster1_device_t* dev;
2901 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002902 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002903 return KM_ERROR_INVALID_OPERATION_HANDLE;
2904 }
2905 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002906 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002907 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002908 rc = KM_ERROR_UNIMPLEMENTED;
2909 } else {
2910 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002911 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002912 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002913 if (rc) {
2914 return rc;
2915 }
2916 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002917 }
2918
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002919 bool isOperationAuthorized(const sp<IBinder>& token) {
2920 const keymaster1_device_t* dev;
2921 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002922 Unique_keymaster_key_blob key(new keymaster_key_blob_t);
2923 *key = {NULL, 0};
2924 if(!mOperationMap.getOperation(token, &handle, &dev, key.get())) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002925 return false;
2926 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002927 std::vector<keymaster_key_param_t> ignored;
2928 int32_t authResult = authorizeOperation(*key, handle, &ignored);
2929 return authResult == KM_ERROR_OK;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002930 }
2931
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002932 int32_t addAuthToken(const uint8_t* token, size_t length) {
2933 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2934 pid_t spid = IPCThreadState::self()->getCallingPid();
2935 if (!has_permission(callingUid, P_ADD_AUTH, spid)) {
2936 ALOGW("permission denied for %d: addAuthToken", callingUid);
2937 return ::PERMISSION_DENIED;
2938 }
2939 if (length != sizeof(hw_auth_token_t)) {
2940 return KM_ERROR_INVALID_ARGUMENT;
2941 }
2942 hw_auth_token_t* authToken = new hw_auth_token_t;
2943 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2944 // The table takes ownership of authToken.
2945 mAuthTokenTable.AddAuthenticationToken(authToken);
2946 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002947 }
2948
Kenny Root07438c82012-11-02 15:41:02 -07002949private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002950 inline bool isKeystoreUnlocked(State state) {
2951 switch (state) {
2952 case ::STATE_NO_ERROR:
2953 return true;
2954 case ::STATE_UNINITIALIZED:
2955 case ::STATE_LOCKED:
2956 return false;
2957 }
2958 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002959 }
2960
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002961 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002962 const int32_t device_api = device->common.module->module_api_version;
2963 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2964 switch (keyType) {
2965 case TYPE_RSA:
2966 case TYPE_DSA:
2967 case TYPE_EC:
2968 return true;
2969 default:
2970 return false;
2971 }
2972 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2973 switch (keyType) {
2974 case TYPE_RSA:
2975 return true;
2976 case TYPE_DSA:
2977 return device->flags & KEYMASTER_SUPPORTS_DSA;
2978 case TYPE_EC:
2979 return device->flags & KEYMASTER_SUPPORTS_EC;
2980 default:
2981 return false;
2982 }
2983 } else {
2984 return keyType == TYPE_RSA;
2985 }
2986 }
2987
Kenny Root07438c82012-11-02 15:41:02 -07002988 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002989 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002990 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07002991};
2992
2993}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002994
2995int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002996 if (argc < 2) {
2997 ALOGE("A directory must be specified!");
2998 return 1;
2999 }
3000 if (chdir(argv[1]) == -1) {
3001 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3002 return 1;
3003 }
3004
3005 Entropy entropy;
3006 if (!entropy.open()) {
3007 return 1;
3008 }
Kenny Root70e3a862012-02-15 17:20:23 -08003009
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07003010 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003011 if (keymaster_device_initialize(&dev)) {
3012 ALOGE("keystore keymaster could not be initialized; exiting");
3013 return 1;
3014 }
3015
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003016 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003017 if (fallback_keymaster_device_initialize(&fallback)) {
3018 ALOGE("software keymaster could not be initialized; exiting");
3019 return 1;
3020 }
3021
Riley Spahneaabae92014-06-30 12:39:52 -07003022 ks_is_selinux_enabled = is_selinux_enabled();
3023 if (ks_is_selinux_enabled) {
3024 union selinux_callback cb;
3025 cb.func_log = selinux_log_callback;
3026 selinux_set_callback(SELINUX_CB_LOG, cb);
3027 if (getcon(&tctx) != 0) {
3028 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3029 return -1;
3030 }
3031 } else {
3032 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3033 }
3034
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003035 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003036 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003037 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3038 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3039 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3040 if (ret != android::OK) {
3041 ALOGE("Couldn't register binder service!");
3042 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003043 }
Kenny Root07438c82012-11-02 15:41:02 -07003044
3045 /*
3046 * We're the only thread in existence, so we're just going to process
3047 * Binder transaction as a single-threaded program.
3048 */
3049 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003050
3051 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003052 return 1;
3053}