blob: 360619cc502ddde22353d28c7fb4b088a77f4fbb [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
Chad Brubakereecdd122015-05-07 10:19:40 -0700771 bool deleteMasterKey() {
772 setState(STATE_UNINITIALIZED);
773 zeroizeMasterKeysInMemory();
774 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
775 }
776
Kenny Root655b9582013-04-04 08:37:42 -0700777 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
778 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800779 return SYSTEM_ERROR;
780 }
Kenny Root655b9582013-04-04 08:37:42 -0700781 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800782 if (response != NO_ERROR) {
783 return response;
784 }
785 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700786 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800787 }
788
Robin Lee4e865752014-08-19 17:37:55 +0100789 ResponseCode copyMasterKey(UserState* src) {
790 if (mState != STATE_UNINITIALIZED) {
791 return ::SYSTEM_ERROR;
792 }
793 if (src->getState() != STATE_NO_ERROR) {
794 return ::SYSTEM_ERROR;
795 }
796 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
797 setupMasterKeys();
798 return ::NO_ERROR;
799 }
800
Kenny Root655b9582013-04-04 08:37:42 -0700801 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800802 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
803 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
804 AES_KEY passwordAesKey;
805 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700806 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700807 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800808 }
809
Kenny Root655b9582013-04-04 08:37:42 -0700810 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
811 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800812 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800813 return SYSTEM_ERROR;
814 }
815
816 // we read the raw blob to just to get the salt to generate
817 // the AES key, then we create the Blob to use with decryptBlob
818 blob rawBlob;
819 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
820 if (close(in) != 0) {
821 return SYSTEM_ERROR;
822 }
823 // find salt at EOF if present, otherwise we have an old file
824 uint8_t* salt;
825 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
826 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
827 } else {
828 salt = NULL;
829 }
830 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
831 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
832 AES_KEY passwordAesKey;
833 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
834 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700835 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
836 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800837 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700838 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800839 }
840 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
841 // if salt was missing, generate one and write a new master key file with the salt.
842 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700843 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800844 return SYSTEM_ERROR;
845 }
Kenny Root655b9582013-04-04 08:37:42 -0700846 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800847 }
848 if (response == NO_ERROR) {
849 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
850 setupMasterKeys();
851 }
852 return response;
853 }
854 if (mRetry <= 0) {
855 reset();
856 return UNINITIALIZED;
857 }
858 --mRetry;
859 switch (mRetry) {
860 case 0: return WRONG_PASSWORD_0;
861 case 1: return WRONG_PASSWORD_1;
862 case 2: return WRONG_PASSWORD_2;
863 case 3: return WRONG_PASSWORD_3;
864 default: return WRONG_PASSWORD_3;
865 }
866 }
867
Kenny Root655b9582013-04-04 08:37:42 -0700868 AES_KEY* getEncryptionKey() {
869 return &mMasterKeyEncryption;
870 }
871
872 AES_KEY* getDecryptionKey() {
873 return &mMasterKeyDecryption;
874 }
875
Kenny Roota91203b2012-02-15 15:00:46 -0800876 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700877 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800878 if (!dir) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700879 // If the directory doesn't exist then nothing to do.
880 if (errno == ENOENT) {
881 return true;
882 }
Kenny Root655b9582013-04-04 08:37:42 -0700883 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800884 return false;
885 }
Kenny Root655b9582013-04-04 08:37:42 -0700886
887 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800888 while ((file = readdir(dir)) != NULL) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700889 // skip . and ..
890 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700891 continue;
892 }
893
894 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800895 }
896 closedir(dir);
897 return true;
898 }
899
Kenny Root655b9582013-04-04 08:37:42 -0700900private:
901 static const int MASTER_KEY_SIZE_BYTES = 16;
902 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
903
904 static const int MAX_RETRY = 4;
905 static const size_t SALT_SIZE = 16;
906
907 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
908 uint8_t* salt) {
909 size_t saltSize;
910 if (salt != NULL) {
911 saltSize = SALT_SIZE;
912 } else {
913 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
914 salt = (uint8_t*) "keystore";
915 // sizeof = 9, not strlen = 8
916 saltSize = sizeof("keystore");
917 }
918
919 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
920 saltSize, 8192, keySize, key);
921 }
922
923 bool generateSalt(Entropy* entropy) {
924 return entropy->generate_random_data(mSalt, sizeof(mSalt));
925 }
926
927 bool generateMasterKey(Entropy* entropy) {
928 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
929 return false;
930 }
931 if (!generateSalt(entropy)) {
932 return false;
933 }
934 return true;
935 }
936
937 void setupMasterKeys() {
938 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
939 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
940 setState(STATE_NO_ERROR);
941 }
942
943 uid_t mUserId;
944
945 char* mUserDir;
946 char* mMasterKeyFile;
947
948 State mState;
949 int8_t mRetry;
950
951 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
952 uint8_t mSalt[SALT_SIZE];
953
954 AES_KEY mMasterKeyEncryption;
955 AES_KEY mMasterKeyDecryption;
956};
957
958typedef struct {
959 uint32_t uid;
960 const uint8_t* filename;
961} grant_t;
962
963class KeyStore {
964public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800965 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700966 : mEntropy(entropy)
967 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800968 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700969 {
970 memset(&mMetaData, '\0', sizeof(mMetaData));
971 }
972
973 ~KeyStore() {
974 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
975 it != mGrants.end(); it++) {
976 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700977 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800978 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700979
980 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
981 it != mMasterKeys.end(); it++) {
982 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700983 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800984 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700985 }
986
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800987 /**
988 * Depending on the hardware keymaster version is this may return a
989 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
990 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
991 * be guarded by a check on the device's version.
992 */
993 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700994 return mDevice;
995 }
996
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800997 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800998 return mFallbackDevice;
999 }
1000
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001001 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001002 return blob.isFallback() ? mFallbackDevice: mDevice;
1003 }
1004
Kenny Root655b9582013-04-04 08:37:42 -07001005 ResponseCode initialize() {
1006 readMetaData();
1007 if (upgradeKeystore()) {
1008 writeMetaData();
1009 }
1010
1011 return ::NO_ERROR;
1012 }
1013
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001014 State getState(uid_t userId) {
1015 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001016 }
1017
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001018 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1019 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001020 return userState->initialize(pw, mEntropy);
1021 }
1022
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001023 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1024 UserState *userState = getUserState(dstUser);
1025 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001026 return userState->copyMasterKey(initState);
1027 }
1028
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001029 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1030 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001031 return userState->writeMasterKey(pw, mEntropy);
1032 }
1033
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001034 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1035 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001036 return userState->readMasterKey(pw, mEntropy);
1037 }
1038
1039 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001040 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001041 encode_key(encoded, keyName);
1042 return android::String8(encoded);
1043 }
1044
1045 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001046 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001047 encode_key(encoded, keyName);
1048 return android::String8::format("%u_%s", uid, encoded);
1049 }
1050
1051 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001052 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001053 encode_key(encoded, keyName);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001054 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001055 encoded);
1056 }
1057
Chad Brubakereecdd122015-05-07 10:19:40 -07001058 /*
1059 * Delete entries owned by userId. If keepUnencryptedEntries is true
1060 * then only encrypted entries will be removed, otherwise all entries will
1061 * be removed.
1062 */
1063 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001064 android::String8 prefix("");
1065 android::Vector<android::String16> aliases;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001066 UserState* userState = getUserState(userId);
1067 if (saw(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001068 return;
1069 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001070 for (uint32_t i = 0; i < aliases.size(); i++) {
1071 android::String8 filename(aliases[i]);
1072 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubakereecdd122015-05-07 10:19:40 -07001073 getKeyName(filename).string());
1074 bool shouldDelete = true;
1075 if (keepUnenryptedEntries) {
1076 Blob blob;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001077 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001078
Chad Brubakereecdd122015-05-07 10:19:40 -07001079 /* get can fail if the blob is encrypted and the state is
1080 * not unlocked, only skip deleting blobs that were loaded and
1081 * who are not encrypted. If there are blobs we fail to read for
1082 * other reasons err on the safe side and delete them since we
1083 * can't tell if they're encrypted.
1084 */
1085 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1086 }
1087 if (shouldDelete) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001088 del(filename, ::TYPE_ANY, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001089 }
1090 }
1091 if (!userState->deleteMasterKey()) {
1092 ALOGE("Failed to delete user %d's master key", userId);
1093 }
1094 if (!keepUnenryptedEntries) {
1095 if(!userState->reset()) {
1096 ALOGE("Failed to remove user %d's directory", userId);
1097 }
1098 }
Kenny Root655b9582013-04-04 08:37:42 -07001099 }
1100
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001101 bool isEmpty(uid_t userId) const {
1102 const UserState* userState = getUserState(userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001103 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001104 return true;
1105 }
1106
1107 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001108 if (!dir) {
1109 return true;
1110 }
Kenny Root31e27462014-09-10 11:28:03 -07001111
Kenny Roota91203b2012-02-15 15:00:46 -08001112 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001113 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001114 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001115 // We only care about files.
1116 if (file->d_type != DT_REG) {
1117 continue;
1118 }
1119
1120 // Skip anything that starts with a "."
1121 if (file->d_name[0] == '.') {
1122 continue;
1123 }
1124
Kenny Root31e27462014-09-10 11:28:03 -07001125 result = false;
1126 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001127 }
1128 closedir(dir);
1129 return result;
1130 }
1131
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001132 void lock(uid_t userId) {
1133 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001134 userState->zeroizeMasterKeysInMemory();
1135 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001136 }
1137
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001138 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1139 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001140 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1141 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001142 if (rc != NO_ERROR) {
1143 return rc;
1144 }
1145
1146 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001147 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001148 /* If we upgrade the key, we need to write it to disk again. Then
1149 * it must be read it again since the blob is encrypted each time
1150 * it's written.
1151 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001152 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1153 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001154 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1155 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001156 return rc;
1157 }
1158 }
Kenny Root822c3a92012-03-23 16:34:39 -07001159 }
1160
Kenny Root17208e02013-09-04 13:56:03 -07001161 /*
1162 * This will upgrade software-backed keys to hardware-backed keys when
1163 * the HAL for the device supports the newer key types.
1164 */
1165 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1166 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1167 && keyBlob->isFallback()) {
1168 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001169 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001170
1171 // The HAL allowed the import, reget the key to have the "fresh"
1172 // version.
1173 if (imported == NO_ERROR) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001174 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001175 }
1176 }
1177
Kenny Rootd53bc922013-03-21 14:10:15 -07001178 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001179 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1180 return KEY_NOT_FOUND;
1181 }
1182
1183 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001184 }
1185
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001186 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1187 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001188 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1189 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001190 }
1191
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001192 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001193 Blob keyBlob;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001194 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001195 if (rc != ::NO_ERROR) {
1196 return rc;
1197 }
1198
1199 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1200 // A device doesn't have to implement delete_keypair.
1201 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1202 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1203 rc = ::SYSTEM_ERROR;
1204 }
1205 }
1206 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001207 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1208 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1209 if (dev->delete_key) {
1210 keymaster_key_blob_t blob;
1211 blob.key_material = keyBlob.getValue();
1212 blob.key_material_size = keyBlob.getLength();
1213 dev->delete_key(dev, &blob);
1214 }
1215 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001216 if (rc != ::NO_ERROR) {
1217 return rc;
1218 }
1219
1220 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1221 }
1222
1223 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001224 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001225
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001226 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001227 size_t n = prefix.length();
1228
1229 DIR* dir = opendir(userState->getUserDirName());
1230 if (!dir) {
1231 ALOGW("can't open directory for user: %s", strerror(errno));
1232 return ::SYSTEM_ERROR;
1233 }
1234
1235 struct dirent* file;
1236 while ((file = readdir(dir)) != NULL) {
1237 // We only care about files.
1238 if (file->d_type != DT_REG) {
1239 continue;
1240 }
1241
1242 // Skip anything that starts with a "."
1243 if (file->d_name[0] == '.') {
1244 continue;
1245 }
1246
1247 if (!strncmp(prefix.string(), file->d_name, n)) {
1248 const char* p = &file->d_name[n];
1249 size_t plen = strlen(p);
1250
1251 size_t extra = decode_key_length(p, plen);
1252 char *match = (char*) malloc(extra + 1);
1253 if (match != NULL) {
1254 decode_key(match, p, plen);
1255 matches->push(android::String16(match, extra));
1256 free(match);
1257 } else {
1258 ALOGW("could not allocate match of size %zd", extra);
1259 }
1260 }
1261 }
1262 closedir(dir);
1263 return ::NO_ERROR;
1264 }
1265
Kenny Root07438c82012-11-02 15:41:02 -07001266 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001267 const grant_t* existing = getGrant(filename, granteeUid);
1268 if (existing == NULL) {
1269 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001270 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001271 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001272 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001273 }
1274 }
1275
Kenny Root07438c82012-11-02 15:41:02 -07001276 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001277 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1278 it != mGrants.end(); it++) {
1279 grant_t* grant = *it;
1280 if (grant->uid == granteeUid
1281 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1282 mGrants.erase(it);
1283 return true;
1284 }
Kenny Root70e3a862012-02-15 17:20:23 -08001285 }
Kenny Root70e3a862012-02-15 17:20:23 -08001286 return false;
1287 }
1288
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001289 bool hasGrant(const char* filename, const uid_t uid) const {
1290 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001291 }
1292
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001293 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001294 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001295 uint8_t* data;
1296 size_t dataLength;
1297 int rc;
1298
1299 if (mDevice->import_keypair == NULL) {
1300 ALOGE("Keymaster doesn't support import!");
1301 return SYSTEM_ERROR;
1302 }
1303
Kenny Root17208e02013-09-04 13:56:03 -07001304 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001305 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001306 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001307 /*
1308 * Maybe the device doesn't support this type of key. Try to use the
1309 * software fallback keymaster implementation. This is a little bit
1310 * lazier than checking the PKCS#8 key type, but the software
1311 * implementation will do that anyway.
1312 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001313 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001314 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001315
1316 if (rc) {
1317 ALOGE("Error while importing keypair: %d", rc);
1318 return SYSTEM_ERROR;
1319 }
Kenny Root822c3a92012-03-23 16:34:39 -07001320 }
1321
1322 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1323 free(data);
1324
Kenny Rootf9119d62013-04-03 09:22:15 -07001325 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001326 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001327
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001328 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001329 }
1330
Kenny Root1b0e3932013-09-05 13:06:32 -07001331 bool isHardwareBacked(const android::String16& keyType) const {
1332 if (mDevice == NULL) {
1333 ALOGW("can't get keymaster device");
1334 return false;
1335 }
1336
1337 if (sRSAKeyType == keyType) {
1338 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1339 } else {
1340 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1341 && (mDevice->common.module->module_api_version
1342 >= KEYMASTER_MODULE_API_VERSION_0_2);
1343 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001344 }
1345
Kenny Root655b9582013-04-04 08:37:42 -07001346 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1347 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001348 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001349 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001350
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001351 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001352 if (responseCode == NO_ERROR) {
1353 return responseCode;
1354 }
1355
1356 // If this is one of the legacy UID->UID mappings, use it.
1357 uid_t euid = get_keystore_euid(uid);
1358 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001359 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001360 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001361 if (responseCode == NO_ERROR) {
1362 return responseCode;
1363 }
1364 }
1365
1366 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001367 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001368 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001369 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001370 if (end[0] != '_' || end[1] == 0) {
1371 return KEY_NOT_FOUND;
1372 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001373 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001374 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001375 if (!hasGrant(filepath8.string(), uid)) {
1376 return responseCode;
1377 }
1378
1379 // It is a granted key. Try to load it.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001380 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001381 }
1382
1383 /**
1384 * Returns any existing UserState or creates it if it doesn't exist.
1385 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001386 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001387 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1388 it != mMasterKeys.end(); it++) {
1389 UserState* state = *it;
1390 if (state->getUserId() == userId) {
1391 return state;
1392 }
1393 }
1394
1395 UserState* userState = new UserState(userId);
1396 if (!userState->initialize()) {
1397 /* There's not much we can do if initialization fails. Trying to
1398 * unlock the keystore for that user will fail as well, so any
1399 * subsequent request for this user will just return SYSTEM_ERROR.
1400 */
1401 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1402 }
1403 mMasterKeys.add(userState);
1404 return userState;
1405 }
1406
1407 /**
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001408 * Returns any existing UserState or creates it if it doesn't exist.
1409 */
1410 UserState* getUserStateByUid(uid_t uid) {
1411 uid_t userId = get_user_id(uid);
1412 return getUserState(userId);
1413 }
1414
1415 /**
Kenny Root655b9582013-04-04 08:37:42 -07001416 * Returns NULL if the UserState doesn't already exist.
1417 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001418 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001419 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1420 it != mMasterKeys.end(); it++) {
1421 UserState* state = *it;
1422 if (state->getUserId() == userId) {
1423 return state;
1424 }
1425 }
1426
1427 return NULL;
1428 }
1429
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001430 /**
1431 * Returns NULL if the UserState doesn't already exist.
1432 */
1433 const UserState* getUserStateByUid(uid_t uid) const {
1434 uid_t userId = get_user_id(uid);
1435 return getUserState(userId);
1436 }
1437
Kenny Roota91203b2012-02-15 15:00:46 -08001438private:
Kenny Root655b9582013-04-04 08:37:42 -07001439 static const char* sOldMasterKey;
1440 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001441 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001442 Entropy* mEntropy;
1443
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001444 keymaster1_device_t* mDevice;
1445 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001446
Kenny Root655b9582013-04-04 08:37:42 -07001447 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001448
Kenny Root655b9582013-04-04 08:37:42 -07001449 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001450
Kenny Root655b9582013-04-04 08:37:42 -07001451 typedef struct {
1452 uint32_t version;
1453 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001454
Kenny Root655b9582013-04-04 08:37:42 -07001455 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001456
Kenny Root655b9582013-04-04 08:37:42 -07001457 const grant_t* getGrant(const char* filename, uid_t uid) const {
1458 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1459 it != mGrants.end(); it++) {
1460 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001461 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001462 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001463 return grant;
1464 }
1465 }
Kenny Root70e3a862012-02-15 17:20:23 -08001466 return NULL;
1467 }
1468
Kenny Root822c3a92012-03-23 16:34:39 -07001469 /**
1470 * Upgrade code. This will upgrade the key from the current version
1471 * to whatever is newest.
1472 */
Kenny Root655b9582013-04-04 08:37:42 -07001473 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1474 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001475 bool updated = false;
1476 uint8_t version = oldVersion;
1477
1478 /* From V0 -> V1: All old types were unknown */
1479 if (version == 0) {
1480 ALOGV("upgrading to version 1 and setting type %d", type);
1481
1482 blob->setType(type);
1483 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001484 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001485 }
1486 version = 1;
1487 updated = true;
1488 }
1489
Kenny Rootf9119d62013-04-03 09:22:15 -07001490 /* From V1 -> V2: All old keys were encrypted */
1491 if (version == 1) {
1492 ALOGV("upgrading to version 2");
1493
1494 blob->setEncrypted(true);
1495 version = 2;
1496 updated = true;
1497 }
1498
Kenny Root822c3a92012-03-23 16:34:39 -07001499 /*
1500 * If we've updated, set the key blob to the right version
1501 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001502 */
Kenny Root822c3a92012-03-23 16:34:39 -07001503 if (updated) {
1504 ALOGV("updated and writing file %s", filename);
1505 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001506 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001507
1508 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001509 }
1510
1511 /**
1512 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1513 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1514 * Then it overwrites the original blob with the new blob
1515 * format that is returned from the keymaster.
1516 */
Kenny Root655b9582013-04-04 08:37:42 -07001517 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001518 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1519 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1520 if (b.get() == NULL) {
1521 ALOGE("Problem instantiating BIO");
1522 return SYSTEM_ERROR;
1523 }
1524
1525 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1526 if (pkey.get() == NULL) {
1527 ALOGE("Couldn't read old PEM file");
1528 return SYSTEM_ERROR;
1529 }
1530
1531 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1532 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1533 if (len < 0) {
1534 ALOGE("Couldn't measure PKCS#8 length");
1535 return SYSTEM_ERROR;
1536 }
1537
Kenny Root70c98892013-02-07 09:10:36 -08001538 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1539 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001540 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1541 ALOGE("Couldn't convert to PKCS#8");
1542 return SYSTEM_ERROR;
1543 }
1544
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001545 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001546 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001547 if (rc != NO_ERROR) {
1548 return rc;
1549 }
1550
Kenny Root655b9582013-04-04 08:37:42 -07001551 return get(filename, blob, TYPE_KEY_PAIR, uid);
1552 }
1553
1554 void readMetaData() {
1555 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1556 if (in < 0) {
1557 return;
1558 }
1559 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1560 if (fileLength != sizeof(mMetaData)) {
1561 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1562 sizeof(mMetaData));
1563 }
1564 close(in);
1565 }
1566
1567 void writeMetaData() {
1568 const char* tmpFileName = ".metadata.tmp";
1569 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1570 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1571 if (out < 0) {
1572 ALOGE("couldn't write metadata file: %s", strerror(errno));
1573 return;
1574 }
1575 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1576 if (fileLength != sizeof(mMetaData)) {
1577 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1578 sizeof(mMetaData));
1579 }
1580 close(out);
1581 rename(tmpFileName, sMetaDataFile);
1582 }
1583
1584 bool upgradeKeystore() {
1585 bool upgraded = false;
1586
1587 if (mMetaData.version == 0) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001588 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001589
1590 // Initialize first so the directory is made.
1591 userState->initialize();
1592
1593 // Migrate the old .masterkey file to user 0.
1594 if (access(sOldMasterKey, R_OK) == 0) {
1595 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1596 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1597 return false;
1598 }
1599 }
1600
1601 // Initialize again in case we had a key.
1602 userState->initialize();
1603
1604 // Try to migrate existing keys.
1605 DIR* dir = opendir(".");
1606 if (!dir) {
1607 // Give up now; maybe we can upgrade later.
1608 ALOGE("couldn't open keystore's directory; something is wrong");
1609 return false;
1610 }
1611
1612 struct dirent* file;
1613 while ((file = readdir(dir)) != NULL) {
1614 // We only care about files.
1615 if (file->d_type != DT_REG) {
1616 continue;
1617 }
1618
1619 // Skip anything that starts with a "."
1620 if (file->d_name[0] == '.') {
1621 continue;
1622 }
1623
1624 // Find the current file's user.
1625 char* end;
1626 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1627 if (end[0] != '_' || end[1] == 0) {
1628 continue;
1629 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001630 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001631 if (otherUser->getUserId() != 0) {
1632 unlinkat(dirfd(dir), file->d_name, 0);
1633 }
1634
1635 // Rename the file into user directory.
1636 DIR* otherdir = opendir(otherUser->getUserDirName());
1637 if (otherdir == NULL) {
1638 ALOGW("couldn't open user directory for rename");
1639 continue;
1640 }
1641 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1642 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1643 }
1644 closedir(otherdir);
1645 }
1646 closedir(dir);
1647
1648 mMetaData.version = 1;
1649 upgraded = true;
1650 }
1651
1652 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001653 }
Kenny Roota91203b2012-02-15 15:00:46 -08001654};
1655
Kenny Root655b9582013-04-04 08:37:42 -07001656const char* KeyStore::sOldMasterKey = ".masterkey";
1657const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001658
Kenny Root1b0e3932013-09-05 13:06:32 -07001659const android::String16 KeyStore::sRSAKeyType("RSA");
1660
Kenny Root07438c82012-11-02 15:41:02 -07001661namespace android {
1662class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1663public:
1664 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001665 : mKeyStore(keyStore),
1666 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001667 {
Kenny Roota91203b2012-02-15 15:00:46 -08001668 }
Kenny Roota91203b2012-02-15 15:00:46 -08001669
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001670 void binderDied(const wp<IBinder>& who) {
1671 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1672 for (auto token: operations) {
1673 abort(token);
1674 }
Kenny Root822c3a92012-03-23 16:34:39 -07001675 }
Kenny Roota91203b2012-02-15 15:00:46 -08001676
Kenny Root07438c82012-11-02 15:41:02 -07001677 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001678 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001679 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001680 }
Kenny Roota91203b2012-02-15 15:00:46 -08001681
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001682 return mKeyStore->getState(get_user_id(IPCThreadState::self()->getCallingUid()));
Kenny Root298e7b12012-03-26 13:54:44 -07001683 }
1684
Kenny Root07438c82012-11-02 15:41:02 -07001685 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001686 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001687 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001688 }
Kenny Root07438c82012-11-02 15:41:02 -07001689
Chad Brubaker9489b792015-04-14 11:01:45 -07001690 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001691 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001692 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001693
Kenny Root655b9582013-04-04 08:37:42 -07001694 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001695 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001696 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001697 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001698 *item = NULL;
1699 *itemLength = 0;
1700 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001701 }
Kenny Roota91203b2012-02-15 15:00:46 -08001702
Kenny Root07438c82012-11-02 15:41:02 -07001703 *item = (uint8_t*) malloc(keyBlob.getLength());
1704 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1705 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001706
Kenny Root07438c82012-11-02 15:41:02 -07001707 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001708 }
1709
Kenny Rootf9119d62013-04-03 09:22:15 -07001710 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1711 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001712 targetUid = getEffectiveUid(targetUid);
1713 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1714 flags & KEYSTORE_FLAG_ENCRYPTED);
1715 if (result != ::NO_ERROR) {
1716 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001717 }
1718
Kenny Root07438c82012-11-02 15:41:02 -07001719 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001720 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001721
1722 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001723 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1724
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001725 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001726 }
1727
Kenny Root49468902013-03-19 13:41:33 -07001728 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001729 targetUid = getEffectiveUid(targetUid);
1730 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001731 return ::PERMISSION_DENIED;
1732 }
Kenny Root07438c82012-11-02 15:41:02 -07001733 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001734 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001735 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001736 }
1737
Kenny Root49468902013-03-19 13:41:33 -07001738 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001739 targetUid = getEffectiveUid(targetUid);
1740 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001741 return ::PERMISSION_DENIED;
1742 }
1743
Kenny Root07438c82012-11-02 15:41:02 -07001744 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001745 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001746
Kenny Root655b9582013-04-04 08:37:42 -07001747 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001748 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1749 }
1750 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001751 }
1752
Kenny Root49468902013-03-19 13:41:33 -07001753 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001754 targetUid = getEffectiveUid(targetUid);
1755 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001756 return ::PERMISSION_DENIED;
1757 }
Kenny Root07438c82012-11-02 15:41:02 -07001758 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001759 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001760
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001761 if (mKeyStore->saw(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001762 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001763 }
Kenny Root07438c82012-11-02 15:41:02 -07001764 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001765 }
1766
Kenny Root07438c82012-11-02 15:41:02 -07001767 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001768 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001769 return ::PERMISSION_DENIED;
1770 }
1771
Chad Brubaker9489b792015-04-14 11:01:45 -07001772 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubakereecdd122015-05-07 10:19:40 -07001773 mKeyStore->resetUser(get_user_id(callingUid), false);
1774 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001775 }
1776
Chad Brubakereecdd122015-05-07 10:19:40 -07001777 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001778 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001779 return ::PERMISSION_DENIED;
1780 }
Kenny Root70e3a862012-02-15 17:20:23 -08001781
Kenny Root07438c82012-11-02 15:41:02 -07001782 const String8 password8(password);
Chad Brubakereecdd122015-05-07 10:19:40 -07001783 // Flush the auth token table to prevent stale tokens from sticking
1784 // around.
1785 mAuthTokenTable.Clear();
1786
1787 if (password.size() == 0) {
1788 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001789 mKeyStore->resetUser(userId, true);
Chad Brubakereecdd122015-05-07 10:19:40 -07001790 return ::NO_ERROR;
1791 } else {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001792 switch (mKeyStore->getState(userId)) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001793 case ::STATE_UNINITIALIZED: {
1794 // generate master key, encrypt with password, write to file,
1795 // initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001796 return mKeyStore->initializeUser(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001797 }
1798 case ::STATE_NO_ERROR: {
1799 // rewrite master key with new password.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001800 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001801 }
1802 case ::STATE_LOCKED: {
1803 ALOGE("Changing user %d's password while locked, clearing old encryption",
1804 userId);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001805 mKeyStore->resetUser(userId, true);
1806 return mKeyStore->initializeUser(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001807 }
Kenny Root07438c82012-11-02 15:41:02 -07001808 }
Chad Brubakereecdd122015-05-07 10:19:40 -07001809 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001810 }
Kenny Root70e3a862012-02-15 17:20:23 -08001811 }
1812
Kenny Root07438c82012-11-02 15:41:02 -07001813 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001814 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001815 return ::PERMISSION_DENIED;
1816 }
Kenny Root70e3a862012-02-15 17:20:23 -08001817
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001818 uid_t userId = get_user_id(IPCThreadState::self()->getCallingUid());
1819 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001820 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001821 ALOGD("calling lock in state: %d", state);
1822 return state;
1823 }
1824
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001825 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001826 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001827 }
1828
Chad Brubakereecdd122015-05-07 10:19:40 -07001829 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001830 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001831 return ::PERMISSION_DENIED;
1832 }
1833
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001834 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001835 if (state != ::STATE_LOCKED) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001836 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001837 return state;
1838 }
1839
1840 const String8 password8(pw);
Chad Brubakereecdd122015-05-07 10:19:40 -07001841 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001842 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001843 }
1844
Kenny Root07438c82012-11-02 15:41:02 -07001845 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001846 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001847 return -1;
1848 }
Kenny Root70e3a862012-02-15 17:20:23 -08001849
Chad Brubaker9489b792015-04-14 11:01:45 -07001850 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001851 return mKeyStore->isEmpty(get_user_id(callingUid)) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001852 }
1853
Kenny Root96427ba2013-08-16 14:02:41 -07001854 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1855 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001856 targetUid = getEffectiveUid(targetUid);
1857 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1858 flags & KEYSTORE_FLAG_ENCRYPTED);
1859 if (result != ::NO_ERROR) {
1860 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001861 }
Kenny Root07438c82012-11-02 15:41:02 -07001862 uint8_t* data;
1863 size_t dataLength;
1864 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001865 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001866
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001867 const keymaster1_device_t* device = mKeyStore->getDevice();
1868 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001869 if (device == NULL) {
1870 return ::SYSTEM_ERROR;
1871 }
1872
1873 if (device->generate_keypair == NULL) {
1874 return ::SYSTEM_ERROR;
1875 }
1876
Kenny Root17208e02013-09-04 13:56:03 -07001877 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001878 keymaster_dsa_keygen_params_t dsa_params;
1879 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001880
Kenny Root96427ba2013-08-16 14:02:41 -07001881 if (keySize == -1) {
1882 keySize = DSA_DEFAULT_KEY_SIZE;
1883 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1884 || keySize > DSA_MAX_KEY_SIZE) {
1885 ALOGI("invalid key size %d", keySize);
1886 return ::SYSTEM_ERROR;
1887 }
1888 dsa_params.key_size = keySize;
1889
1890 if (args->size() == 3) {
1891 sp<KeystoreArg> gArg = args->itemAt(0);
1892 sp<KeystoreArg> pArg = args->itemAt(1);
1893 sp<KeystoreArg> qArg = args->itemAt(2);
1894
1895 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1896 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1897 dsa_params.generator_len = gArg->size();
1898
1899 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1900 dsa_params.prime_p_len = pArg->size();
1901
1902 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1903 dsa_params.prime_q_len = qArg->size();
1904 } else {
1905 ALOGI("not all DSA parameters were read");
1906 return ::SYSTEM_ERROR;
1907 }
1908 } else if (args->size() != 0) {
1909 ALOGI("DSA args must be 3");
1910 return ::SYSTEM_ERROR;
1911 }
1912
Kenny Root1d448c02013-11-21 10:36:53 -08001913 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001914 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1915 } else {
1916 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001917 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1918 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001919 }
1920 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001921 keymaster_ec_keygen_params_t ec_params;
1922 memset(&ec_params, '\0', sizeof(ec_params));
1923
1924 if (keySize == -1) {
1925 keySize = EC_DEFAULT_KEY_SIZE;
1926 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1927 ALOGI("invalid key size %d", keySize);
1928 return ::SYSTEM_ERROR;
1929 }
1930 ec_params.field_size = keySize;
1931
Kenny Root1d448c02013-11-21 10:36:53 -08001932 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001933 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1934 } else {
1935 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001936 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001937 }
Kenny Root96427ba2013-08-16 14:02:41 -07001938 } else if (keyType == EVP_PKEY_RSA) {
1939 keymaster_rsa_keygen_params_t rsa_params;
1940 memset(&rsa_params, '\0', sizeof(rsa_params));
1941 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1942
1943 if (keySize == -1) {
1944 keySize = RSA_DEFAULT_KEY_SIZE;
1945 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1946 ALOGI("invalid key size %d", keySize);
1947 return ::SYSTEM_ERROR;
1948 }
1949 rsa_params.modulus_size = keySize;
1950
1951 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001952 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001953 return ::SYSTEM_ERROR;
1954 } else if (args->size() == 1) {
1955 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1956 if (pubExpBlob != NULL) {
1957 Unique_BIGNUM pubExpBn(
1958 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1959 pubExpBlob->size(), NULL));
1960 if (pubExpBn.get() == NULL) {
1961 ALOGI("Could not convert public exponent to BN");
1962 return ::SYSTEM_ERROR;
1963 }
1964 unsigned long pubExp = BN_get_word(pubExpBn.get());
1965 if (pubExp == 0xFFFFFFFFL) {
1966 ALOGI("cannot represent public exponent as a long value");
1967 return ::SYSTEM_ERROR;
1968 }
1969 rsa_params.public_exponent = pubExp;
1970 }
1971 }
1972
1973 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1974 } else {
1975 ALOGW("Unsupported key type %d", keyType);
1976 rc = -1;
1977 }
1978
Kenny Root07438c82012-11-02 15:41:02 -07001979 if (rc) {
1980 return ::SYSTEM_ERROR;
1981 }
1982
Kenny Root655b9582013-04-04 08:37:42 -07001983 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07001984 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001985
1986 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1987 free(data);
1988
Kenny Rootee8068b2013-10-07 09:49:15 -07001989 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001990 keyBlob.setFallback(isFallback);
1991
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001992 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001993 }
1994
Kenny Rootf9119d62013-04-03 09:22:15 -07001995 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1996 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001997 targetUid = getEffectiveUid(targetUid);
1998 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1999 flags & KEYSTORE_FLAG_ENCRYPTED);
2000 if (result != ::NO_ERROR) {
2001 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002002 }
Kenny Root07438c82012-11-02 15:41:02 -07002003 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002004 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002005
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002006 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2007 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002008 }
2009
Kenny Root07438c82012-11-02 15:41:02 -07002010 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2011 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002012 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002013 return ::PERMISSION_DENIED;
2014 }
Kenny Root07438c82012-11-02 15:41:02 -07002015
Chad Brubaker9489b792015-04-14 11:01:45 -07002016 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002017 Blob keyBlob;
2018 String8 name8(name);
2019
Kenny Rootd38a0b02013-02-13 12:59:14 -08002020 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002021
Kenny Root655b9582013-04-04 08:37:42 -07002022 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002023 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002024 if (responseCode != ::NO_ERROR) {
2025 return responseCode;
2026 }
2027
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002028 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002029 if (device == NULL) {
2030 ALOGE("no keymaster device; cannot sign");
2031 return ::SYSTEM_ERROR;
2032 }
2033
2034 if (device->sign_data == NULL) {
2035 ALOGE("device doesn't implement signing");
2036 return ::SYSTEM_ERROR;
2037 }
2038
2039 keymaster_rsa_sign_params_t params;
2040 params.digest_type = DIGEST_NONE;
2041 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002042 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002043 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002044 if (rc) {
2045 ALOGW("device couldn't sign data");
2046 return ::SYSTEM_ERROR;
2047 }
2048
2049 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002050 }
2051
Kenny Root07438c82012-11-02 15:41:02 -07002052 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2053 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002054 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002055 return ::PERMISSION_DENIED;
2056 }
Kenny Root70e3a862012-02-15 17:20:23 -08002057
Chad Brubaker9489b792015-04-14 11:01:45 -07002058 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002059 Blob keyBlob;
2060 String8 name8(name);
2061 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002062
Kenny Root655b9582013-04-04 08:37:42 -07002063 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002064 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002065 if (responseCode != ::NO_ERROR) {
2066 return responseCode;
2067 }
Kenny Root70e3a862012-02-15 17:20:23 -08002068
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002069 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002070 if (device == NULL) {
2071 return ::SYSTEM_ERROR;
2072 }
Kenny Root70e3a862012-02-15 17:20:23 -08002073
Kenny Root07438c82012-11-02 15:41:02 -07002074 if (device->verify_data == NULL) {
2075 return ::SYSTEM_ERROR;
2076 }
Kenny Root70e3a862012-02-15 17:20:23 -08002077
Kenny Root07438c82012-11-02 15:41:02 -07002078 keymaster_rsa_sign_params_t params;
2079 params.digest_type = DIGEST_NONE;
2080 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002081
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002082 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2083 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002084 if (rc) {
2085 return ::SYSTEM_ERROR;
2086 } else {
2087 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002088 }
2089 }
Kenny Root07438c82012-11-02 15:41:02 -07002090
2091 /*
2092 * TODO: The abstraction between things stored in hardware and regular blobs
2093 * of data stored on the filesystem should be moved down to keystore itself.
2094 * Unfortunately the Java code that calls this has naming conventions that it
2095 * knows about. Ideally keystore shouldn't be used to store random blobs of
2096 * data.
2097 *
2098 * Until that happens, it's necessary to have a separate "get_pubkey" and
2099 * "del_key" since the Java code doesn't really communicate what it's
2100 * intentions are.
2101 */
2102 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002103 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002104 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002105 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002106 return ::PERMISSION_DENIED;
2107 }
Kenny Root07438c82012-11-02 15:41:02 -07002108
Kenny Root07438c82012-11-02 15:41:02 -07002109 Blob keyBlob;
2110 String8 name8(name);
2111
Kenny Rootd38a0b02013-02-13 12:59:14 -08002112 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002113
Kenny Root655b9582013-04-04 08:37:42 -07002114 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002115 TYPE_KEY_PAIR);
2116 if (responseCode != ::NO_ERROR) {
2117 return responseCode;
2118 }
2119
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002120 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002121 if (device == NULL) {
2122 return ::SYSTEM_ERROR;
2123 }
2124
2125 if (device->get_keypair_public == NULL) {
2126 ALOGE("device has no get_keypair_public implementation!");
2127 return ::SYSTEM_ERROR;
2128 }
2129
Kenny Root17208e02013-09-04 13:56:03 -07002130 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002131 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2132 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002133 if (rc) {
2134 return ::SYSTEM_ERROR;
2135 }
2136
2137 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002138 }
Kenny Root07438c82012-11-02 15:41:02 -07002139
Kenny Root49468902013-03-19 13:41:33 -07002140 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002141 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002142 }
2143
2144 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002145 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002146 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2147 if (result != ::NO_ERROR) {
2148 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002149 }
2150
2151 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002152 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002153
Kenny Root655b9582013-04-04 08:37:42 -07002154 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002155 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2156 }
2157
Kenny Root655b9582013-04-04 08:37:42 -07002158 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002159 return ::NO_ERROR;
2160 }
2161
2162 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002163 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002164 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2165 if (result != ::NO_ERROR) {
2166 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002167 }
2168
2169 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002170 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002171
Kenny Root655b9582013-04-04 08:37:42 -07002172 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002173 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2174 }
2175
Kenny Root655b9582013-04-04 08:37:42 -07002176 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002177 }
2178
2179 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002180 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002181 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002182 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002183 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002184 }
Kenny Root07438c82012-11-02 15:41:02 -07002185
2186 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002187 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002188
Kenny Root655b9582013-04-04 08:37:42 -07002189 if (access(filename.string(), R_OK) == -1) {
2190 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002191 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002192 }
2193
Kenny Root655b9582013-04-04 08:37:42 -07002194 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002195 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002196 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002197 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002198 }
2199
2200 struct stat s;
2201 int ret = fstat(fd, &s);
2202 close(fd);
2203 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002204 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002205 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002206 }
2207
Kenny Root36a9e232013-02-04 14:24:15 -08002208 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002209 }
2210
Kenny Rootd53bc922013-03-21 14:10:15 -07002211 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2212 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002213 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002214 pid_t spid = IPCThreadState::self()->getCallingPid();
2215 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002216 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002217 return -1L;
2218 }
2219
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002220 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002221 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002222 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002223 return state;
2224 }
2225
Kenny Rootd53bc922013-03-21 14:10:15 -07002226 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2227 srcUid = callingUid;
2228 } else if (!is_granted_to(callingUid, srcUid)) {
2229 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002230 return ::PERMISSION_DENIED;
2231 }
2232
Kenny Rootd53bc922013-03-21 14:10:15 -07002233 if (destUid == -1) {
2234 destUid = callingUid;
2235 }
2236
2237 if (srcUid != destUid) {
2238 if (static_cast<uid_t>(srcUid) != callingUid) {
2239 ALOGD("can only duplicate from caller to other or to same uid: "
2240 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2241 return ::PERMISSION_DENIED;
2242 }
2243
2244 if (!is_granted_to(callingUid, destUid)) {
2245 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2246 return ::PERMISSION_DENIED;
2247 }
2248 }
2249
2250 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002251 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002252
Kenny Rootd53bc922013-03-21 14:10:15 -07002253 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002254 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002255
Kenny Root655b9582013-04-04 08:37:42 -07002256 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2257 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002258 return ::SYSTEM_ERROR;
2259 }
2260
Kenny Rootd53bc922013-03-21 14:10:15 -07002261 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002262 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002263 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002264 if (responseCode != ::NO_ERROR) {
2265 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002266 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002267
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002268 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002269 }
2270
Kenny Root1b0e3932013-09-05 13:06:32 -07002271 int32_t is_hardware_backed(const String16& keyType) {
2272 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002273 }
2274
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002275 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002276 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubaker01771ae2015-05-01 10:21:27 -07002277 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002278 return ::PERMISSION_DENIED;
2279 }
2280
Robin Lee4b84fdc2014-09-24 11:56:57 +01002281 String8 prefix = String8::format("%u_", targetUid);
2282 Vector<String16> aliases;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002283 if (mKeyStore->saw(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002284 return ::SYSTEM_ERROR;
2285 }
2286
Robin Lee4b84fdc2014-09-24 11:56:57 +01002287 for (uint32_t i = 0; i < aliases.size(); i++) {
2288 String8 name8(aliases[i]);
2289 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002290 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002291 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002292 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002293 }
2294
Robin Lee4b84fdc2014-09-24 11:56:57 +01002295 int32_t reset_uid(int32_t targetUid) {
Chad Brubakereecdd122015-05-07 10:19:40 -07002296 // TODO: Remove this method from the binder interface
Chad Brubaker9489b792015-04-14 11:01:45 -07002297 targetUid = getEffectiveUid(targetUid);
Chad Brubakereecdd122015-05-07 10:19:40 -07002298 return onUserPasswordChanged(get_user_id(targetUid), String16(""));
Robin Lee4e865752014-08-19 17:37:55 +01002299 }
2300
2301 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002302 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002303 return ::PERMISSION_DENIED;
2304 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002305 uid_t sourceUser = get_user_id(sourceUid);
2306 uid_t targetUser = get_user_id(targetUid);
Chad Brubaker9489b792015-04-14 11:01:45 -07002307
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002308 if (sourceUser == targetUser) {
Robin Lee4e865752014-08-19 17:37:55 +01002309 return ::SYSTEM_ERROR;
2310 }
2311
2312 // Initialise user keystore with existing master key held in-memory
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002313 return mKeyStore->copyMasterKey(sourceUser, targetUser);
Robin Lee4e865752014-08-19 17:37:55 +01002314 }
2315
2316 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002317 targetUid = getEffectiveUid(targetUid);
2318 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002319 return ::PERMISSION_DENIED;
2320 }
Robin Lee4e865752014-08-19 17:37:55 +01002321 const String8 password8(pw);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002322 uid_t userId = get_user_id(targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002323
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002324 switch (mKeyStore->getState(userId)) {
Robin Lee4e865752014-08-19 17:37:55 +01002325 case ::STATE_UNINITIALIZED: {
2326 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002327 return mKeyStore->initializeUser(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002328 }
2329 case ::STATE_NO_ERROR: {
2330 // rewrite master key with new password.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002331 return mKeyStore->writeMasterKey(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002332 }
2333 case ::STATE_LOCKED: {
2334 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002335 return mKeyStore->readMasterKey(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002336 }
2337 }
2338 return ::SYSTEM_ERROR;
2339 }
2340
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002341 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2342 const keymaster1_device_t* device = mKeyStore->getDevice();
2343 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2344 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2345 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2346 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2347 device->add_rng_entropy != NULL) {
2348 devResult = device->add_rng_entropy(device, data, dataLength);
2349 }
2350 if (fallback->add_rng_entropy) {
2351 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2352 }
2353 if (devResult) {
2354 return devResult;
2355 }
2356 if (fallbackResult) {
2357 return fallbackResult;
2358 }
2359 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002360 }
2361
Chad Brubaker17d68b92015-02-05 22:04:16 -08002362 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002363 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2364 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002365 uid = getEffectiveUid(uid);
2366 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2367 flags & KEYSTORE_FLAG_ENCRYPTED);
2368 if (rc != ::NO_ERROR) {
2369 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002370 }
2371
Chad Brubaker9489b792015-04-14 11:01:45 -07002372 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002373 bool isFallback = false;
2374 keymaster_key_blob_t blob;
2375 keymaster_key_characteristics_t *out = NULL;
2376
2377 const keymaster1_device_t* device = mKeyStore->getDevice();
2378 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2379 if (device == NULL) {
2380 return ::SYSTEM_ERROR;
2381 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002382 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002383 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2384 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002385 if (!entropy) {
2386 rc = KM_ERROR_OK;
2387 } else if (device->add_rng_entropy) {
2388 rc = device->add_rng_entropy(device, entropy, entropyLength);
2389 } else {
2390 rc = KM_ERROR_UNIMPLEMENTED;
2391 }
2392 if (rc == KM_ERROR_OK) {
2393 rc = device->generate_key(device, params.params.data(), params.params.size(),
2394 &blob, &out);
2395 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002396 }
2397 // If the HW device didn't support generate_key or generate_key failed
2398 // fall back to the software implementation.
2399 if (rc && fallback->generate_key != NULL) {
2400 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002401 if (!entropy) {
2402 rc = KM_ERROR_OK;
2403 } else if (fallback->add_rng_entropy) {
2404 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2405 } else {
2406 rc = KM_ERROR_UNIMPLEMENTED;
2407 }
2408 if (rc == KM_ERROR_OK) {
2409 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2410 &blob,
2411 &out);
2412 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002413 }
2414
2415 if (out) {
2416 if (outCharacteristics) {
2417 outCharacteristics->characteristics = *out;
2418 } else {
2419 keymaster_free_characteristics(out);
2420 }
2421 free(out);
2422 }
2423
2424 if (rc) {
2425 return rc;
2426 }
2427
2428 String8 name8(name);
2429 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2430
2431 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2432 keyBlob.setFallback(isFallback);
2433 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2434
2435 free(const_cast<uint8_t*>(blob.key_material));
2436
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002437 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002438 }
2439
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002440 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002441 const keymaster_blob_t* clientId,
2442 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002443 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002444 if (!outCharacteristics) {
2445 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2446 }
2447
2448 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2449
2450 Blob keyBlob;
2451 String8 name8(name);
2452 int rc;
2453
2454 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2455 TYPE_KEYMASTER_10);
2456 if (responseCode != ::NO_ERROR) {
2457 return responseCode;
2458 }
2459 keymaster_key_blob_t key;
2460 key.key_material_size = keyBlob.getLength();
2461 key.key_material = keyBlob.getValue();
2462 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2463 keymaster_key_characteristics_t *out = NULL;
2464 if (!dev->get_key_characteristics) {
2465 ALOGW("device does not implement get_key_characteristics");
2466 return KM_ERROR_UNIMPLEMENTED;
2467 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002468 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002469 if (out) {
2470 outCharacteristics->characteristics = *out;
2471 free(out);
2472 }
2473 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002474 }
2475
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002476 int32_t importKey(const String16& name, const KeymasterArguments& params,
2477 keymaster_key_format_t format, const uint8_t *keyData,
2478 size_t keyLength, int uid, int flags,
2479 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002480 uid = getEffectiveUid(uid);
2481 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2482 flags & KEYSTORE_FLAG_ENCRYPTED);
2483 if (rc != ::NO_ERROR) {
2484 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002485 }
2486
Chad Brubaker9489b792015-04-14 11:01:45 -07002487 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002488 bool isFallback = false;
2489 keymaster_key_blob_t blob;
2490 keymaster_key_characteristics_t *out = NULL;
2491
2492 const keymaster1_device_t* device = mKeyStore->getDevice();
2493 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2494 if (device == NULL) {
2495 return ::SYSTEM_ERROR;
2496 }
2497 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2498 device->import_key != NULL) {
2499 rc = device->import_key(device, params.params.data(), params.params.size(),
2500 format, keyData, keyLength, &blob, &out);
2501 }
2502 if (rc && fallback->import_key != NULL) {
2503 isFallback = true;
2504 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2505 format, keyData, keyLength, &blob, &out);
2506 }
2507 if (out) {
2508 if (outCharacteristics) {
2509 outCharacteristics->characteristics = *out;
2510 } else {
2511 keymaster_free_characteristics(out);
2512 }
2513 free(out);
2514 }
2515 if (rc) {
2516 return rc;
2517 }
2518
2519 String8 name8(name);
2520 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2521
2522 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2523 keyBlob.setFallback(isFallback);
2524 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2525
2526 free((void*) blob.key_material);
2527
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002528 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002529 }
2530
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002531 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002532 const keymaster_blob_t* clientId,
2533 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002534
2535 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2536
2537 Blob keyBlob;
2538 String8 name8(name);
2539 int rc;
2540
2541 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2542 TYPE_KEYMASTER_10);
2543 if (responseCode != ::NO_ERROR) {
2544 result->resultCode = responseCode;
2545 return;
2546 }
2547 keymaster_key_blob_t key;
2548 key.key_material_size = keyBlob.getLength();
2549 key.key_material = keyBlob.getValue();
2550 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2551 if (!dev->export_key) {
2552 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2553 return;
2554 }
2555 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002556 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002557 &ptr, &result->dataLength);
2558 result->exportData.reset(ptr);
2559 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002560 }
2561
Chad Brubakerad6514a2015-04-09 14:00:26 -07002562
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002563 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002564 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2565 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002566 if (!result || !outParams) {
2567 ALOGE("Unexpected null arguments to begin()");
2568 return;
2569 }
2570 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2571 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2572 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2573 result->resultCode = ::PERMISSION_DENIED;
2574 return;
2575 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002576 if (!checkAllowedOperationParams(params.params)) {
2577 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2578 return;
2579 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002580 Blob keyBlob;
2581 String8 name8(name);
2582 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2583 TYPE_KEYMASTER_10);
2584 if (responseCode != ::NO_ERROR) {
2585 result->resultCode = responseCode;
2586 return;
2587 }
2588 keymaster_key_blob_t key;
2589 key.key_material_size = keyBlob.getLength();
2590 key.key_material = keyBlob.getValue();
2591 keymaster_key_param_t* out;
2592 size_t outSize;
2593 keymaster_operation_handle_t handle;
2594 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002595 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002596 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002597 Unique_keymaster_key_characteristics characteristics;
2598 characteristics.reset(new keymaster_key_characteristics_t);
2599 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2600 if (err) {
2601 result->resultCode = err;
2602 return;
2603 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002604 const hw_auth_token_t* authToken = NULL;
2605 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002606 /*failOnTokenMissing*/ false);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002607 // If per-operation auth is needed we need to begin the operation and
2608 // the client will need to authorize that operation before calling
2609 // update. Any other auth issues stop here.
2610 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2611 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002612 return;
2613 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002614 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002615 // Add entropy to the device first.
2616 if (entropy) {
2617 if (dev->add_rng_entropy) {
2618 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2619 } else {
2620 err = KM_ERROR_UNIMPLEMENTED;
2621 }
2622 if (err) {
2623 result->resultCode = err;
2624 return;
2625 }
2626 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002627 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2628 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002629
2630 // If there are too many operations abort the oldest operation that was
2631 // started as pruneable and try again.
2632 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2633 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2634 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2635 if (abort(oldest) != ::NO_ERROR) {
2636 break;
2637 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002638 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002639 &handle);
2640 }
2641 if (err) {
2642 result->resultCode = err;
2643 return;
2644 }
2645 if (out) {
2646 outParams->params.assign(out, out + outSize);
2647 free(out);
2648 }
2649
Chad Brubakerad6514a2015-04-09 14:00:26 -07002650 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2651 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002652 pruneable);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002653 if (authToken) {
2654 mOperationMap.setOperationAuthToken(operationToken, authToken);
2655 }
2656 // Return the authentication lookup result. If this is a per operation
2657 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2658 // application should get an auth token using the handle before the
2659 // first call to update, which will fail if keystore hasn't received the
2660 // auth token.
2661 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002662 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002663 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002664 }
2665
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002666 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2667 size_t dataLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002668 if (!checkAllowedOperationParams(params.params)) {
2669 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2670 return;
2671 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002672 const keymaster1_device_t* dev;
2673 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002674 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002675 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2676 return;
2677 }
2678 uint8_t* output_buf = NULL;
2679 size_t output_length = 0;
2680 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002681 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002682 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2683 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002684 result->resultCode = authResult;
2685 return;
2686 }
2687 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2688 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002689 result->data.reset(output_buf);
2690 result->dataLength = output_length;
2691 result->inputConsumed = consumed;
2692 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002693 }
2694
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002695 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2696 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002697 if (!checkAllowedOperationParams(params.params)) {
2698 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2699 return;
2700 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002701 const keymaster1_device_t* dev;
2702 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002703 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002704 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2705 return;
2706 }
2707 uint8_t* output_buf = NULL;
2708 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002709 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002710 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2711 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002712 result->resultCode = authResult;
2713 return;
2714 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002715
Chad Brubaker06801e02015-03-31 15:13:13 -07002716 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2717 signature, signatureLength, &output_buf,
2718 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002719 // Remove the operation regardless of the result
2720 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002721 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002722 result->data.reset(output_buf);
2723 result->dataLength = output_length;
2724 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002725 }
2726
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002727 int32_t abort(const sp<IBinder>& token) {
2728 const keymaster1_device_t* dev;
2729 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002730 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002731 return KM_ERROR_INVALID_OPERATION_HANDLE;
2732 }
2733 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002734 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002735 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002736 rc = KM_ERROR_UNIMPLEMENTED;
2737 } else {
2738 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002739 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002740 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002741 if (rc) {
2742 return rc;
2743 }
2744 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002745 }
2746
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002747 bool isOperationAuthorized(const sp<IBinder>& token) {
2748 const keymaster1_device_t* dev;
2749 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002750 const keymaster_key_characteristics_t* characteristics;
2751 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002752 return false;
2753 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002754 const hw_auth_token_t* authToken = NULL;
2755 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002756 std::vector<keymaster_key_param_t> ignored;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002757 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2758 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002759 }
2760
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002761 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002762 if (!checkBinderPermission(P_ADD_AUTH)) {
2763 ALOGW("addAuthToken: permission denied for %d",
2764 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002765 return ::PERMISSION_DENIED;
2766 }
2767 if (length != sizeof(hw_auth_token_t)) {
2768 return KM_ERROR_INVALID_ARGUMENT;
2769 }
2770 hw_auth_token_t* authToken = new hw_auth_token_t;
2771 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2772 // The table takes ownership of authToken.
2773 mAuthTokenTable.AddAuthenticationToken(authToken);
2774 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002775 }
2776
Kenny Root07438c82012-11-02 15:41:02 -07002777private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002778 static const int32_t UID_SELF = -1;
2779
2780 /**
2781 * Get the effective target uid for a binder operation that takes an
2782 * optional uid as the target.
2783 */
2784 inline uid_t getEffectiveUid(int32_t targetUid) {
2785 if (targetUid == UID_SELF) {
2786 return IPCThreadState::self()->getCallingUid();
2787 }
2788 return static_cast<uid_t>(targetUid);
2789 }
2790
2791 /**
2792 * Check if the caller of the current binder method has the required
2793 * permission and if acting on other uids the grants to do so.
2794 */
2795 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2796 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2797 pid_t spid = IPCThreadState::self()->getCallingPid();
2798 if (!has_permission(callingUid, permission, spid)) {
2799 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2800 return false;
2801 }
2802 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2803 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2804 return false;
2805 }
2806 return true;
2807 }
2808
2809 /**
2810 * Check if the caller of the current binder method has the required
Chad Brubaker01771ae2015-05-01 10:21:27 -07002811 * permission and the target uid is the caller or the caller is system.
2812 */
2813 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2814 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2815 pid_t spid = IPCThreadState::self()->getCallingPid();
2816 if (!has_permission(callingUid, permission, spid)) {
2817 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2818 return false;
2819 }
2820 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2821 }
2822
2823 /**
2824 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002825 * permission or the target of the operation is the caller's uid. This is
2826 * for operation where the permission is only for cross-uid activity and all
2827 * uids are allowed to act on their own (ie: clearing all entries for a
2828 * given uid).
2829 */
2830 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2831 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2832 if (getEffectiveUid(targetUid) == callingUid) {
2833 return true;
2834 } else {
2835 return checkBinderPermission(permission, targetUid);
2836 }
2837 }
2838
2839 /**
2840 * Helper method to check that the caller has the required permission as
2841 * well as the keystore is in the unlocked state if checkUnlocked is true.
2842 *
2843 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2844 * otherwise the state of keystore when not unlocked and checkUnlocked is
2845 * true.
2846 */
2847 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2848 bool checkUnlocked = true) {
2849 if (!checkBinderPermission(permission, targetUid)) {
2850 return ::PERMISSION_DENIED;
2851 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002852 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002853 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2854 return state;
2855 }
2856
2857 return ::NO_ERROR;
2858
2859 }
2860
Kenny Root9d45d1c2013-02-14 10:32:30 -08002861 inline bool isKeystoreUnlocked(State state) {
2862 switch (state) {
2863 case ::STATE_NO_ERROR:
2864 return true;
2865 case ::STATE_UNINITIALIZED:
2866 case ::STATE_LOCKED:
2867 return false;
2868 }
2869 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002870 }
2871
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002872 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002873 const int32_t device_api = device->common.module->module_api_version;
2874 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2875 switch (keyType) {
2876 case TYPE_RSA:
2877 case TYPE_DSA:
2878 case TYPE_EC:
2879 return true;
2880 default:
2881 return false;
2882 }
2883 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2884 switch (keyType) {
2885 case TYPE_RSA:
2886 return true;
2887 case TYPE_DSA:
2888 return device->flags & KEYMASTER_SUPPORTS_DSA;
2889 case TYPE_EC:
2890 return device->flags & KEYMASTER_SUPPORTS_EC;
2891 default:
2892 return false;
2893 }
2894 } else {
2895 return keyType == TYPE_RSA;
2896 }
2897 }
2898
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002899 /**
2900 * Check that all keymaster_key_param_t's provided by the application are
2901 * allowed. Any parameter that keystore adds itself should be disallowed here.
2902 */
2903 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2904 for (auto param: params) {
2905 switch (param.tag) {
2906 case KM_TAG_AUTH_TOKEN:
2907 return false;
2908 default:
2909 break;
2910 }
2911 }
2912 return true;
2913 }
2914
2915 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2916 const keymaster1_device_t* dev,
2917 const std::vector<keymaster_key_param_t>& params,
2918 keymaster_key_characteristics_t* out) {
2919 UniquePtr<keymaster_blob_t> appId;
2920 UniquePtr<keymaster_blob_t> appData;
2921 for (auto param : params) {
2922 if (param.tag == KM_TAG_APPLICATION_ID) {
2923 appId.reset(new keymaster_blob_t);
2924 appId->data = param.blob.data;
2925 appId->data_length = param.blob.data_length;
2926 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2927 appData.reset(new keymaster_blob_t);
2928 appData->data = param.blob.data;
2929 appData->data_length = param.blob.data_length;
2930 }
2931 }
2932 keymaster_key_characteristics_t* result = NULL;
2933 if (!dev->get_key_characteristics) {
2934 return KM_ERROR_UNIMPLEMENTED;
2935 }
2936 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2937 appData.get(), &result);
2938 if (result) {
2939 *out = *result;
2940 free(result);
2941 }
2942 return error;
2943 }
2944
2945 /**
2946 * Get the auth token for this operation from the auth token table.
2947 *
2948 * Returns ::NO_ERROR if the auth token was set or none was required.
2949 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2950 * authorization token exists for that operation and
2951 * failOnTokenMissing is false.
2952 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2953 * token for the operation
2954 */
2955 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2956 keymaster_operation_handle_t handle,
2957 const hw_auth_token_t** authToken,
2958 bool failOnTokenMissing = true) {
2959
2960 std::vector<keymaster_key_param_t> allCharacteristics;
2961 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2962 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2963 }
2964 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2965 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2966 }
2967 keymaster::AuthTokenTable::Error err =
2968 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2969 allCharacteristics.size(), handle, authToken);
2970 switch (err) {
2971 case keymaster::AuthTokenTable::OK:
2972 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2973 return ::NO_ERROR;
2974 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2975 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2976 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2977 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2978 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2979 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2980 (int32_t) ::OP_AUTH_NEEDED;
2981 default:
2982 ALOGE("Unexpected FindAuthorization return value %d", err);
2983 return KM_ERROR_INVALID_ARGUMENT;
2984 }
2985 }
2986
2987 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2988 const hw_auth_token_t* token) {
2989 if (token) {
2990 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2991 reinterpret_cast<const uint8_t*>(token),
2992 sizeof(hw_auth_token_t)));
2993 }
2994 }
2995
2996 /**
2997 * Add the auth token for the operation to the param list if the operation
2998 * requires authorization. Uses the cached result in the OperationMap if available
2999 * otherwise gets the token from the AuthTokenTable and caches the result.
3000 *
3001 * Returns ::NO_ERROR if the auth token was added or not needed.
3002 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3003 * authenticated.
3004 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3005 * operation token.
3006 */
3007 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3008 std::vector<keymaster_key_param_t>* params) {
3009 const hw_auth_token_t* authToken = NULL;
Chad Brubaker6b541162015-04-29 19:58:34 -07003010 mOperationMap.getOperationAuthToken(token, &authToken);
3011 if (!authToken) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07003012 const keymaster1_device_t* dev;
3013 keymaster_operation_handle_t handle;
3014 const keymaster_key_characteristics_t* characteristics = NULL;
3015 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3016 return KM_ERROR_INVALID_OPERATION_HANDLE;
3017 }
3018 int32_t result = getAuthToken(characteristics, handle, &authToken);
3019 if (result != ::NO_ERROR) {
3020 return result;
3021 }
3022 if (authToken) {
3023 mOperationMap.setOperationAuthToken(token, authToken);
3024 }
3025 }
3026 addAuthToParams(params, authToken);
3027 return ::NO_ERROR;
3028 }
3029
Kenny Root07438c82012-11-02 15:41:02 -07003030 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003031 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003032 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003033};
3034
3035}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003036
3037int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003038 if (argc < 2) {
3039 ALOGE("A directory must be specified!");
3040 return 1;
3041 }
3042 if (chdir(argv[1]) == -1) {
3043 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3044 return 1;
3045 }
3046
3047 Entropy entropy;
3048 if (!entropy.open()) {
3049 return 1;
3050 }
Kenny Root70e3a862012-02-15 17:20:23 -08003051
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07003052 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003053 if (keymaster_device_initialize(&dev)) {
3054 ALOGE("keystore keymaster could not be initialized; exiting");
3055 return 1;
3056 }
3057
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003058 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003059 if (fallback_keymaster_device_initialize(&fallback)) {
3060 ALOGE("software keymaster could not be initialized; exiting");
3061 return 1;
3062 }
3063
Riley Spahneaabae92014-06-30 12:39:52 -07003064 ks_is_selinux_enabled = is_selinux_enabled();
3065 if (ks_is_selinux_enabled) {
3066 union selinux_callback cb;
3067 cb.func_log = selinux_log_callback;
3068 selinux_set_callback(SELINUX_CB_LOG, cb);
3069 if (getcon(&tctx) != 0) {
3070 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3071 return -1;
3072 }
3073 } else {
3074 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3075 }
3076
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003077 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003078 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003079 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3080 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3081 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3082 if (ret != android::OK) {
3083 ALOGE("Couldn't register binder service!");
3084 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003085 }
Kenny Root07438c82012-11-02 15:41:02 -07003086
3087 /*
3088 * We're the only thread in existence, so we're just going to process
3089 * Binder transaction as a single-threaded program.
3090 */
3091 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003092
3093 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003094 return 1;
3095}