blob: 13612b79758c6387a0248104a3277532fd04df17 [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
Chad Brubaker919cb2a2015-02-05 21:58:25 -080046#include <keymaster/soft_keymaster_device.h>
Shawn Willden9e5016a2015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Shawn Willden9e5016a2015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willdenef572b62015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100155 P_TEST = 1 << 0,
156 P_GET = 1 << 1,
157 P_INSERT = 1 << 2,
158 P_DELETE = 1 << 3,
159 P_EXIST = 1 << 4,
160 P_SAW = 1 << 5,
161 P_RESET = 1 << 6,
162 P_PASSWORD = 1 << 7,
163 P_LOCK = 1 << 8,
164 P_UNLOCK = 1 << 9,
165 P_ZERO = 1 << 10,
166 P_SIGN = 1 << 11,
167 P_VERIFY = 1 << 12,
168 P_GRANT = 1 << 13,
169 P_DUPLICATE = 1 << 14,
170 P_CLEAR_UID = 1 << 15,
171 P_RESET_UID = 1 << 16,
172 P_SYNC_UID = 1 << 17,
173 P_PASSWORD_UID = 1 << 18,
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700174 P_ADD_AUTH = 1 << 19,
Kenny Root07438c82012-11-02 15:41:02 -0700175} perm_t;
176
177static struct user_euid {
178 uid_t uid;
179 uid_t euid;
180} user_euids[] = {
181 {AID_VPN, AID_SYSTEM},
182 {AID_WIFI, AID_SYSTEM},
183 {AID_ROOT, AID_SYSTEM},
184};
185
Riley Spahneaabae92014-06-30 12:39:52 -0700186/* perm_labels associcated with keystore_key SELinux class verbs. */
187const char *perm_labels[] = {
188 "test",
189 "get",
190 "insert",
191 "delete",
192 "exist",
193 "saw",
194 "reset",
195 "password",
196 "lock",
197 "unlock",
198 "zero",
199 "sign",
200 "verify",
201 "grant",
202 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100203 "clear_uid",
204 "reset_uid",
205 "sync_uid",
206 "password_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700207 "add_auth",
Riley Spahneaabae92014-06-30 12:39:52 -0700208};
209
Kenny Root07438c82012-11-02 15:41:02 -0700210static struct user_perm {
211 uid_t uid;
212 perm_t perms;
213} user_perms[] = {
214 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
215 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
216 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
217 {AID_ROOT, static_cast<perm_t>(P_GET) },
218};
219
220static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
221 | P_VERIFY);
222
Riley Spahneaabae92014-06-30 12:39:52 -0700223static char *tctx;
224static int ks_is_selinux_enabled;
225
226static const char *get_perm_label(perm_t perm) {
227 unsigned int index = ffs(perm);
228 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
229 return perm_labels[index - 1];
230 } else {
231 ALOGE("Keystore: Failed to retrieve permission label.\n");
232 abort();
233 }
234}
235
Kenny Root655b9582013-04-04 08:37:42 -0700236/**
237 * Returns the app ID (in the Android multi-user sense) for the current
238 * UNIX UID.
239 */
240static uid_t get_app_id(uid_t uid) {
241 return uid % AID_USER;
242}
243
244/**
245 * Returns the user ID (in the Android multi-user sense) for the current
246 * UNIX UID.
247 */
248static uid_t get_user_id(uid_t uid) {
249 return uid / AID_USER;
250}
251
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700252static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700253 if (!ks_is_selinux_enabled) {
254 return true;
255 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000256
Riley Spahneaabae92014-06-30 12:39:52 -0700257 char *sctx = NULL;
258 const char *selinux_class = "keystore_key";
259 const char *str_perm = get_perm_label(perm);
260
261 if (!str_perm) {
262 return false;
263 }
264
265 if (getpidcon(spid, &sctx) != 0) {
266 ALOGE("SELinux: Failed to get source pid context.\n");
267 return false;
268 }
269
270 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
271 NULL) == 0;
272 freecon(sctx);
273 return allowed;
274}
275
276static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700277 // All system users are equivalent for multi-user support.
278 if (get_app_id(uid) == AID_SYSTEM) {
279 uid = AID_SYSTEM;
280 }
281
Kenny Root07438c82012-11-02 15:41:02 -0700282 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
283 struct user_perm user = user_perms[i];
284 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700285 return (user.perms & perm) &&
286 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700287 }
288 }
289
Riley Spahneaabae92014-06-30 12:39:52 -0700290 return (DEFAULT_PERMS & perm) &&
291 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700292}
293
Kenny Root49468902013-03-19 13:41:33 -0700294/**
295 * Returns the UID that the callingUid should act as. This is here for
296 * legacy support of the WiFi and VPN systems and should be removed
297 * when WiFi can operate in its own namespace.
298 */
Kenny Root07438c82012-11-02 15:41:02 -0700299static uid_t get_keystore_euid(uid_t uid) {
300 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
301 struct user_euid user = user_euids[i];
302 if (user.uid == uid) {
303 return user.euid;
304 }
305 }
306
307 return uid;
308}
309
Kenny Root49468902013-03-19 13:41:33 -0700310/**
311 * Returns true if the callingUid is allowed to interact in the targetUid's
312 * namespace.
313 */
314static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700315 if (callingUid == targetUid) {
316 return true;
317 }
Kenny Root49468902013-03-19 13:41:33 -0700318 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
319 struct user_euid user = user_euids[i];
320 if (user.euid == callingUid && user.uid == targetUid) {
321 return true;
322 }
323 }
324
325 return false;
326}
327
Kenny Roota91203b2012-02-15 15:00:46 -0800328/* Here is the encoding of keys. This is necessary in order to allow arbitrary
329 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
330 * into two bytes. The first byte is one of [+-.] which represents the first
331 * two bits of the character. The second byte encodes the rest of the bits into
332 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
333 * that Base64 cannot be used here due to the need of prefix match on keys. */
334
Kenny Root655b9582013-04-04 08:37:42 -0700335static size_t encode_key_length(const android::String8& keyName) {
336 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
337 size_t length = keyName.length();
338 for (int i = length; i > 0; --i, ++in) {
339 if (*in < '0' || *in > '~') {
340 ++length;
341 }
342 }
343 return length;
344}
345
Kenny Root07438c82012-11-02 15:41:02 -0700346static int encode_key(char* out, const android::String8& keyName) {
347 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
348 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800349 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700350 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800351 *out = '+' + (*in >> 6);
352 *++out = '0' + (*in & 0x3F);
353 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700354 } else {
355 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800356 }
357 }
358 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800359 return length;
360}
361
Kenny Root07438c82012-11-02 15:41:02 -0700362/*
363 * Converts from the "escaped" format on disk to actual name.
364 * This will be smaller than the input string.
365 *
366 * Characters that should combine with the next at the end will be truncated.
367 */
368static size_t decode_key_length(const char* in, size_t length) {
369 size_t outLength = 0;
370
371 for (const char* end = in + length; in < end; in++) {
372 /* This combines with the next character. */
373 if (*in < '0' || *in > '~') {
374 continue;
375 }
376
377 outLength++;
378 }
379 return outLength;
380}
381
382static void decode_key(char* out, const char* in, size_t length) {
383 for (const char* end = in + length; in < end; in++) {
384 if (*in < '0' || *in > '~') {
385 /* Truncate combining characters at the end. */
386 if (in + 1 >= end) {
387 break;
388 }
389
390 *out = (*in++ - '+') << 6;
391 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800392 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700393 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800394 }
395 }
396 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800397}
398
399static size_t readFully(int fd, uint8_t* data, size_t size) {
400 size_t remaining = size;
401 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800402 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800403 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800404 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800405 }
406 data += n;
407 remaining -= n;
408 }
409 return size;
410}
411
412static size_t writeFully(int fd, uint8_t* data, size_t size) {
413 size_t remaining = size;
414 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800415 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
416 if (n < 0) {
417 ALOGW("write failed: %s", strerror(errno));
418 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800419 }
420 data += n;
421 remaining -= n;
422 }
423 return size;
424}
425
426class Entropy {
427public:
428 Entropy() : mRandom(-1) {}
429 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800430 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800431 close(mRandom);
432 }
433 }
434
435 bool open() {
436 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800437 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
438 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800439 ALOGE("open: %s: %s", randomDevice, strerror(errno));
440 return false;
441 }
442 return true;
443 }
444
Kenny Root51878182012-03-13 12:53:19 -0700445 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800446 return (readFully(mRandom, data, size) == size);
447 }
448
449private:
450 int mRandom;
451};
452
453/* Here is the file format. There are two parts in blob.value, the secret and
454 * the description. The secret is stored in ciphertext, and its original size
455 * can be found in blob.length. The description is stored after the secret in
456 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700457 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700458 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800459 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
460 * and decryptBlob(). Thus they should not be accessed from outside. */
461
Kenny Root822c3a92012-03-23 16:34:39 -0700462/* ** Note to future implementors of encryption: **
463 * Currently this is the construction:
464 * metadata || Enc(MD5(data) || data)
465 *
466 * This should be the construction used for encrypting if re-implementing:
467 *
468 * Derive independent keys for encryption and MAC:
469 * Kenc = AES_encrypt(masterKey, "Encrypt")
470 * Kmac = AES_encrypt(masterKey, "MAC")
471 *
472 * Store this:
473 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
474 * HMAC(Kmac, metadata || Enc(data))
475 */
Kenny Roota91203b2012-02-15 15:00:46 -0800476struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700477 uint8_t version;
478 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700479 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800480 uint8_t info;
481 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700482 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800483 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700484 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800485 int32_t length; // in network byte order when encrypted
486 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
487};
488
Kenny Root822c3a92012-03-23 16:34:39 -0700489typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700490 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700491 TYPE_GENERIC = 1,
492 TYPE_MASTER_KEY = 2,
493 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800494 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700495} BlobType;
496
Kenny Rootf9119d62013-04-03 09:22:15 -0700497static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700498
Kenny Roota91203b2012-02-15 15:00:46 -0800499class Blob {
500public:
Kenny Root07438c82012-11-02 15:41:02 -0700501 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
502 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800503 mBlob.length = valueLength;
504 memcpy(mBlob.value, value, valueLength);
505
506 mBlob.info = infoLength;
507 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700508
Kenny Root07438c82012-11-02 15:41:02 -0700509 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700510 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700511
Kenny Rootee8068b2013-10-07 09:49:15 -0700512 if (type == TYPE_MASTER_KEY) {
513 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
514 } else {
515 mBlob.flags = KEYSTORE_FLAG_NONE;
516 }
Kenny Roota91203b2012-02-15 15:00:46 -0800517 }
518
519 Blob(blob b) {
520 mBlob = b;
521 }
522
523 Blob() {}
524
Kenny Root51878182012-03-13 12:53:19 -0700525 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800526 return mBlob.value;
527 }
528
Kenny Root51878182012-03-13 12:53:19 -0700529 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800530 return mBlob.length;
531 }
532
Kenny Root51878182012-03-13 12:53:19 -0700533 const uint8_t* getInfo() const {
534 return mBlob.value + mBlob.length;
535 }
536
537 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800538 return mBlob.info;
539 }
540
Kenny Root822c3a92012-03-23 16:34:39 -0700541 uint8_t getVersion() const {
542 return mBlob.version;
543 }
544
Kenny Rootf9119d62013-04-03 09:22:15 -0700545 bool isEncrypted() const {
546 if (mBlob.version < 2) {
547 return true;
548 }
549
550 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
551 }
552
553 void setEncrypted(bool encrypted) {
554 if (encrypted) {
555 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
556 } else {
557 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
558 }
559 }
560
Kenny Root17208e02013-09-04 13:56:03 -0700561 bool isFallback() const {
562 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
563 }
564
565 void setFallback(bool fallback) {
566 if (fallback) {
567 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
568 } else {
569 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
570 }
571 }
572
Kenny Root822c3a92012-03-23 16:34:39 -0700573 void setVersion(uint8_t version) {
574 mBlob.version = version;
575 }
576
577 BlobType getType() const {
578 return BlobType(mBlob.type);
579 }
580
581 void setType(BlobType type) {
582 mBlob.type = uint8_t(type);
583 }
584
Kenny Rootf9119d62013-04-03 09:22:15 -0700585 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
586 ALOGV("writing blob %s", filename);
587 if (isEncrypted()) {
588 if (state != STATE_NO_ERROR) {
589 ALOGD("couldn't insert encrypted blob while not unlocked");
590 return LOCKED;
591 }
592
593 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
594 ALOGW("Could not read random data for: %s", filename);
595 return SYSTEM_ERROR;
596 }
Kenny Roota91203b2012-02-15 15:00:46 -0800597 }
598
599 // data includes the value and the value's length
600 size_t dataLength = mBlob.length + sizeof(mBlob.length);
601 // pad data to the AES_BLOCK_SIZE
602 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
603 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
604 // encrypted data includes the digest value
605 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
606 // move info after space for padding
607 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
608 // zero padding area
609 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
610
611 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800612
Kenny Rootf9119d62013-04-03 09:22:15 -0700613 if (isEncrypted()) {
614 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800615
Kenny Rootf9119d62013-04-03 09:22:15 -0700616 uint8_t vector[AES_BLOCK_SIZE];
617 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
618 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
619 aes_key, vector, AES_ENCRYPT);
620 }
621
Kenny Roota91203b2012-02-15 15:00:46 -0800622 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
623 size_t fileLength = encryptedLength + headerLength + mBlob.info;
624
625 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800626 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
627 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
628 if (out < 0) {
629 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800630 return SYSTEM_ERROR;
631 }
632 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
633 if (close(out) != 0) {
634 return SYSTEM_ERROR;
635 }
636 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800637 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800638 unlink(tmpFileName);
639 return SYSTEM_ERROR;
640 }
Kenny Root150ca932012-11-14 14:29:02 -0800641 if (rename(tmpFileName, filename) == -1) {
642 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
643 return SYSTEM_ERROR;
644 }
645 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800646 }
647
Kenny Rootf9119d62013-04-03 09:22:15 -0700648 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
649 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800650 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
651 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800652 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
653 }
654 // fileLength may be less than sizeof(mBlob) since the in
655 // memory version has extra padding to tolerate rounding up to
656 // the AES_BLOCK_SIZE
657 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
658 if (close(in) != 0) {
659 return SYSTEM_ERROR;
660 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700661
662 if (isEncrypted() && (state != STATE_NO_ERROR)) {
663 return LOCKED;
664 }
665
Kenny Roota91203b2012-02-15 15:00:46 -0800666 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
667 if (fileLength < headerLength) {
668 return VALUE_CORRUPTED;
669 }
670
671 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700672 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800673 return VALUE_CORRUPTED;
674 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700675
676 ssize_t digestedLength;
677 if (isEncrypted()) {
678 if (encryptedLength % AES_BLOCK_SIZE != 0) {
679 return VALUE_CORRUPTED;
680 }
681
682 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
683 mBlob.vector, AES_DECRYPT);
684 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
685 uint8_t computedDigest[MD5_DIGEST_LENGTH];
686 MD5(mBlob.digested, digestedLength, computedDigest);
687 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
688 return VALUE_CORRUPTED;
689 }
690 } else {
691 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800692 }
693
694 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
695 mBlob.length = ntohl(mBlob.length);
696 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
697 return VALUE_CORRUPTED;
698 }
699 if (mBlob.info != 0) {
700 // move info from after padding to after data
701 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
702 }
Kenny Root07438c82012-11-02 15:41:02 -0700703 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800704 }
705
706private:
707 struct blob mBlob;
708};
709
Kenny Root655b9582013-04-04 08:37:42 -0700710class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800711public:
Kenny Root655b9582013-04-04 08:37:42 -0700712 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
713 asprintf(&mUserDir, "user_%u", mUserId);
714 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
715 }
716
717 ~UserState() {
718 free(mUserDir);
719 free(mMasterKeyFile);
720 }
721
722 bool initialize() {
723 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
724 ALOGE("Could not create directory '%s'", mUserDir);
725 return false;
726 }
727
728 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800729 setState(STATE_LOCKED);
730 } else {
731 setState(STATE_UNINITIALIZED);
732 }
Kenny Root70e3a862012-02-15 17:20:23 -0800733
Kenny Root655b9582013-04-04 08:37:42 -0700734 return true;
735 }
736
737 uid_t getUserId() const {
738 return mUserId;
739 }
740
741 const char* getUserDirName() const {
742 return mUserDir;
743 }
744
745 const char* getMasterKeyFileName() const {
746 return mMasterKeyFile;
747 }
748
749 void setState(State state) {
750 mState = state;
751 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
752 mRetry = MAX_RETRY;
753 }
Kenny Roota91203b2012-02-15 15:00:46 -0800754 }
755
Kenny Root51878182012-03-13 12:53:19 -0700756 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800757 return mState;
758 }
759
Kenny Root51878182012-03-13 12:53:19 -0700760 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800761 return mRetry;
762 }
763
Kenny Root655b9582013-04-04 08:37:42 -0700764 void zeroizeMasterKeysInMemory() {
765 memset(mMasterKey, 0, sizeof(mMasterKey));
766 memset(mSalt, 0, sizeof(mSalt));
767 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
768 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800769 }
770
Kenny Root655b9582013-04-04 08:37:42 -0700771 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
772 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800773 return SYSTEM_ERROR;
774 }
Kenny Root655b9582013-04-04 08:37:42 -0700775 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800776 if (response != NO_ERROR) {
777 return response;
778 }
779 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700780 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800781 }
782
Robin Lee4e865752014-08-19 17:37:55 +0100783 ResponseCode copyMasterKey(UserState* src) {
784 if (mState != STATE_UNINITIALIZED) {
785 return ::SYSTEM_ERROR;
786 }
787 if (src->getState() != STATE_NO_ERROR) {
788 return ::SYSTEM_ERROR;
789 }
790 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
791 setupMasterKeys();
792 return ::NO_ERROR;
793 }
794
Kenny Root655b9582013-04-04 08:37:42 -0700795 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800796 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
797 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
798 AES_KEY passwordAesKey;
799 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700800 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700801 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800802 }
803
Kenny Root655b9582013-04-04 08:37:42 -0700804 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
805 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800806 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800807 return SYSTEM_ERROR;
808 }
809
810 // we read the raw blob to just to get the salt to generate
811 // the AES key, then we create the Blob to use with decryptBlob
812 blob rawBlob;
813 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
814 if (close(in) != 0) {
815 return SYSTEM_ERROR;
816 }
817 // find salt at EOF if present, otherwise we have an old file
818 uint8_t* salt;
819 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
820 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
821 } else {
822 salt = NULL;
823 }
824 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
825 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
826 AES_KEY passwordAesKey;
827 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
828 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700829 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
830 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800831 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700832 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800833 }
834 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
835 // if salt was missing, generate one and write a new master key file with the salt.
836 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700837 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800838 return SYSTEM_ERROR;
839 }
Kenny Root655b9582013-04-04 08:37:42 -0700840 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800841 }
842 if (response == NO_ERROR) {
843 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
844 setupMasterKeys();
845 }
846 return response;
847 }
848 if (mRetry <= 0) {
849 reset();
850 return UNINITIALIZED;
851 }
852 --mRetry;
853 switch (mRetry) {
854 case 0: return WRONG_PASSWORD_0;
855 case 1: return WRONG_PASSWORD_1;
856 case 2: return WRONG_PASSWORD_2;
857 case 3: return WRONG_PASSWORD_3;
858 default: return WRONG_PASSWORD_3;
859 }
860 }
861
Kenny Root655b9582013-04-04 08:37:42 -0700862 AES_KEY* getEncryptionKey() {
863 return &mMasterKeyEncryption;
864 }
865
866 AES_KEY* getDecryptionKey() {
867 return &mMasterKeyDecryption;
868 }
869
Kenny Roota91203b2012-02-15 15:00:46 -0800870 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700871 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800872 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700873 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800874 return false;
875 }
Kenny Root655b9582013-04-04 08:37:42 -0700876
877 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800878 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700879 // We only care about files.
880 if (file->d_type != DT_REG) {
881 continue;
882 }
883
884 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700885 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700886 continue;
887 }
888
889 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800890 }
891 closedir(dir);
892 return true;
893 }
894
Kenny Root655b9582013-04-04 08:37:42 -0700895private:
896 static const int MASTER_KEY_SIZE_BYTES = 16;
897 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
898
899 static const int MAX_RETRY = 4;
900 static const size_t SALT_SIZE = 16;
901
902 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
903 uint8_t* salt) {
904 size_t saltSize;
905 if (salt != NULL) {
906 saltSize = SALT_SIZE;
907 } else {
908 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
909 salt = (uint8_t*) "keystore";
910 // sizeof = 9, not strlen = 8
911 saltSize = sizeof("keystore");
912 }
913
914 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
915 saltSize, 8192, keySize, key);
916 }
917
918 bool generateSalt(Entropy* entropy) {
919 return entropy->generate_random_data(mSalt, sizeof(mSalt));
920 }
921
922 bool generateMasterKey(Entropy* entropy) {
923 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
924 return false;
925 }
926 if (!generateSalt(entropy)) {
927 return false;
928 }
929 return true;
930 }
931
932 void setupMasterKeys() {
933 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
934 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
935 setState(STATE_NO_ERROR);
936 }
937
938 uid_t mUserId;
939
940 char* mUserDir;
941 char* mMasterKeyFile;
942
943 State mState;
944 int8_t mRetry;
945
946 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
947 uint8_t mSalt[SALT_SIZE];
948
949 AES_KEY mMasterKeyEncryption;
950 AES_KEY mMasterKeyDecryption;
951};
952
953typedef struct {
954 uint32_t uid;
955 const uint8_t* filename;
956} grant_t;
957
958class KeyStore {
959public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800960 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700961 : mEntropy(entropy)
962 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800963 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700964 {
965 memset(&mMetaData, '\0', sizeof(mMetaData));
966 }
967
968 ~KeyStore() {
969 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
970 it != mGrants.end(); it++) {
971 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700972 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800973 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700974
975 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
976 it != mMasterKeys.end(); it++) {
977 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700978 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800979 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700980 }
981
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800982 /**
983 * Depending on the hardware keymaster version is this may return a
984 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
985 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
986 * be guarded by a check on the device's version.
987 */
988 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700989 return mDevice;
990 }
991
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800992 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800993 return mFallbackDevice;
994 }
995
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800996 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800997 return blob.isFallback() ? mFallbackDevice: mDevice;
998 }
999
Kenny Root655b9582013-04-04 08:37:42 -07001000 ResponseCode initialize() {
1001 readMetaData();
1002 if (upgradeKeystore()) {
1003 writeMetaData();
1004 }
1005
1006 return ::NO_ERROR;
1007 }
1008
1009 State getState(uid_t uid) {
1010 return getUserState(uid)->getState();
1011 }
1012
1013 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1014 UserState* userState = getUserState(uid);
1015 return userState->initialize(pw, mEntropy);
1016 }
1017
Robin Lee4e865752014-08-19 17:37:55 +01001018 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1019 UserState *userState = getUserState(uid);
1020 UserState *initState = getUserState(src);
1021 return userState->copyMasterKey(initState);
1022 }
1023
Kenny Root655b9582013-04-04 08:37:42 -07001024 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001025 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001026 return userState->writeMasterKey(pw, mEntropy);
1027 }
1028
1029 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001030 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001031 return userState->readMasterKey(pw, mEntropy);
1032 }
1033
1034 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001035 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001036 encode_key(encoded, keyName);
1037 return android::String8(encoded);
1038 }
1039
1040 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001041 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001042 encode_key(encoded, keyName);
1043 return android::String8::format("%u_%s", uid, encoded);
1044 }
1045
1046 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001047 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001048 encode_key(encoded, keyName);
1049 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1050 encoded);
1051 }
1052
1053 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001054 android::String8 prefix("");
1055 android::Vector<android::String16> aliases;
1056 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1057 return ::SYSTEM_ERROR;
1058 }
1059
Kenny Root655b9582013-04-04 08:37:42 -07001060 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001061 for (uint32_t i = 0; i < aliases.size(); i++) {
1062 android::String8 filename(aliases[i]);
1063 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1064 getKeyName(filename).string());
1065 del(filename, ::TYPE_ANY, uid);
1066 }
1067
Kenny Root655b9582013-04-04 08:37:42 -07001068 userState->zeroizeMasterKeysInMemory();
1069 userState->setState(STATE_UNINITIALIZED);
1070 return userState->reset();
1071 }
1072
1073 bool isEmpty(uid_t uid) const {
1074 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001075 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001076 return true;
1077 }
1078
1079 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001080 if (!dir) {
1081 return true;
1082 }
Kenny Root31e27462014-09-10 11:28:03 -07001083
Kenny Roota91203b2012-02-15 15:00:46 -08001084 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001085 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001086 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001087 // We only care about files.
1088 if (file->d_type != DT_REG) {
1089 continue;
1090 }
1091
1092 // Skip anything that starts with a "."
1093 if (file->d_name[0] == '.') {
1094 continue;
1095 }
1096
Kenny Root31e27462014-09-10 11:28:03 -07001097 result = false;
1098 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001099 }
1100 closedir(dir);
1101 return result;
1102 }
1103
Kenny Root655b9582013-04-04 08:37:42 -07001104 void lock(uid_t uid) {
1105 UserState* userState = getUserState(uid);
1106 userState->zeroizeMasterKeysInMemory();
1107 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001108 }
1109
Kenny Root655b9582013-04-04 08:37:42 -07001110 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1111 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001112 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1113 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001114 if (rc != NO_ERROR) {
1115 return rc;
1116 }
1117
1118 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001119 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001120 /* If we upgrade the key, we need to write it to disk again. Then
1121 * it must be read it again since the blob is encrypted each time
1122 * it's written.
1123 */
Kenny Root655b9582013-04-04 08:37:42 -07001124 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1125 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001126 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1127 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001128 return rc;
1129 }
1130 }
Kenny Root822c3a92012-03-23 16:34:39 -07001131 }
1132
Kenny Root17208e02013-09-04 13:56:03 -07001133 /*
1134 * This will upgrade software-backed keys to hardware-backed keys when
1135 * the HAL for the device supports the newer key types.
1136 */
1137 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1138 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1139 && keyBlob->isFallback()) {
1140 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1141 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1142
1143 // The HAL allowed the import, reget the key to have the "fresh"
1144 // version.
1145 if (imported == NO_ERROR) {
1146 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1147 }
1148 }
1149
Kenny Rootd53bc922013-03-21 14:10:15 -07001150 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001151 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1152 return KEY_NOT_FOUND;
1153 }
1154
1155 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001156 }
1157
Kenny Root655b9582013-04-04 08:37:42 -07001158 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1159 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001160 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1161 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001162 }
1163
Robin Lee4b84fdc2014-09-24 11:56:57 +01001164 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1165 Blob keyBlob;
1166 ResponseCode rc = get(filename, &keyBlob, type, uid);
1167 if (rc != ::NO_ERROR) {
1168 return rc;
1169 }
1170
1171 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1172 // A device doesn't have to implement delete_keypair.
1173 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1174 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1175 rc = ::SYSTEM_ERROR;
1176 }
1177 }
1178 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001179 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1180 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1181 if (dev->delete_key) {
1182 keymaster_key_blob_t blob;
1183 blob.key_material = keyBlob.getValue();
1184 blob.key_material_size = keyBlob.getLength();
1185 dev->delete_key(dev, &blob);
1186 }
1187 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001188 if (rc != ::NO_ERROR) {
1189 return rc;
1190 }
1191
1192 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1193 }
1194
1195 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1196 uid_t uid) {
1197
1198 UserState* userState = getUserState(uid);
1199 size_t n = prefix.length();
1200
1201 DIR* dir = opendir(userState->getUserDirName());
1202 if (!dir) {
1203 ALOGW("can't open directory for user: %s", strerror(errno));
1204 return ::SYSTEM_ERROR;
1205 }
1206
1207 struct dirent* file;
1208 while ((file = readdir(dir)) != NULL) {
1209 // We only care about files.
1210 if (file->d_type != DT_REG) {
1211 continue;
1212 }
1213
1214 // Skip anything that starts with a "."
1215 if (file->d_name[0] == '.') {
1216 continue;
1217 }
1218
1219 if (!strncmp(prefix.string(), file->d_name, n)) {
1220 const char* p = &file->d_name[n];
1221 size_t plen = strlen(p);
1222
1223 size_t extra = decode_key_length(p, plen);
1224 char *match = (char*) malloc(extra + 1);
1225 if (match != NULL) {
1226 decode_key(match, p, plen);
1227 matches->push(android::String16(match, extra));
1228 free(match);
1229 } else {
1230 ALOGW("could not allocate match of size %zd", extra);
1231 }
1232 }
1233 }
1234 closedir(dir);
1235 return ::NO_ERROR;
1236 }
1237
Kenny Root07438c82012-11-02 15:41:02 -07001238 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001239 const grant_t* existing = getGrant(filename, granteeUid);
1240 if (existing == NULL) {
1241 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001242 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001243 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001244 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001245 }
1246 }
1247
Kenny Root07438c82012-11-02 15:41:02 -07001248 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001249 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1250 it != mGrants.end(); it++) {
1251 grant_t* grant = *it;
1252 if (grant->uid == granteeUid
1253 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1254 mGrants.erase(it);
1255 return true;
1256 }
Kenny Root70e3a862012-02-15 17:20:23 -08001257 }
Kenny Root70e3a862012-02-15 17:20:23 -08001258 return false;
1259 }
1260
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001261 bool hasGrant(const char* filename, const uid_t uid) const {
1262 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001263 }
1264
Kenny Rootf9119d62013-04-03 09:22:15 -07001265 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1266 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001267 uint8_t* data;
1268 size_t dataLength;
1269 int rc;
1270
1271 if (mDevice->import_keypair == NULL) {
1272 ALOGE("Keymaster doesn't support import!");
1273 return SYSTEM_ERROR;
1274 }
1275
Kenny Root17208e02013-09-04 13:56:03 -07001276 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001277 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001278 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001279 /*
1280 * Maybe the device doesn't support this type of key. Try to use the
1281 * software fallback keymaster implementation. This is a little bit
1282 * lazier than checking the PKCS#8 key type, but the software
1283 * implementation will do that anyway.
1284 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001285 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001286 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001287
1288 if (rc) {
1289 ALOGE("Error while importing keypair: %d", rc);
1290 return SYSTEM_ERROR;
1291 }
Kenny Root822c3a92012-03-23 16:34:39 -07001292 }
1293
1294 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1295 free(data);
1296
Kenny Rootf9119d62013-04-03 09:22:15 -07001297 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001298 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001299
Kenny Root655b9582013-04-04 08:37:42 -07001300 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001301 }
1302
Kenny Root1b0e3932013-09-05 13:06:32 -07001303 bool isHardwareBacked(const android::String16& keyType) const {
1304 if (mDevice == NULL) {
1305 ALOGW("can't get keymaster device");
1306 return false;
1307 }
1308
1309 if (sRSAKeyType == keyType) {
1310 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1311 } else {
1312 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1313 && (mDevice->common.module->module_api_version
1314 >= KEYMASTER_MODULE_API_VERSION_0_2);
1315 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001316 }
1317
Kenny Root655b9582013-04-04 08:37:42 -07001318 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1319 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001320 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001321
1322 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1323 if (responseCode == NO_ERROR) {
1324 return responseCode;
1325 }
1326
1327 // If this is one of the legacy UID->UID mappings, use it.
1328 uid_t euid = get_keystore_euid(uid);
1329 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001330 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001331 responseCode = get(filepath8.string(), keyBlob, type, uid);
1332 if (responseCode == NO_ERROR) {
1333 return responseCode;
1334 }
1335 }
1336
1337 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001338 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001339 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001340 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001341 if (end[0] != '_' || end[1] == 0) {
1342 return KEY_NOT_FOUND;
1343 }
Kenny Root86b16e82013-09-09 11:15:54 -07001344 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1345 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001346 if (!hasGrant(filepath8.string(), uid)) {
1347 return responseCode;
1348 }
1349
1350 // It is a granted key. Try to load it.
1351 return get(filepath8.string(), keyBlob, type, uid);
1352 }
1353
1354 /**
1355 * Returns any existing UserState or creates it if it doesn't exist.
1356 */
1357 UserState* getUserState(uid_t uid) {
1358 uid_t userId = get_user_id(uid);
1359
1360 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1361 it != mMasterKeys.end(); it++) {
1362 UserState* state = *it;
1363 if (state->getUserId() == userId) {
1364 return state;
1365 }
1366 }
1367
1368 UserState* userState = new UserState(userId);
1369 if (!userState->initialize()) {
1370 /* There's not much we can do if initialization fails. Trying to
1371 * unlock the keystore for that user will fail as well, so any
1372 * subsequent request for this user will just return SYSTEM_ERROR.
1373 */
1374 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1375 }
1376 mMasterKeys.add(userState);
1377 return userState;
1378 }
1379
1380 /**
1381 * Returns NULL if the UserState doesn't already exist.
1382 */
1383 const UserState* getUserState(uid_t uid) const {
1384 uid_t userId = get_user_id(uid);
1385
1386 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1387 it != mMasterKeys.end(); it++) {
1388 UserState* state = *it;
1389 if (state->getUserId() == userId) {
1390 return state;
1391 }
1392 }
1393
1394 return NULL;
1395 }
1396
Kenny Roota91203b2012-02-15 15:00:46 -08001397private:
Kenny Root655b9582013-04-04 08:37:42 -07001398 static const char* sOldMasterKey;
1399 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001400 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001401 Entropy* mEntropy;
1402
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001403 keymaster1_device_t* mDevice;
1404 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001405
Kenny Root655b9582013-04-04 08:37:42 -07001406 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001407
Kenny Root655b9582013-04-04 08:37:42 -07001408 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001409
Kenny Root655b9582013-04-04 08:37:42 -07001410 typedef struct {
1411 uint32_t version;
1412 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001413
Kenny Root655b9582013-04-04 08:37:42 -07001414 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001415
Kenny Root655b9582013-04-04 08:37:42 -07001416 const grant_t* getGrant(const char* filename, uid_t uid) const {
1417 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1418 it != mGrants.end(); it++) {
1419 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001420 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001421 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001422 return grant;
1423 }
1424 }
Kenny Root70e3a862012-02-15 17:20:23 -08001425 return NULL;
1426 }
1427
Kenny Root822c3a92012-03-23 16:34:39 -07001428 /**
1429 * Upgrade code. This will upgrade the key from the current version
1430 * to whatever is newest.
1431 */
Kenny Root655b9582013-04-04 08:37:42 -07001432 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1433 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001434 bool updated = false;
1435 uint8_t version = oldVersion;
1436
1437 /* From V0 -> V1: All old types were unknown */
1438 if (version == 0) {
1439 ALOGV("upgrading to version 1 and setting type %d", type);
1440
1441 blob->setType(type);
1442 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001443 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001444 }
1445 version = 1;
1446 updated = true;
1447 }
1448
Kenny Rootf9119d62013-04-03 09:22:15 -07001449 /* From V1 -> V2: All old keys were encrypted */
1450 if (version == 1) {
1451 ALOGV("upgrading to version 2");
1452
1453 blob->setEncrypted(true);
1454 version = 2;
1455 updated = true;
1456 }
1457
Kenny Root822c3a92012-03-23 16:34:39 -07001458 /*
1459 * If we've updated, set the key blob to the right version
1460 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001461 */
Kenny Root822c3a92012-03-23 16:34:39 -07001462 if (updated) {
1463 ALOGV("updated and writing file %s", filename);
1464 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001465 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001466
1467 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001468 }
1469
1470 /**
1471 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1472 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1473 * Then it overwrites the original blob with the new blob
1474 * format that is returned from the keymaster.
1475 */
Kenny Root655b9582013-04-04 08:37:42 -07001476 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001477 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1478 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1479 if (b.get() == NULL) {
1480 ALOGE("Problem instantiating BIO");
1481 return SYSTEM_ERROR;
1482 }
1483
1484 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1485 if (pkey.get() == NULL) {
1486 ALOGE("Couldn't read old PEM file");
1487 return SYSTEM_ERROR;
1488 }
1489
1490 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1491 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1492 if (len < 0) {
1493 ALOGE("Couldn't measure PKCS#8 length");
1494 return SYSTEM_ERROR;
1495 }
1496
Kenny Root70c98892013-02-07 09:10:36 -08001497 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1498 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001499 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1500 ALOGE("Couldn't convert to PKCS#8");
1501 return SYSTEM_ERROR;
1502 }
1503
Kenny Rootf9119d62013-04-03 09:22:15 -07001504 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1505 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001506 if (rc != NO_ERROR) {
1507 return rc;
1508 }
1509
Kenny Root655b9582013-04-04 08:37:42 -07001510 return get(filename, blob, TYPE_KEY_PAIR, uid);
1511 }
1512
1513 void readMetaData() {
1514 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1515 if (in < 0) {
1516 return;
1517 }
1518 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1519 if (fileLength != sizeof(mMetaData)) {
1520 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1521 sizeof(mMetaData));
1522 }
1523 close(in);
1524 }
1525
1526 void writeMetaData() {
1527 const char* tmpFileName = ".metadata.tmp";
1528 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1529 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1530 if (out < 0) {
1531 ALOGE("couldn't write metadata file: %s", strerror(errno));
1532 return;
1533 }
1534 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1535 if (fileLength != sizeof(mMetaData)) {
1536 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1537 sizeof(mMetaData));
1538 }
1539 close(out);
1540 rename(tmpFileName, sMetaDataFile);
1541 }
1542
1543 bool upgradeKeystore() {
1544 bool upgraded = false;
1545
1546 if (mMetaData.version == 0) {
1547 UserState* userState = getUserState(0);
1548
1549 // Initialize first so the directory is made.
1550 userState->initialize();
1551
1552 // Migrate the old .masterkey file to user 0.
1553 if (access(sOldMasterKey, R_OK) == 0) {
1554 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1555 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1556 return false;
1557 }
1558 }
1559
1560 // Initialize again in case we had a key.
1561 userState->initialize();
1562
1563 // Try to migrate existing keys.
1564 DIR* dir = opendir(".");
1565 if (!dir) {
1566 // Give up now; maybe we can upgrade later.
1567 ALOGE("couldn't open keystore's directory; something is wrong");
1568 return false;
1569 }
1570
1571 struct dirent* file;
1572 while ((file = readdir(dir)) != NULL) {
1573 // We only care about files.
1574 if (file->d_type != DT_REG) {
1575 continue;
1576 }
1577
1578 // Skip anything that starts with a "."
1579 if (file->d_name[0] == '.') {
1580 continue;
1581 }
1582
1583 // Find the current file's user.
1584 char* end;
1585 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1586 if (end[0] != '_' || end[1] == 0) {
1587 continue;
1588 }
1589 UserState* otherUser = getUserState(thisUid);
1590 if (otherUser->getUserId() != 0) {
1591 unlinkat(dirfd(dir), file->d_name, 0);
1592 }
1593
1594 // Rename the file into user directory.
1595 DIR* otherdir = opendir(otherUser->getUserDirName());
1596 if (otherdir == NULL) {
1597 ALOGW("couldn't open user directory for rename");
1598 continue;
1599 }
1600 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1601 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1602 }
1603 closedir(otherdir);
1604 }
1605 closedir(dir);
1606
1607 mMetaData.version = 1;
1608 upgraded = true;
1609 }
1610
1611 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001612 }
Kenny Roota91203b2012-02-15 15:00:46 -08001613};
1614
Kenny Root655b9582013-04-04 08:37:42 -07001615const char* KeyStore::sOldMasterKey = ".masterkey";
1616const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001617
Kenny Root1b0e3932013-09-05 13:06:32 -07001618const android::String16 KeyStore::sRSAKeyType("RSA");
1619
Kenny Root07438c82012-11-02 15:41:02 -07001620namespace android {
1621class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1622public:
1623 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001624 : mKeyStore(keyStore),
1625 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001626 {
Kenny Roota91203b2012-02-15 15:00:46 -08001627 }
Kenny Roota91203b2012-02-15 15:00:46 -08001628
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001629 void binderDied(const wp<IBinder>& who) {
1630 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1631 for (auto token: operations) {
1632 abort(token);
1633 }
Kenny Root822c3a92012-03-23 16:34:39 -07001634 }
Kenny Roota91203b2012-02-15 15:00:46 -08001635
Kenny Root07438c82012-11-02 15:41:02 -07001636 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001637 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001638 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001639 }
Kenny Roota91203b2012-02-15 15:00:46 -08001640
Chad Brubaker9489b792015-04-14 11:01:45 -07001641 return mKeyStore->getState(IPCThreadState::self()->getCallingUid());
Kenny Root298e7b12012-03-26 13:54:44 -07001642 }
1643
Kenny Root07438c82012-11-02 15:41:02 -07001644 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001645 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001646 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001647 }
Kenny Root07438c82012-11-02 15:41:02 -07001648
Chad Brubaker9489b792015-04-14 11:01:45 -07001649 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001650 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001651 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001652
Kenny Root655b9582013-04-04 08:37:42 -07001653 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001654 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001655 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001656 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001657 *item = NULL;
1658 *itemLength = 0;
1659 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001660 }
Kenny Roota91203b2012-02-15 15:00:46 -08001661
Kenny Root07438c82012-11-02 15:41:02 -07001662 *item = (uint8_t*) malloc(keyBlob.getLength());
1663 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1664 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001665
Kenny Root07438c82012-11-02 15:41:02 -07001666 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001667 }
1668
Kenny Rootf9119d62013-04-03 09:22:15 -07001669 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1670 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001671 targetUid = getEffectiveUid(targetUid);
1672 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1673 flags & KEYSTORE_FLAG_ENCRYPTED);
1674 if (result != ::NO_ERROR) {
1675 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001676 }
1677
Kenny Root07438c82012-11-02 15:41:02 -07001678 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001679 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001680
1681 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001682 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1683
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001684 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001685 }
1686
Kenny Root49468902013-03-19 13:41:33 -07001687 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001688 targetUid = getEffectiveUid(targetUid);
1689 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001690 return ::PERMISSION_DENIED;
1691 }
Kenny Root07438c82012-11-02 15:41:02 -07001692 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001693 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001694 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001695 }
1696
Kenny Root49468902013-03-19 13:41:33 -07001697 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001698 targetUid = getEffectiveUid(targetUid);
1699 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001700 return ::PERMISSION_DENIED;
1701 }
1702
Kenny Root07438c82012-11-02 15:41:02 -07001703 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001704 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001705
Kenny Root655b9582013-04-04 08:37:42 -07001706 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001707 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1708 }
1709 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001710 }
1711
Kenny Root49468902013-03-19 13:41:33 -07001712 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001713 targetUid = getEffectiveUid(targetUid);
1714 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001715 return ::PERMISSION_DENIED;
1716 }
Kenny Root07438c82012-11-02 15:41:02 -07001717 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001718 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001719
Robin Lee4b84fdc2014-09-24 11:56:57 +01001720 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1721 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001722 }
Kenny Root07438c82012-11-02 15:41:02 -07001723 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001724 }
1725
Kenny Root07438c82012-11-02 15:41:02 -07001726 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001727 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001728 return ::PERMISSION_DENIED;
1729 }
1730
Chad Brubaker9489b792015-04-14 11:01:45 -07001731 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01001732 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001733 }
1734
Kenny Root07438c82012-11-02 15:41:02 -07001735 /*
1736 * Here is the history. To improve the security, the parameters to generate the
1737 * master key has been changed. To make a seamless transition, we update the
1738 * file using the same password when the user unlock it for the first time. If
1739 * any thing goes wrong during the transition, the new file will not overwrite
1740 * the old one. This avoids permanent damages of the existing data.
1741 */
1742 int32_t password(const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001743 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001744 return ::PERMISSION_DENIED;
1745 }
Kenny Root70e3a862012-02-15 17:20:23 -08001746
Kenny Root07438c82012-11-02 15:41:02 -07001747 const String8 password8(password);
Chad Brubaker9489b792015-04-14 11:01:45 -07001748 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root70e3a862012-02-15 17:20:23 -08001749
Kenny Root655b9582013-04-04 08:37:42 -07001750 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001751 case ::STATE_UNINITIALIZED: {
1752 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001753 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001754 }
1755 case ::STATE_NO_ERROR: {
1756 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001757 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001758 }
1759 case ::STATE_LOCKED: {
1760 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001761 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001762 }
1763 }
1764 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001765 }
1766
Kenny Root07438c82012-11-02 15:41:02 -07001767 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001768 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001769 return ::PERMISSION_DENIED;
1770 }
Kenny Root70e3a862012-02-15 17:20:23 -08001771
Chad Brubaker9489b792015-04-14 11:01:45 -07001772 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001773 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001774 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001775 ALOGD("calling lock in state: %d", state);
1776 return state;
1777 }
1778
Kenny Root655b9582013-04-04 08:37:42 -07001779 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001780 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001781 }
1782
Kenny Root07438c82012-11-02 15:41:02 -07001783 int32_t unlock(const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001784 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001785 return ::PERMISSION_DENIED;
1786 }
1787
Chad Brubaker9489b792015-04-14 11:01:45 -07001788 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001789 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001790 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001791 ALOGD("calling unlock when not locked");
1792 return state;
1793 }
1794
1795 const String8 password8(pw);
1796 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001797 }
1798
Kenny Root07438c82012-11-02 15:41:02 -07001799 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001800 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001801 return -1;
1802 }
Kenny Root70e3a862012-02-15 17:20:23 -08001803
Chad Brubaker9489b792015-04-14 11:01:45 -07001804 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001805 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001806 }
1807
Kenny Root96427ba2013-08-16 14:02:41 -07001808 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1809 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001810 targetUid = getEffectiveUid(targetUid);
1811 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1812 flags & KEYSTORE_FLAG_ENCRYPTED);
1813 if (result != ::NO_ERROR) {
1814 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001815 }
Kenny Root07438c82012-11-02 15:41:02 -07001816 uint8_t* data;
1817 size_t dataLength;
1818 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001819 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001820
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001821 const keymaster1_device_t* device = mKeyStore->getDevice();
1822 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001823 if (device == NULL) {
1824 return ::SYSTEM_ERROR;
1825 }
1826
1827 if (device->generate_keypair == NULL) {
1828 return ::SYSTEM_ERROR;
1829 }
1830
Kenny Root17208e02013-09-04 13:56:03 -07001831 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001832 keymaster_dsa_keygen_params_t dsa_params;
1833 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001834
Kenny Root96427ba2013-08-16 14:02:41 -07001835 if (keySize == -1) {
1836 keySize = DSA_DEFAULT_KEY_SIZE;
1837 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1838 || keySize > DSA_MAX_KEY_SIZE) {
1839 ALOGI("invalid key size %d", keySize);
1840 return ::SYSTEM_ERROR;
1841 }
1842 dsa_params.key_size = keySize;
1843
1844 if (args->size() == 3) {
1845 sp<KeystoreArg> gArg = args->itemAt(0);
1846 sp<KeystoreArg> pArg = args->itemAt(1);
1847 sp<KeystoreArg> qArg = args->itemAt(2);
1848
1849 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1850 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1851 dsa_params.generator_len = gArg->size();
1852
1853 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1854 dsa_params.prime_p_len = pArg->size();
1855
1856 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1857 dsa_params.prime_q_len = qArg->size();
1858 } else {
1859 ALOGI("not all DSA parameters were read");
1860 return ::SYSTEM_ERROR;
1861 }
1862 } else if (args->size() != 0) {
1863 ALOGI("DSA args must be 3");
1864 return ::SYSTEM_ERROR;
1865 }
1866
Kenny Root1d448c02013-11-21 10:36:53 -08001867 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001868 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1869 } else {
1870 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001871 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1872 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001873 }
1874 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001875 keymaster_ec_keygen_params_t ec_params;
1876 memset(&ec_params, '\0', sizeof(ec_params));
1877
1878 if (keySize == -1) {
1879 keySize = EC_DEFAULT_KEY_SIZE;
1880 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1881 ALOGI("invalid key size %d", keySize);
1882 return ::SYSTEM_ERROR;
1883 }
1884 ec_params.field_size = keySize;
1885
Kenny Root1d448c02013-11-21 10:36:53 -08001886 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001887 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1888 } else {
1889 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001890 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001891 }
Kenny Root96427ba2013-08-16 14:02:41 -07001892 } else if (keyType == EVP_PKEY_RSA) {
1893 keymaster_rsa_keygen_params_t rsa_params;
1894 memset(&rsa_params, '\0', sizeof(rsa_params));
1895 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1896
1897 if (keySize == -1) {
1898 keySize = RSA_DEFAULT_KEY_SIZE;
1899 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1900 ALOGI("invalid key size %d", keySize);
1901 return ::SYSTEM_ERROR;
1902 }
1903 rsa_params.modulus_size = keySize;
1904
1905 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001906 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001907 return ::SYSTEM_ERROR;
1908 } else if (args->size() == 1) {
1909 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1910 if (pubExpBlob != NULL) {
1911 Unique_BIGNUM pubExpBn(
1912 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1913 pubExpBlob->size(), NULL));
1914 if (pubExpBn.get() == NULL) {
1915 ALOGI("Could not convert public exponent to BN");
1916 return ::SYSTEM_ERROR;
1917 }
1918 unsigned long pubExp = BN_get_word(pubExpBn.get());
1919 if (pubExp == 0xFFFFFFFFL) {
1920 ALOGI("cannot represent public exponent as a long value");
1921 return ::SYSTEM_ERROR;
1922 }
1923 rsa_params.public_exponent = pubExp;
1924 }
1925 }
1926
1927 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1928 } else {
1929 ALOGW("Unsupported key type %d", keyType);
1930 rc = -1;
1931 }
1932
Kenny Root07438c82012-11-02 15:41:02 -07001933 if (rc) {
1934 return ::SYSTEM_ERROR;
1935 }
1936
Kenny Root655b9582013-04-04 08:37:42 -07001937 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07001938 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001939
1940 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1941 free(data);
1942
Kenny Rootee8068b2013-10-07 09:49:15 -07001943 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001944 keyBlob.setFallback(isFallback);
1945
Chad Brubaker9489b792015-04-14 11:01:45 -07001946 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001947 }
1948
Kenny Rootf9119d62013-04-03 09:22:15 -07001949 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1950 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001951 targetUid = getEffectiveUid(targetUid);
1952 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1953 flags & KEYSTORE_FLAG_ENCRYPTED);
1954 if (result != ::NO_ERROR) {
1955 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001956 }
Kenny Root07438c82012-11-02 15:41:02 -07001957 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001958 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001959
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001960 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001961 }
1962
Kenny Root07438c82012-11-02 15:41:02 -07001963 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1964 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001965 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07001966 return ::PERMISSION_DENIED;
1967 }
Kenny Root07438c82012-11-02 15:41:02 -07001968
Chad Brubaker9489b792015-04-14 11:01:45 -07001969 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001970 Blob keyBlob;
1971 String8 name8(name);
1972
Kenny Rootd38a0b02013-02-13 12:59:14 -08001973 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001974
Kenny Root655b9582013-04-04 08:37:42 -07001975 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001976 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001977 if (responseCode != ::NO_ERROR) {
1978 return responseCode;
1979 }
1980
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001981 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07001982 if (device == NULL) {
1983 ALOGE("no keymaster device; cannot sign");
1984 return ::SYSTEM_ERROR;
1985 }
1986
1987 if (device->sign_data == NULL) {
1988 ALOGE("device doesn't implement signing");
1989 return ::SYSTEM_ERROR;
1990 }
1991
1992 keymaster_rsa_sign_params_t params;
1993 params.digest_type = DIGEST_NONE;
1994 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07001995 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001996 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07001997 if (rc) {
1998 ALOGW("device couldn't sign data");
1999 return ::SYSTEM_ERROR;
2000 }
2001
2002 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002003 }
2004
Kenny Root07438c82012-11-02 15:41:02 -07002005 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2006 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002007 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002008 return ::PERMISSION_DENIED;
2009 }
Kenny Root70e3a862012-02-15 17:20:23 -08002010
Chad Brubaker9489b792015-04-14 11:01:45 -07002011 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002012 Blob keyBlob;
2013 String8 name8(name);
2014 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002015
Kenny Root655b9582013-04-04 08:37:42 -07002016 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002017 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002018 if (responseCode != ::NO_ERROR) {
2019 return responseCode;
2020 }
Kenny Root70e3a862012-02-15 17:20:23 -08002021
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002022 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002023 if (device == NULL) {
2024 return ::SYSTEM_ERROR;
2025 }
Kenny Root70e3a862012-02-15 17:20:23 -08002026
Kenny Root07438c82012-11-02 15:41:02 -07002027 if (device->verify_data == NULL) {
2028 return ::SYSTEM_ERROR;
2029 }
Kenny Root70e3a862012-02-15 17:20:23 -08002030
Kenny Root07438c82012-11-02 15:41:02 -07002031 keymaster_rsa_sign_params_t params;
2032 params.digest_type = DIGEST_NONE;
2033 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002034
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002035 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2036 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002037 if (rc) {
2038 return ::SYSTEM_ERROR;
2039 } else {
2040 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002041 }
2042 }
Kenny Root07438c82012-11-02 15:41:02 -07002043
2044 /*
2045 * TODO: The abstraction between things stored in hardware and regular blobs
2046 * of data stored on the filesystem should be moved down to keystore itself.
2047 * Unfortunately the Java code that calls this has naming conventions that it
2048 * knows about. Ideally keystore shouldn't be used to store random blobs of
2049 * data.
2050 *
2051 * Until that happens, it's necessary to have a separate "get_pubkey" and
2052 * "del_key" since the Java code doesn't really communicate what it's
2053 * intentions are.
2054 */
2055 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002056 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002057 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002058 ALOGW("permission denied for %d: get_pubkey", 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("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002066
Kenny Root655b9582013-04-04 08:37:42 -07002067 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002068 TYPE_KEY_PAIR);
2069 if (responseCode != ::NO_ERROR) {
2070 return responseCode;
2071 }
2072
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002073 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002074 if (device == NULL) {
2075 return ::SYSTEM_ERROR;
2076 }
2077
2078 if (device->get_keypair_public == NULL) {
2079 ALOGE("device has no get_keypair_public implementation!");
2080 return ::SYSTEM_ERROR;
2081 }
2082
Kenny Root17208e02013-09-04 13:56:03 -07002083 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002084 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2085 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002086 if (rc) {
2087 return ::SYSTEM_ERROR;
2088 }
2089
2090 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002091 }
Kenny Root07438c82012-11-02 15:41:02 -07002092
Kenny Root49468902013-03-19 13:41:33 -07002093 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002094 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002095 }
2096
2097 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002098 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002099 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2100 if (result != ::NO_ERROR) {
2101 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002102 }
2103
2104 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002105 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002106
Kenny Root655b9582013-04-04 08:37:42 -07002107 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002108 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2109 }
2110
Kenny Root655b9582013-04-04 08:37:42 -07002111 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002112 return ::NO_ERROR;
2113 }
2114
2115 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002116 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002117 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2118 if (result != ::NO_ERROR) {
2119 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002120 }
2121
2122 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002123 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002124
Kenny Root655b9582013-04-04 08:37:42 -07002125 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002126 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2127 }
2128
Kenny Root655b9582013-04-04 08:37:42 -07002129 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002130 }
2131
2132 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002133 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002134 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002135 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002136 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002137 }
Kenny Root07438c82012-11-02 15:41:02 -07002138
2139 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002140 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002141
Kenny Root655b9582013-04-04 08:37:42 -07002142 if (access(filename.string(), R_OK) == -1) {
2143 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002144 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002145 }
2146
Kenny Root655b9582013-04-04 08:37:42 -07002147 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002148 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002149 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002150 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002151 }
2152
2153 struct stat s;
2154 int ret = fstat(fd, &s);
2155 close(fd);
2156 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002157 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002158 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002159 }
2160
Kenny Root36a9e232013-02-04 14:24:15 -08002161 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002162 }
2163
Kenny Rootd53bc922013-03-21 14:10:15 -07002164 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2165 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002166 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002167 pid_t spid = IPCThreadState::self()->getCallingPid();
2168 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002169 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002170 return -1L;
2171 }
2172
Kenny Root655b9582013-04-04 08:37:42 -07002173 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002174 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002175 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002176 return state;
2177 }
2178
Kenny Rootd53bc922013-03-21 14:10:15 -07002179 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2180 srcUid = callingUid;
2181 } else if (!is_granted_to(callingUid, srcUid)) {
2182 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002183 return ::PERMISSION_DENIED;
2184 }
2185
Kenny Rootd53bc922013-03-21 14:10:15 -07002186 if (destUid == -1) {
2187 destUid = callingUid;
2188 }
2189
2190 if (srcUid != destUid) {
2191 if (static_cast<uid_t>(srcUid) != callingUid) {
2192 ALOGD("can only duplicate from caller to other or to same uid: "
2193 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2194 return ::PERMISSION_DENIED;
2195 }
2196
2197 if (!is_granted_to(callingUid, destUid)) {
2198 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2199 return ::PERMISSION_DENIED;
2200 }
2201 }
2202
2203 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002204 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002205
Kenny Rootd53bc922013-03-21 14:10:15 -07002206 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002207 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002208
Kenny Root655b9582013-04-04 08:37:42 -07002209 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2210 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002211 return ::SYSTEM_ERROR;
2212 }
2213
Kenny Rootd53bc922013-03-21 14:10:15 -07002214 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002215 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002216 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002217 if (responseCode != ::NO_ERROR) {
2218 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002219 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002220
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002221 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002222 }
2223
Kenny Root1b0e3932013-09-05 13:06:32 -07002224 int32_t is_hardware_backed(const String16& keyType) {
2225 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002226 }
2227
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002228 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002229 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubaker01771ae2015-05-01 10:21:27 -07002230 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002231 return ::PERMISSION_DENIED;
2232 }
2233
Robin Lee4b84fdc2014-09-24 11:56:57 +01002234 String8 prefix = String8::format("%u_", targetUid);
2235 Vector<String16> aliases;
2236 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002237 return ::SYSTEM_ERROR;
2238 }
2239
Robin Lee4b84fdc2014-09-24 11:56:57 +01002240 for (uint32_t i = 0; i < aliases.size(); i++) {
2241 String8 name8(aliases[i]);
2242 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2243 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002244 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002245 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002246 }
2247
Robin Lee4b84fdc2014-09-24 11:56:57 +01002248 int32_t reset_uid(int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002249 targetUid = getEffectiveUid(targetUid);
Chad Brubaker01771ae2015-05-01 10:21:27 -07002250 if (!checkBinderPermissionSelfOrSystem(P_RESET_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002251 return ::PERMISSION_DENIED;
2252 }
Chad Brubakerbbc76482015-04-16 15:16:44 -07002253 // Flush the auth token table to prevent stale tokens from sticking
2254 // around.
2255 mAuthTokenTable.Clear();
Robin Lee4e865752014-08-19 17:37:55 +01002256
Robin Lee4b84fdc2014-09-24 11:56:57 +01002257 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002258 }
2259
2260 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002261 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002262 return ::PERMISSION_DENIED;
2263 }
Chad Brubaker9489b792015-04-14 11:01:45 -07002264
Robin Lee4e865752014-08-19 17:37:55 +01002265 if (sourceUid == targetUid) {
2266 return ::SYSTEM_ERROR;
2267 }
2268
2269 // Initialise user keystore with existing master key held in-memory
2270 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2271 }
2272
2273 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002274 targetUid = getEffectiveUid(targetUid);
2275 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002276 return ::PERMISSION_DENIED;
2277 }
Robin Lee4e865752014-08-19 17:37:55 +01002278 const String8 password8(pw);
2279
2280 switch (mKeyStore->getState(targetUid)) {
2281 case ::STATE_UNINITIALIZED: {
2282 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2283 return mKeyStore->initializeUser(password8, targetUid);
2284 }
2285 case ::STATE_NO_ERROR: {
2286 // rewrite master key with new password.
2287 return mKeyStore->writeMasterKey(password8, targetUid);
2288 }
2289 case ::STATE_LOCKED: {
2290 // read master key, decrypt with password, initialize mMasterKey*.
2291 return mKeyStore->readMasterKey(password8, targetUid);
2292 }
2293 }
2294 return ::SYSTEM_ERROR;
2295 }
2296
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002297 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2298 const keymaster1_device_t* device = mKeyStore->getDevice();
2299 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2300 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2301 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2302 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2303 device->add_rng_entropy != NULL) {
2304 devResult = device->add_rng_entropy(device, data, dataLength);
2305 }
2306 if (fallback->add_rng_entropy) {
2307 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2308 }
2309 if (devResult) {
2310 return devResult;
2311 }
2312 if (fallbackResult) {
2313 return fallbackResult;
2314 }
2315 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002316 }
2317
Chad Brubaker17d68b92015-02-05 22:04:16 -08002318 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002319 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2320 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002321 uid = getEffectiveUid(uid);
2322 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2323 flags & KEYSTORE_FLAG_ENCRYPTED);
2324 if (rc != ::NO_ERROR) {
2325 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002326 }
2327
Chad Brubaker9489b792015-04-14 11:01:45 -07002328 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002329 bool isFallback = false;
2330 keymaster_key_blob_t blob;
2331 keymaster_key_characteristics_t *out = NULL;
2332
2333 const keymaster1_device_t* device = mKeyStore->getDevice();
2334 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2335 if (device == NULL) {
2336 return ::SYSTEM_ERROR;
2337 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002338 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002339 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2340 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002341 if (!entropy) {
2342 rc = KM_ERROR_OK;
2343 } else if (device->add_rng_entropy) {
2344 rc = device->add_rng_entropy(device, entropy, entropyLength);
2345 } else {
2346 rc = KM_ERROR_UNIMPLEMENTED;
2347 }
2348 if (rc == KM_ERROR_OK) {
2349 rc = device->generate_key(device, params.params.data(), params.params.size(),
2350 &blob, &out);
2351 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002352 }
2353 // If the HW device didn't support generate_key or generate_key failed
2354 // fall back to the software implementation.
2355 if (rc && fallback->generate_key != NULL) {
2356 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002357 if (!entropy) {
2358 rc = KM_ERROR_OK;
2359 } else if (fallback->add_rng_entropy) {
2360 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2361 } else {
2362 rc = KM_ERROR_UNIMPLEMENTED;
2363 }
2364 if (rc == KM_ERROR_OK) {
2365 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2366 &blob,
2367 &out);
2368 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002369 }
2370
2371 if (out) {
2372 if (outCharacteristics) {
2373 outCharacteristics->characteristics = *out;
2374 } else {
2375 keymaster_free_characteristics(out);
2376 }
2377 free(out);
2378 }
2379
2380 if (rc) {
2381 return rc;
2382 }
2383
2384 String8 name8(name);
2385 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2386
2387 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2388 keyBlob.setFallback(isFallback);
2389 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2390
2391 free(const_cast<uint8_t*>(blob.key_material));
2392
2393 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002394 }
2395
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002396 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002397 const keymaster_blob_t* clientId,
2398 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002399 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002400 if (!outCharacteristics) {
2401 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2402 }
2403
2404 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2405
2406 Blob keyBlob;
2407 String8 name8(name);
2408 int rc;
2409
2410 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2411 TYPE_KEYMASTER_10);
2412 if (responseCode != ::NO_ERROR) {
2413 return responseCode;
2414 }
2415 keymaster_key_blob_t key;
2416 key.key_material_size = keyBlob.getLength();
2417 key.key_material = keyBlob.getValue();
2418 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2419 keymaster_key_characteristics_t *out = NULL;
2420 if (!dev->get_key_characteristics) {
2421 ALOGW("device does not implement get_key_characteristics");
2422 return KM_ERROR_UNIMPLEMENTED;
2423 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002424 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002425 if (out) {
2426 outCharacteristics->characteristics = *out;
2427 free(out);
2428 }
2429 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002430 }
2431
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002432 int32_t importKey(const String16& name, const KeymasterArguments& params,
2433 keymaster_key_format_t format, const uint8_t *keyData,
2434 size_t keyLength, int uid, int flags,
2435 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002436 uid = getEffectiveUid(uid);
2437 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2438 flags & KEYSTORE_FLAG_ENCRYPTED);
2439 if (rc != ::NO_ERROR) {
2440 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002441 }
2442
Chad Brubaker9489b792015-04-14 11:01:45 -07002443 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002444 bool isFallback = false;
2445 keymaster_key_blob_t blob;
2446 keymaster_key_characteristics_t *out = NULL;
2447
2448 const keymaster1_device_t* device = mKeyStore->getDevice();
2449 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2450 if (device == NULL) {
2451 return ::SYSTEM_ERROR;
2452 }
2453 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2454 device->import_key != NULL) {
2455 rc = device->import_key(device, params.params.data(), params.params.size(),
2456 format, keyData, keyLength, &blob, &out);
2457 }
2458 if (rc && fallback->import_key != NULL) {
2459 isFallback = true;
2460 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2461 format, keyData, keyLength, &blob, &out);
2462 }
2463 if (out) {
2464 if (outCharacteristics) {
2465 outCharacteristics->characteristics = *out;
2466 } else {
2467 keymaster_free_characteristics(out);
2468 }
2469 free(out);
2470 }
2471 if (rc) {
2472 return rc;
2473 }
2474
2475 String8 name8(name);
2476 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2477
2478 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2479 keyBlob.setFallback(isFallback);
2480 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2481
2482 free((void*) blob.key_material);
2483
2484 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002485 }
2486
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002487 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002488 const keymaster_blob_t* clientId,
2489 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002490
2491 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2492
2493 Blob keyBlob;
2494 String8 name8(name);
2495 int rc;
2496
2497 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2498 TYPE_KEYMASTER_10);
2499 if (responseCode != ::NO_ERROR) {
2500 result->resultCode = responseCode;
2501 return;
2502 }
2503 keymaster_key_blob_t key;
2504 key.key_material_size = keyBlob.getLength();
2505 key.key_material = keyBlob.getValue();
2506 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2507 if (!dev->export_key) {
2508 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2509 return;
2510 }
2511 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002512 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002513 &ptr, &result->dataLength);
2514 result->exportData.reset(ptr);
2515 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002516 }
2517
Chad Brubakerad6514a2015-04-09 14:00:26 -07002518
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002519 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002520 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2521 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002522 if (!result || !outParams) {
2523 ALOGE("Unexpected null arguments to begin()");
2524 return;
2525 }
2526 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2527 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2528 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2529 result->resultCode = ::PERMISSION_DENIED;
2530 return;
2531 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002532 if (!checkAllowedOperationParams(params.params)) {
2533 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2534 return;
2535 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002536 Blob keyBlob;
2537 String8 name8(name);
2538 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2539 TYPE_KEYMASTER_10);
2540 if (responseCode != ::NO_ERROR) {
2541 result->resultCode = responseCode;
2542 return;
2543 }
2544 keymaster_key_blob_t key;
2545 key.key_material_size = keyBlob.getLength();
2546 key.key_material = keyBlob.getValue();
2547 keymaster_key_param_t* out;
2548 size_t outSize;
2549 keymaster_operation_handle_t handle;
2550 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002551 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002552 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002553 Unique_keymaster_key_characteristics characteristics;
2554 characteristics.reset(new keymaster_key_characteristics_t);
2555 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2556 if (err) {
2557 result->resultCode = err;
2558 return;
2559 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002560 const hw_auth_token_t* authToken = NULL;
2561 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002562 /*failOnTokenMissing*/ false);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002563 // If per-operation auth is needed we need to begin the operation and
2564 // the client will need to authorize that operation before calling
2565 // update. Any other auth issues stop here.
2566 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2567 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002568 return;
2569 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002570 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002571 // Add entropy to the device first.
2572 if (entropy) {
2573 if (dev->add_rng_entropy) {
2574 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2575 } else {
2576 err = KM_ERROR_UNIMPLEMENTED;
2577 }
2578 if (err) {
2579 result->resultCode = err;
2580 return;
2581 }
2582 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002583 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2584 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002585
2586 // If there are too many operations abort the oldest operation that was
2587 // started as pruneable and try again.
2588 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2589 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2590 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2591 if (abort(oldest) != ::NO_ERROR) {
2592 break;
2593 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002594 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002595 &handle);
2596 }
2597 if (err) {
2598 result->resultCode = err;
2599 return;
2600 }
2601 if (out) {
2602 outParams->params.assign(out, out + outSize);
2603 free(out);
2604 }
2605
Chad Brubakerad6514a2015-04-09 14:00:26 -07002606 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2607 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002608 pruneable);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002609 if (authToken) {
2610 mOperationMap.setOperationAuthToken(operationToken, authToken);
2611 }
2612 // Return the authentication lookup result. If this is a per operation
2613 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2614 // application should get an auth token using the handle before the
2615 // first call to update, which will fail if keystore hasn't received the
2616 // auth token.
2617 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002618 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002619 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002620 }
2621
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002622 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2623 size_t dataLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002624 if (!checkAllowedOperationParams(params.params)) {
2625 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2626 return;
2627 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002628 const keymaster1_device_t* dev;
2629 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002630 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002631 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2632 return;
2633 }
2634 uint8_t* output_buf = NULL;
2635 size_t output_length = 0;
2636 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002637 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002638 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2639 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002640 result->resultCode = authResult;
2641 return;
2642 }
2643 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2644 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002645 result->data.reset(output_buf);
2646 result->dataLength = output_length;
2647 result->inputConsumed = consumed;
2648 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002649 }
2650
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002651 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2652 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002653 if (!checkAllowedOperationParams(params.params)) {
2654 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2655 return;
2656 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002657 const keymaster1_device_t* dev;
2658 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002659 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002660 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2661 return;
2662 }
2663 uint8_t* output_buf = NULL;
2664 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002665 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002666 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2667 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002668 result->resultCode = authResult;
2669 return;
2670 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002671
Chad Brubaker06801e02015-03-31 15:13:13 -07002672 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2673 signature, signatureLength, &output_buf,
2674 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002675 // Remove the operation regardless of the result
2676 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002677 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002678 result->data.reset(output_buf);
2679 result->dataLength = output_length;
2680 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002681 }
2682
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002683 int32_t abort(const sp<IBinder>& token) {
2684 const keymaster1_device_t* dev;
2685 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002686 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002687 return KM_ERROR_INVALID_OPERATION_HANDLE;
2688 }
2689 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002690 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002691 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002692 rc = KM_ERROR_UNIMPLEMENTED;
2693 } else {
2694 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002695 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002696 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002697 if (rc) {
2698 return rc;
2699 }
2700 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002701 }
2702
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002703 bool isOperationAuthorized(const sp<IBinder>& token) {
2704 const keymaster1_device_t* dev;
2705 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002706 const keymaster_key_characteristics_t* characteristics;
2707 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002708 return false;
2709 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002710 const hw_auth_token_t* authToken = NULL;
2711 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002712 std::vector<keymaster_key_param_t> ignored;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002713 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2714 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002715 }
2716
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002717 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002718 if (!checkBinderPermission(P_ADD_AUTH)) {
2719 ALOGW("addAuthToken: permission denied for %d",
2720 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002721 return ::PERMISSION_DENIED;
2722 }
2723 if (length != sizeof(hw_auth_token_t)) {
2724 return KM_ERROR_INVALID_ARGUMENT;
2725 }
2726 hw_auth_token_t* authToken = new hw_auth_token_t;
2727 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2728 // The table takes ownership of authToken.
2729 mAuthTokenTable.AddAuthenticationToken(authToken);
2730 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002731 }
2732
Kenny Root07438c82012-11-02 15:41:02 -07002733private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002734 static const int32_t UID_SELF = -1;
2735
2736 /**
2737 * Get the effective target uid for a binder operation that takes an
2738 * optional uid as the target.
2739 */
2740 inline uid_t getEffectiveUid(int32_t targetUid) {
2741 if (targetUid == UID_SELF) {
2742 return IPCThreadState::self()->getCallingUid();
2743 }
2744 return static_cast<uid_t>(targetUid);
2745 }
2746
2747 /**
2748 * Check if the caller of the current binder method has the required
2749 * permission and if acting on other uids the grants to do so.
2750 */
2751 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2752 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2753 pid_t spid = IPCThreadState::self()->getCallingPid();
2754 if (!has_permission(callingUid, permission, spid)) {
2755 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2756 return false;
2757 }
2758 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2759 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2760 return false;
2761 }
2762 return true;
2763 }
2764
2765 /**
2766 * Check if the caller of the current binder method has the required
Chad Brubaker01771ae2015-05-01 10:21:27 -07002767 * permission and the target uid is the caller or the caller is system.
2768 */
2769 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2770 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2771 pid_t spid = IPCThreadState::self()->getCallingPid();
2772 if (!has_permission(callingUid, permission, spid)) {
2773 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2774 return false;
2775 }
2776 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2777 }
2778
2779 /**
2780 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002781 * permission or the target of the operation is the caller's uid. This is
2782 * for operation where the permission is only for cross-uid activity and all
2783 * uids are allowed to act on their own (ie: clearing all entries for a
2784 * given uid).
2785 */
2786 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2787 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2788 if (getEffectiveUid(targetUid) == callingUid) {
2789 return true;
2790 } else {
2791 return checkBinderPermission(permission, targetUid);
2792 }
2793 }
2794
2795 /**
2796 * Helper method to check that the caller has the required permission as
2797 * well as the keystore is in the unlocked state if checkUnlocked is true.
2798 *
2799 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2800 * otherwise the state of keystore when not unlocked and checkUnlocked is
2801 * true.
2802 */
2803 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2804 bool checkUnlocked = true) {
2805 if (!checkBinderPermission(permission, targetUid)) {
2806 return ::PERMISSION_DENIED;
2807 }
2808 State state = mKeyStore->getState(getEffectiveUid(targetUid));
2809 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2810 return state;
2811 }
2812
2813 return ::NO_ERROR;
2814
2815 }
2816
Kenny Root9d45d1c2013-02-14 10:32:30 -08002817 inline bool isKeystoreUnlocked(State state) {
2818 switch (state) {
2819 case ::STATE_NO_ERROR:
2820 return true;
2821 case ::STATE_UNINITIALIZED:
2822 case ::STATE_LOCKED:
2823 return false;
2824 }
2825 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002826 }
2827
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002828 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002829 const int32_t device_api = device->common.module->module_api_version;
2830 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2831 switch (keyType) {
2832 case TYPE_RSA:
2833 case TYPE_DSA:
2834 case TYPE_EC:
2835 return true;
2836 default:
2837 return false;
2838 }
2839 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2840 switch (keyType) {
2841 case TYPE_RSA:
2842 return true;
2843 case TYPE_DSA:
2844 return device->flags & KEYMASTER_SUPPORTS_DSA;
2845 case TYPE_EC:
2846 return device->flags & KEYMASTER_SUPPORTS_EC;
2847 default:
2848 return false;
2849 }
2850 } else {
2851 return keyType == TYPE_RSA;
2852 }
2853 }
2854
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002855 /**
2856 * Check that all keymaster_key_param_t's provided by the application are
2857 * allowed. Any parameter that keystore adds itself should be disallowed here.
2858 */
2859 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2860 for (auto param: params) {
2861 switch (param.tag) {
2862 case KM_TAG_AUTH_TOKEN:
2863 return false;
2864 default:
2865 break;
2866 }
2867 }
2868 return true;
2869 }
2870
2871 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2872 const keymaster1_device_t* dev,
2873 const std::vector<keymaster_key_param_t>& params,
2874 keymaster_key_characteristics_t* out) {
2875 UniquePtr<keymaster_blob_t> appId;
2876 UniquePtr<keymaster_blob_t> appData;
2877 for (auto param : params) {
2878 if (param.tag == KM_TAG_APPLICATION_ID) {
2879 appId.reset(new keymaster_blob_t);
2880 appId->data = param.blob.data;
2881 appId->data_length = param.blob.data_length;
2882 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2883 appData.reset(new keymaster_blob_t);
2884 appData->data = param.blob.data;
2885 appData->data_length = param.blob.data_length;
2886 }
2887 }
2888 keymaster_key_characteristics_t* result = NULL;
2889 if (!dev->get_key_characteristics) {
2890 return KM_ERROR_UNIMPLEMENTED;
2891 }
2892 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2893 appData.get(), &result);
2894 if (result) {
2895 *out = *result;
2896 free(result);
2897 }
2898 return error;
2899 }
2900
2901 /**
2902 * Get the auth token for this operation from the auth token table.
2903 *
2904 * Returns ::NO_ERROR if the auth token was set or none was required.
2905 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2906 * authorization token exists for that operation and
2907 * failOnTokenMissing is false.
2908 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2909 * token for the operation
2910 */
2911 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2912 keymaster_operation_handle_t handle,
2913 const hw_auth_token_t** authToken,
2914 bool failOnTokenMissing = true) {
2915
2916 std::vector<keymaster_key_param_t> allCharacteristics;
2917 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2918 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2919 }
2920 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2921 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2922 }
2923 keymaster::AuthTokenTable::Error err =
2924 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2925 allCharacteristics.size(), handle, authToken);
2926 switch (err) {
2927 case keymaster::AuthTokenTable::OK:
2928 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2929 return ::NO_ERROR;
2930 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2931 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2932 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2933 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2934 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2935 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2936 (int32_t) ::OP_AUTH_NEEDED;
2937 default:
2938 ALOGE("Unexpected FindAuthorization return value %d", err);
2939 return KM_ERROR_INVALID_ARGUMENT;
2940 }
2941 }
2942
2943 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2944 const hw_auth_token_t* token) {
2945 if (token) {
2946 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2947 reinterpret_cast<const uint8_t*>(token),
2948 sizeof(hw_auth_token_t)));
2949 }
2950 }
2951
2952 /**
2953 * Add the auth token for the operation to the param list if the operation
2954 * requires authorization. Uses the cached result in the OperationMap if available
2955 * otherwise gets the token from the AuthTokenTable and caches the result.
2956 *
2957 * Returns ::NO_ERROR if the auth token was added or not needed.
2958 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2959 * authenticated.
2960 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2961 * operation token.
2962 */
2963 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2964 std::vector<keymaster_key_param_t>* params) {
2965 const hw_auth_token_t* authToken = NULL;
Chad Brubaker6b541162015-04-29 19:58:34 -07002966 mOperationMap.getOperationAuthToken(token, &authToken);
2967 if (!authToken) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002968 const keymaster1_device_t* dev;
2969 keymaster_operation_handle_t handle;
2970 const keymaster_key_characteristics_t* characteristics = NULL;
2971 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
2972 return KM_ERROR_INVALID_OPERATION_HANDLE;
2973 }
2974 int32_t result = getAuthToken(characteristics, handle, &authToken);
2975 if (result != ::NO_ERROR) {
2976 return result;
2977 }
2978 if (authToken) {
2979 mOperationMap.setOperationAuthToken(token, authToken);
2980 }
2981 }
2982 addAuthToParams(params, authToken);
2983 return ::NO_ERROR;
2984 }
2985
Kenny Root07438c82012-11-02 15:41:02 -07002986 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002987 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002988 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07002989};
2990
2991}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002992
2993int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002994 if (argc < 2) {
2995 ALOGE("A directory must be specified!");
2996 return 1;
2997 }
2998 if (chdir(argv[1]) == -1) {
2999 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3000 return 1;
3001 }
3002
3003 Entropy entropy;
3004 if (!entropy.open()) {
3005 return 1;
3006 }
Kenny Root70e3a862012-02-15 17:20:23 -08003007
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07003008 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003009 if (keymaster_device_initialize(&dev)) {
3010 ALOGE("keystore keymaster could not be initialized; exiting");
3011 return 1;
3012 }
3013
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003014 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003015 if (fallback_keymaster_device_initialize(&fallback)) {
3016 ALOGE("software keymaster could not be initialized; exiting");
3017 return 1;
3018 }
3019
Riley Spahneaabae92014-06-30 12:39:52 -07003020 ks_is_selinux_enabled = is_selinux_enabled();
3021 if (ks_is_selinux_enabled) {
3022 union selinux_callback cb;
3023 cb.func_log = selinux_log_callback;
3024 selinux_set_callback(SELINUX_CB_LOG, cb);
3025 if (getcon(&tctx) != 0) {
3026 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3027 return -1;
3028 }
3029 } else {
3030 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3031 }
3032
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003033 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003034 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003035 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3036 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3037 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3038 if (ret != android::OK) {
3039 ALOGE("Couldn't register binder service!");
3040 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003041 }
Kenny Root07438c82012-11-02 15:41:02 -07003042
3043 /*
3044 * We're the only thread in existence, so we're just going to process
3045 * Binder transaction as a single-threaded program.
3046 */
3047 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003048
3049 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003050 return 1;
3051}