blob: c321c450500b3dea7871981797895c8d0eb21b1f [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Shawn Willden80843db2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willden80843db2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Shawn Willden04006752015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker67d2a502015-03-11 17:21:18 +0000137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willden80843db2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100155 P_TEST = 1 << 0,
156 P_GET = 1 << 1,
157 P_INSERT = 1 << 2,
158 P_DELETE = 1 << 3,
159 P_EXIST = 1 << 4,
160 P_SAW = 1 << 5,
161 P_RESET = 1 << 6,
162 P_PASSWORD = 1 << 7,
163 P_LOCK = 1 << 8,
164 P_UNLOCK = 1 << 9,
165 P_ZERO = 1 << 10,
166 P_SIGN = 1 << 11,
167 P_VERIFY = 1 << 12,
168 P_GRANT = 1 << 13,
169 P_DUPLICATE = 1 << 14,
170 P_CLEAR_UID = 1 << 15,
171 P_RESET_UID = 1 << 16,
172 P_SYNC_UID = 1 << 17,
173 P_PASSWORD_UID = 1 << 18,
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700174 P_ADD_AUTH = 1 << 19,
Kenny Root07438c82012-11-02 15:41:02 -0700175} perm_t;
176
177static struct user_euid {
178 uid_t uid;
179 uid_t euid;
180} user_euids[] = {
181 {AID_VPN, AID_SYSTEM},
182 {AID_WIFI, AID_SYSTEM},
183 {AID_ROOT, AID_SYSTEM},
184};
185
Riley Spahneaabae92014-06-30 12:39:52 -0700186/* perm_labels associcated with keystore_key SELinux class verbs. */
187const char *perm_labels[] = {
188 "test",
189 "get",
190 "insert",
191 "delete",
192 "exist",
193 "saw",
194 "reset",
195 "password",
196 "lock",
197 "unlock",
198 "zero",
199 "sign",
200 "verify",
201 "grant",
202 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100203 "clear_uid",
204 "reset_uid",
205 "sync_uid",
206 "password_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700207 "add_auth",
Riley Spahneaabae92014-06-30 12:39:52 -0700208};
209
Kenny Root07438c82012-11-02 15:41:02 -0700210static struct user_perm {
211 uid_t uid;
212 perm_t perms;
213} user_perms[] = {
214 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
215 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
216 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
217 {AID_ROOT, static_cast<perm_t>(P_GET) },
218};
219
220static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
221 | P_VERIFY);
222
Riley Spahneaabae92014-06-30 12:39:52 -0700223static char *tctx;
224static int ks_is_selinux_enabled;
225
226static const char *get_perm_label(perm_t perm) {
227 unsigned int index = ffs(perm);
228 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
229 return perm_labels[index - 1];
230 } else {
231 ALOGE("Keystore: Failed to retrieve permission label.\n");
232 abort();
233 }
234}
235
Kenny Root655b9582013-04-04 08:37:42 -0700236/**
237 * Returns the app ID (in the Android multi-user sense) for the current
238 * UNIX UID.
239 */
240static uid_t get_app_id(uid_t uid) {
241 return uid % AID_USER;
242}
243
244/**
245 * Returns the user ID (in the Android multi-user sense) for the current
246 * UNIX UID.
247 */
248static uid_t get_user_id(uid_t uid) {
249 return uid / AID_USER;
250}
251
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700252static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700253 if (!ks_is_selinux_enabled) {
254 return true;
255 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000256
Riley Spahneaabae92014-06-30 12:39:52 -0700257 char *sctx = NULL;
258 const char *selinux_class = "keystore_key";
259 const char *str_perm = get_perm_label(perm);
260
261 if (!str_perm) {
262 return false;
263 }
264
265 if (getpidcon(spid, &sctx) != 0) {
266 ALOGE("SELinux: Failed to get source pid context.\n");
267 return false;
268 }
269
270 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
271 NULL) == 0;
272 freecon(sctx);
273 return allowed;
274}
275
276static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700277 // All system users are equivalent for multi-user support.
278 if (get_app_id(uid) == AID_SYSTEM) {
279 uid = AID_SYSTEM;
280 }
281
Kenny Root07438c82012-11-02 15:41:02 -0700282 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
283 struct user_perm user = user_perms[i];
284 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700285 return (user.perms & perm) &&
286 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700287 }
288 }
289
Riley Spahneaabae92014-06-30 12:39:52 -0700290 return (DEFAULT_PERMS & perm) &&
291 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700292}
293
Kenny Root49468902013-03-19 13:41:33 -0700294/**
295 * Returns the UID that the callingUid should act as. This is here for
296 * legacy support of the WiFi and VPN systems and should be removed
297 * when WiFi can operate in its own namespace.
298 */
Kenny Root07438c82012-11-02 15:41:02 -0700299static uid_t get_keystore_euid(uid_t uid) {
300 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
301 struct user_euid user = user_euids[i];
302 if (user.uid == uid) {
303 return user.euid;
304 }
305 }
306
307 return uid;
308}
309
Kenny Root49468902013-03-19 13:41:33 -0700310/**
311 * Returns true if the callingUid is allowed to interact in the targetUid's
312 * namespace.
313 */
314static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700315 if (callingUid == targetUid) {
316 return true;
317 }
Kenny Root49468902013-03-19 13:41:33 -0700318 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
319 struct user_euid user = user_euids[i];
320 if (user.euid == callingUid && user.uid == targetUid) {
321 return true;
322 }
323 }
324
325 return false;
326}
327
Kenny Roota91203b2012-02-15 15:00:46 -0800328/* Here is the encoding of keys. This is necessary in order to allow arbitrary
329 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
330 * into two bytes. The first byte is one of [+-.] which represents the first
331 * two bits of the character. The second byte encodes the rest of the bits into
332 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
333 * that Base64 cannot be used here due to the need of prefix match on keys. */
334
Kenny Root655b9582013-04-04 08:37:42 -0700335static size_t encode_key_length(const android::String8& keyName) {
336 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
337 size_t length = keyName.length();
338 for (int i = length; i > 0; --i, ++in) {
339 if (*in < '0' || *in > '~') {
340 ++length;
341 }
342 }
343 return length;
344}
345
Kenny Root07438c82012-11-02 15:41:02 -0700346static int encode_key(char* out, const android::String8& keyName) {
347 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
348 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800349 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700350 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800351 *out = '+' + (*in >> 6);
352 *++out = '0' + (*in & 0x3F);
353 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700354 } else {
355 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800356 }
357 }
358 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800359 return length;
360}
361
Kenny Root07438c82012-11-02 15:41:02 -0700362/*
363 * Converts from the "escaped" format on disk to actual name.
364 * This will be smaller than the input string.
365 *
366 * Characters that should combine with the next at the end will be truncated.
367 */
368static size_t decode_key_length(const char* in, size_t length) {
369 size_t outLength = 0;
370
371 for (const char* end = in + length; in < end; in++) {
372 /* This combines with the next character. */
373 if (*in < '0' || *in > '~') {
374 continue;
375 }
376
377 outLength++;
378 }
379 return outLength;
380}
381
382static void decode_key(char* out, const char* in, size_t length) {
383 for (const char* end = in + length; in < end; in++) {
384 if (*in < '0' || *in > '~') {
385 /* Truncate combining characters at the end. */
386 if (in + 1 >= end) {
387 break;
388 }
389
390 *out = (*in++ - '+') << 6;
391 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800392 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700393 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800394 }
395 }
396 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800397}
398
399static size_t readFully(int fd, uint8_t* data, size_t size) {
400 size_t remaining = size;
401 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800402 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800403 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800404 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800405 }
406 data += n;
407 remaining -= n;
408 }
409 return size;
410}
411
412static size_t writeFully(int fd, uint8_t* data, size_t size) {
413 size_t remaining = size;
414 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800415 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
416 if (n < 0) {
417 ALOGW("write failed: %s", strerror(errno));
418 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800419 }
420 data += n;
421 remaining -= n;
422 }
423 return size;
424}
425
426class Entropy {
427public:
428 Entropy() : mRandom(-1) {}
429 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800430 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800431 close(mRandom);
432 }
433 }
434
435 bool open() {
436 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800437 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
438 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800439 ALOGE("open: %s: %s", randomDevice, strerror(errno));
440 return false;
441 }
442 return true;
443 }
444
Kenny Root51878182012-03-13 12:53:19 -0700445 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800446 return (readFully(mRandom, data, size) == size);
447 }
448
449private:
450 int mRandom;
451};
452
453/* Here is the file format. There are two parts in blob.value, the secret and
454 * the description. The secret is stored in ciphertext, and its original size
455 * can be found in blob.length. The description is stored after the secret in
456 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700457 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700458 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800459 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
460 * and decryptBlob(). Thus they should not be accessed from outside. */
461
Kenny Root822c3a92012-03-23 16:34:39 -0700462/* ** Note to future implementors of encryption: **
463 * Currently this is the construction:
464 * metadata || Enc(MD5(data) || data)
465 *
466 * This should be the construction used for encrypting if re-implementing:
467 *
468 * Derive independent keys for encryption and MAC:
469 * Kenc = AES_encrypt(masterKey, "Encrypt")
470 * Kmac = AES_encrypt(masterKey, "MAC")
471 *
472 * Store this:
473 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
474 * HMAC(Kmac, metadata || Enc(data))
475 */
Kenny Roota91203b2012-02-15 15:00:46 -0800476struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700477 uint8_t version;
478 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700479 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800480 uint8_t info;
481 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700482 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800483 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700484 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800485 int32_t length; // in network byte order when encrypted
486 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
487};
488
Kenny Root822c3a92012-03-23 16:34:39 -0700489typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700490 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700491 TYPE_GENERIC = 1,
492 TYPE_MASTER_KEY = 2,
493 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800494 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700495} BlobType;
496
Kenny Rootf9119d62013-04-03 09:22:15 -0700497static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700498
Kenny Roota91203b2012-02-15 15:00:46 -0800499class Blob {
500public:
Kenny Root07438c82012-11-02 15:41:02 -0700501 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
502 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800503 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800504 mBlob.length = valueLength;
505 memcpy(mBlob.value, value, valueLength);
506
507 mBlob.info = infoLength;
508 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700509
Kenny Root07438c82012-11-02 15:41:02 -0700510 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700511 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700512
Kenny Rootee8068b2013-10-07 09:49:15 -0700513 if (type == TYPE_MASTER_KEY) {
514 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
515 } else {
516 mBlob.flags = KEYSTORE_FLAG_NONE;
517 }
Kenny Roota91203b2012-02-15 15:00:46 -0800518 }
519
520 Blob(blob b) {
521 mBlob = b;
522 }
523
Alex Klyubin1773b442015-02-20 12:33:33 -0800524 Blob() {
525 memset(&mBlob, 0, sizeof(mBlob));
526 }
Kenny Roota91203b2012-02-15 15:00:46 -0800527
Kenny Root51878182012-03-13 12:53:19 -0700528 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800529 return mBlob.value;
530 }
531
Kenny Root51878182012-03-13 12:53:19 -0700532 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.length;
534 }
535
Kenny Root51878182012-03-13 12:53:19 -0700536 const uint8_t* getInfo() const {
537 return mBlob.value + mBlob.length;
538 }
539
540 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800541 return mBlob.info;
542 }
543
Kenny Root822c3a92012-03-23 16:34:39 -0700544 uint8_t getVersion() const {
545 return mBlob.version;
546 }
547
Kenny Rootf9119d62013-04-03 09:22:15 -0700548 bool isEncrypted() const {
549 if (mBlob.version < 2) {
550 return true;
551 }
552
553 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
554 }
555
556 void setEncrypted(bool encrypted) {
557 if (encrypted) {
558 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
559 } else {
560 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
561 }
562 }
563
Kenny Root17208e02013-09-04 13:56:03 -0700564 bool isFallback() const {
565 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
566 }
567
568 void setFallback(bool fallback) {
569 if (fallback) {
570 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
571 } else {
572 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
573 }
574 }
575
Kenny Root822c3a92012-03-23 16:34:39 -0700576 void setVersion(uint8_t version) {
577 mBlob.version = version;
578 }
579
580 BlobType getType() const {
581 return BlobType(mBlob.type);
582 }
583
584 void setType(BlobType type) {
585 mBlob.type = uint8_t(type);
586 }
587
Kenny Rootf9119d62013-04-03 09:22:15 -0700588 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
589 ALOGV("writing blob %s", filename);
590 if (isEncrypted()) {
591 if (state != STATE_NO_ERROR) {
592 ALOGD("couldn't insert encrypted blob while not unlocked");
593 return LOCKED;
594 }
595
596 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
597 ALOGW("Could not read random data for: %s", filename);
598 return SYSTEM_ERROR;
599 }
Kenny Roota91203b2012-02-15 15:00:46 -0800600 }
601
602 // data includes the value and the value's length
603 size_t dataLength = mBlob.length + sizeof(mBlob.length);
604 // pad data to the AES_BLOCK_SIZE
605 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
606 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
607 // encrypted data includes the digest value
608 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
609 // move info after space for padding
610 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
611 // zero padding area
612 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
613
614 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800615
Kenny Rootf9119d62013-04-03 09:22:15 -0700616 if (isEncrypted()) {
617 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800618
Kenny Rootf9119d62013-04-03 09:22:15 -0700619 uint8_t vector[AES_BLOCK_SIZE];
620 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
621 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
622 aes_key, vector, AES_ENCRYPT);
623 }
624
Kenny Roota91203b2012-02-15 15:00:46 -0800625 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
626 size_t fileLength = encryptedLength + headerLength + mBlob.info;
627
628 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800629 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
630 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
631 if (out < 0) {
632 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800633 return SYSTEM_ERROR;
634 }
635 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
636 if (close(out) != 0) {
637 return SYSTEM_ERROR;
638 }
639 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800640 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800641 unlink(tmpFileName);
642 return SYSTEM_ERROR;
643 }
Kenny Root150ca932012-11-14 14:29:02 -0800644 if (rename(tmpFileName, filename) == -1) {
645 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
646 return SYSTEM_ERROR;
647 }
648 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800649 }
650
Kenny Rootf9119d62013-04-03 09:22:15 -0700651 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
652 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800653 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
654 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800655 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
656 }
657 // fileLength may be less than sizeof(mBlob) since the in
658 // memory version has extra padding to tolerate rounding up to
659 // the AES_BLOCK_SIZE
660 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
661 if (close(in) != 0) {
662 return SYSTEM_ERROR;
663 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700664
665 if (isEncrypted() && (state != STATE_NO_ERROR)) {
666 return LOCKED;
667 }
668
Kenny Roota91203b2012-02-15 15:00:46 -0800669 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
670 if (fileLength < headerLength) {
671 return VALUE_CORRUPTED;
672 }
673
674 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700675 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800676 return VALUE_CORRUPTED;
677 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700678
679 ssize_t digestedLength;
680 if (isEncrypted()) {
681 if (encryptedLength % AES_BLOCK_SIZE != 0) {
682 return VALUE_CORRUPTED;
683 }
684
685 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
686 mBlob.vector, AES_DECRYPT);
687 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
688 uint8_t computedDigest[MD5_DIGEST_LENGTH];
689 MD5(mBlob.digested, digestedLength, computedDigest);
690 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
691 return VALUE_CORRUPTED;
692 }
693 } else {
694 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800695 }
696
697 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
698 mBlob.length = ntohl(mBlob.length);
699 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
700 return VALUE_CORRUPTED;
701 }
702 if (mBlob.info != 0) {
703 // move info from after padding to after data
704 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
705 }
Kenny Root07438c82012-11-02 15:41:02 -0700706 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800707 }
708
709private:
710 struct blob mBlob;
711};
712
Kenny Root655b9582013-04-04 08:37:42 -0700713class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800714public:
Kenny Root655b9582013-04-04 08:37:42 -0700715 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
716 asprintf(&mUserDir, "user_%u", mUserId);
717 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
718 }
719
720 ~UserState() {
721 free(mUserDir);
722 free(mMasterKeyFile);
723 }
724
725 bool initialize() {
726 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
727 ALOGE("Could not create directory '%s'", mUserDir);
728 return false;
729 }
730
731 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800732 setState(STATE_LOCKED);
733 } else {
734 setState(STATE_UNINITIALIZED);
735 }
Kenny Root70e3a862012-02-15 17:20:23 -0800736
Kenny Root655b9582013-04-04 08:37:42 -0700737 return true;
738 }
739
740 uid_t getUserId() const {
741 return mUserId;
742 }
743
744 const char* getUserDirName() const {
745 return mUserDir;
746 }
747
748 const char* getMasterKeyFileName() const {
749 return mMasterKeyFile;
750 }
751
752 void setState(State state) {
753 mState = state;
754 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
755 mRetry = MAX_RETRY;
756 }
Kenny Roota91203b2012-02-15 15:00:46 -0800757 }
758
Kenny Root51878182012-03-13 12:53:19 -0700759 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800760 return mState;
761 }
762
Kenny Root51878182012-03-13 12:53:19 -0700763 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800764 return mRetry;
765 }
766
Kenny Root655b9582013-04-04 08:37:42 -0700767 void zeroizeMasterKeysInMemory() {
768 memset(mMasterKey, 0, sizeof(mMasterKey));
769 memset(mSalt, 0, sizeof(mSalt));
770 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
771 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800772 }
773
Chad Brubaker96d6d782015-05-07 10:19:40 -0700774 bool deleteMasterKey() {
775 setState(STATE_UNINITIALIZED);
776 zeroizeMasterKeysInMemory();
777 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
778 }
779
Kenny Root655b9582013-04-04 08:37:42 -0700780 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
781 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800782 return SYSTEM_ERROR;
783 }
Kenny Root655b9582013-04-04 08:37:42 -0700784 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800785 if (response != NO_ERROR) {
786 return response;
787 }
788 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700789 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800790 }
791
Robin Lee4e865752014-08-19 17:37:55 +0100792 ResponseCode copyMasterKey(UserState* src) {
793 if (mState != STATE_UNINITIALIZED) {
794 return ::SYSTEM_ERROR;
795 }
796 if (src->getState() != STATE_NO_ERROR) {
797 return ::SYSTEM_ERROR;
798 }
799 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
800 setupMasterKeys();
801 return ::NO_ERROR;
802 }
803
Kenny Root655b9582013-04-04 08:37:42 -0700804 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800805 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
806 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
807 AES_KEY passwordAesKey;
808 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700809 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700810 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800811 }
812
Kenny Root655b9582013-04-04 08:37:42 -0700813 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
814 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800815 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800816 return SYSTEM_ERROR;
817 }
818
819 // we read the raw blob to just to get the salt to generate
820 // the AES key, then we create the Blob to use with decryptBlob
821 blob rawBlob;
822 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
823 if (close(in) != 0) {
824 return SYSTEM_ERROR;
825 }
826 // find salt at EOF if present, otherwise we have an old file
827 uint8_t* salt;
828 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
829 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
830 } else {
831 salt = NULL;
832 }
833 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
834 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
835 AES_KEY passwordAesKey;
836 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
837 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700838 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
839 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800840 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700841 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800842 }
843 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
844 // if salt was missing, generate one and write a new master key file with the salt.
845 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700846 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800847 return SYSTEM_ERROR;
848 }
Kenny Root655b9582013-04-04 08:37:42 -0700849 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800850 }
851 if (response == NO_ERROR) {
852 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
853 setupMasterKeys();
854 }
855 return response;
856 }
857 if (mRetry <= 0) {
858 reset();
859 return UNINITIALIZED;
860 }
861 --mRetry;
862 switch (mRetry) {
863 case 0: return WRONG_PASSWORD_0;
864 case 1: return WRONG_PASSWORD_1;
865 case 2: return WRONG_PASSWORD_2;
866 case 3: return WRONG_PASSWORD_3;
867 default: return WRONG_PASSWORD_3;
868 }
869 }
870
Kenny Root655b9582013-04-04 08:37:42 -0700871 AES_KEY* getEncryptionKey() {
872 return &mMasterKeyEncryption;
873 }
874
875 AES_KEY* getDecryptionKey() {
876 return &mMasterKeyDecryption;
877 }
878
Kenny Roota91203b2012-02-15 15:00:46 -0800879 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700880 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800881 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700882 // If the directory doesn't exist then nothing to do.
883 if (errno == ENOENT) {
884 return true;
885 }
Kenny Root655b9582013-04-04 08:37:42 -0700886 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800887 return false;
888 }
Kenny Root655b9582013-04-04 08:37:42 -0700889
890 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800891 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700892 // skip . and ..
893 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700894 continue;
895 }
896
897 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800898 }
899 closedir(dir);
900 return true;
901 }
902
Kenny Root655b9582013-04-04 08:37:42 -0700903private:
904 static const int MASTER_KEY_SIZE_BYTES = 16;
905 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
906
907 static const int MAX_RETRY = 4;
908 static const size_t SALT_SIZE = 16;
909
910 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
911 uint8_t* salt) {
912 size_t saltSize;
913 if (salt != NULL) {
914 saltSize = SALT_SIZE;
915 } else {
916 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
917 salt = (uint8_t*) "keystore";
918 // sizeof = 9, not strlen = 8
919 saltSize = sizeof("keystore");
920 }
921
922 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
923 saltSize, 8192, keySize, key);
924 }
925
926 bool generateSalt(Entropy* entropy) {
927 return entropy->generate_random_data(mSalt, sizeof(mSalt));
928 }
929
930 bool generateMasterKey(Entropy* entropy) {
931 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
932 return false;
933 }
934 if (!generateSalt(entropy)) {
935 return false;
936 }
937 return true;
938 }
939
940 void setupMasterKeys() {
941 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
942 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
943 setState(STATE_NO_ERROR);
944 }
945
946 uid_t mUserId;
947
948 char* mUserDir;
949 char* mMasterKeyFile;
950
951 State mState;
952 int8_t mRetry;
953
954 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
955 uint8_t mSalt[SALT_SIZE];
956
957 AES_KEY mMasterKeyEncryption;
958 AES_KEY mMasterKeyDecryption;
959};
960
961typedef struct {
962 uint32_t uid;
963 const uint8_t* filename;
964} grant_t;
965
966class KeyStore {
967public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000968 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700969 : mEntropy(entropy)
970 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800971 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700972 {
973 memset(&mMetaData, '\0', sizeof(mMetaData));
974 }
975
976 ~KeyStore() {
977 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
978 it != mGrants.end(); it++) {
979 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700980 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800981 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700982
983 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
984 it != mMasterKeys.end(); it++) {
985 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700986 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800987 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700988 }
989
Chad Brubaker67d2a502015-03-11 17:21:18 +0000990 /**
991 * Depending on the hardware keymaster version is this may return a
992 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
993 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
994 * be guarded by a check on the device's version.
995 */
996 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700997 return mDevice;
998 }
999
Chad Brubaker67d2a502015-03-11 17:21:18 +00001000 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001001 return mFallbackDevice;
1002 }
1003
Chad Brubaker67d2a502015-03-11 17:21:18 +00001004 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001005 return blob.isFallback() ? mFallbackDevice: mDevice;
1006 }
1007
Kenny Root655b9582013-04-04 08:37:42 -07001008 ResponseCode initialize() {
1009 readMetaData();
1010 if (upgradeKeystore()) {
1011 writeMetaData();
1012 }
1013
1014 return ::NO_ERROR;
1015 }
1016
Chad Brubaker72593ee2015-05-12 10:42:00 -07001017 State getState(uid_t userId) {
1018 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001019 }
1020
Chad Brubaker72593ee2015-05-12 10:42:00 -07001021 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1022 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001023 return userState->initialize(pw, mEntropy);
1024 }
1025
Chad Brubaker72593ee2015-05-12 10:42:00 -07001026 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1027 UserState *userState = getUserState(dstUser);
1028 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001029 return userState->copyMasterKey(initState);
1030 }
1031
Chad Brubaker72593ee2015-05-12 10:42:00 -07001032 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1033 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001034 return userState->writeMasterKey(pw, mEntropy);
1035 }
1036
Chad Brubaker72593ee2015-05-12 10:42:00 -07001037 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1038 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001039 return userState->readMasterKey(pw, mEntropy);
1040 }
1041
1042 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001043 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001044 encode_key(encoded, keyName);
1045 return android::String8(encoded);
1046 }
1047
1048 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001049 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001050 encode_key(encoded, keyName);
1051 return android::String8::format("%u_%s", uid, encoded);
1052 }
1053
1054 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001055 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001056 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001057 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001058 encoded);
1059 }
1060
Chad Brubaker96d6d782015-05-07 10:19:40 -07001061 /*
1062 * Delete entries owned by userId. If keepUnencryptedEntries is true
1063 * then only encrypted entries will be removed, otherwise all entries will
1064 * be removed.
1065 */
1066 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001067 android::String8 prefix("");
1068 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001069 UserState* userState = getUserState(userId);
1070 if (saw(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001071 return;
1072 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001073 for (uint32_t i = 0; i < aliases.size(); i++) {
1074 android::String8 filename(aliases[i]);
1075 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001076 getKeyName(filename).string());
1077 bool shouldDelete = true;
1078 if (keepUnenryptedEntries) {
1079 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001080 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001081
Chad Brubaker96d6d782015-05-07 10:19:40 -07001082 /* get can fail if the blob is encrypted and the state is
1083 * not unlocked, only skip deleting blobs that were loaded and
1084 * who are not encrypted. If there are blobs we fail to read for
1085 * other reasons err on the safe side and delete them since we
1086 * can't tell if they're encrypted.
1087 */
1088 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1089 }
1090 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001091 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001092 }
1093 }
1094 if (!userState->deleteMasterKey()) {
1095 ALOGE("Failed to delete user %d's master key", userId);
1096 }
1097 if (!keepUnenryptedEntries) {
1098 if(!userState->reset()) {
1099 ALOGE("Failed to remove user %d's directory", userId);
1100 }
1101 }
Kenny Root655b9582013-04-04 08:37:42 -07001102 }
1103
Chad Brubaker72593ee2015-05-12 10:42:00 -07001104 bool isEmpty(uid_t userId) const {
1105 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001106 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001107 return true;
1108 }
1109
1110 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001111 if (!dir) {
1112 return true;
1113 }
Kenny Root31e27462014-09-10 11:28:03 -07001114
Kenny Roota91203b2012-02-15 15:00:46 -08001115 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001116 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001117 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001118 // We only care about files.
1119 if (file->d_type != DT_REG) {
1120 continue;
1121 }
1122
1123 // Skip anything that starts with a "."
1124 if (file->d_name[0] == '.') {
1125 continue;
1126 }
1127
Kenny Root31e27462014-09-10 11:28:03 -07001128 result = false;
1129 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001130 }
1131 closedir(dir);
1132 return result;
1133 }
1134
Chad Brubaker72593ee2015-05-12 10:42:00 -07001135 void lock(uid_t userId) {
1136 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001137 userState->zeroizeMasterKeysInMemory();
1138 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001139 }
1140
Chad Brubaker72593ee2015-05-12 10:42:00 -07001141 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1142 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001143 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1144 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001145 if (rc != NO_ERROR) {
1146 return rc;
1147 }
1148
1149 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001150 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001151 /* If we upgrade the key, we need to write it to disk again. Then
1152 * it must be read it again since the blob is encrypted each time
1153 * it's written.
1154 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001155 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1156 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001157 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1158 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001159 return rc;
1160 }
1161 }
Kenny Root822c3a92012-03-23 16:34:39 -07001162 }
1163
Kenny Root17208e02013-09-04 13:56:03 -07001164 /*
1165 * This will upgrade software-backed keys to hardware-backed keys when
1166 * the HAL for the device supports the newer key types.
1167 */
1168 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1169 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1170 && keyBlob->isFallback()) {
1171 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001172 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001173
1174 // The HAL allowed the import, reget the key to have the "fresh"
1175 // version.
1176 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001177 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001178 }
1179 }
1180
Kenny Rootd53bc922013-03-21 14:10:15 -07001181 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001182 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1183 return KEY_NOT_FOUND;
1184 }
1185
1186 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001187 }
1188
Chad Brubaker72593ee2015-05-12 10:42:00 -07001189 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1190 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001191 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1192 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001193 }
1194
Chad Brubaker72593ee2015-05-12 10:42:00 -07001195 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001196 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001197 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001198 if (rc != ::NO_ERROR) {
1199 return rc;
1200 }
1201
1202 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1203 // A device doesn't have to implement delete_keypair.
1204 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1205 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1206 rc = ::SYSTEM_ERROR;
1207 }
1208 }
1209 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001210 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1211 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1212 if (dev->delete_key) {
1213 keymaster_key_blob_t blob;
1214 blob.key_material = keyBlob.getValue();
1215 blob.key_material_size = keyBlob.getLength();
1216 dev->delete_key(dev, &blob);
1217 }
1218 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001219 if (rc != ::NO_ERROR) {
1220 return rc;
1221 }
1222
1223 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1224 }
1225
1226 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001227 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001228
Chad Brubaker72593ee2015-05-12 10:42:00 -07001229 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001230 size_t n = prefix.length();
1231
1232 DIR* dir = opendir(userState->getUserDirName());
1233 if (!dir) {
1234 ALOGW("can't open directory for user: %s", strerror(errno));
1235 return ::SYSTEM_ERROR;
1236 }
1237
1238 struct dirent* file;
1239 while ((file = readdir(dir)) != NULL) {
1240 // We only care about files.
1241 if (file->d_type != DT_REG) {
1242 continue;
1243 }
1244
1245 // Skip anything that starts with a "."
1246 if (file->d_name[0] == '.') {
1247 continue;
1248 }
1249
1250 if (!strncmp(prefix.string(), file->d_name, n)) {
1251 const char* p = &file->d_name[n];
1252 size_t plen = strlen(p);
1253
1254 size_t extra = decode_key_length(p, plen);
1255 char *match = (char*) malloc(extra + 1);
1256 if (match != NULL) {
1257 decode_key(match, p, plen);
1258 matches->push(android::String16(match, extra));
1259 free(match);
1260 } else {
1261 ALOGW("could not allocate match of size %zd", extra);
1262 }
1263 }
1264 }
1265 closedir(dir);
1266 return ::NO_ERROR;
1267 }
1268
Kenny Root07438c82012-11-02 15:41:02 -07001269 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001270 const grant_t* existing = getGrant(filename, granteeUid);
1271 if (existing == NULL) {
1272 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001273 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001274 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001275 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001276 }
1277 }
1278
Kenny Root07438c82012-11-02 15:41:02 -07001279 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001280 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1281 it != mGrants.end(); it++) {
1282 grant_t* grant = *it;
1283 if (grant->uid == granteeUid
1284 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1285 mGrants.erase(it);
1286 return true;
1287 }
Kenny Root70e3a862012-02-15 17:20:23 -08001288 }
Kenny Root70e3a862012-02-15 17:20:23 -08001289 return false;
1290 }
1291
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001292 bool hasGrant(const char* filename, const uid_t uid) const {
1293 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001294 }
1295
Chad Brubaker72593ee2015-05-12 10:42:00 -07001296 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001297 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001298 uint8_t* data;
1299 size_t dataLength;
1300 int rc;
1301
1302 if (mDevice->import_keypair == NULL) {
1303 ALOGE("Keymaster doesn't support import!");
1304 return SYSTEM_ERROR;
1305 }
1306
Kenny Root17208e02013-09-04 13:56:03 -07001307 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001308 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001309 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001310 /*
1311 * Maybe the device doesn't support this type of key. Try to use the
1312 * software fallback keymaster implementation. This is a little bit
1313 * lazier than checking the PKCS#8 key type, but the software
1314 * implementation will do that anyway.
1315 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001316 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001317 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001318
1319 if (rc) {
1320 ALOGE("Error while importing keypair: %d", rc);
1321 return SYSTEM_ERROR;
1322 }
Kenny Root822c3a92012-03-23 16:34:39 -07001323 }
1324
1325 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1326 free(data);
1327
Kenny Rootf9119d62013-04-03 09:22:15 -07001328 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001329 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001330
Chad Brubaker72593ee2015-05-12 10:42:00 -07001331 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001332 }
1333
Kenny Root1b0e3932013-09-05 13:06:32 -07001334 bool isHardwareBacked(const android::String16& keyType) const {
1335 if (mDevice == NULL) {
1336 ALOGW("can't get keymaster device");
1337 return false;
1338 }
1339
1340 if (sRSAKeyType == keyType) {
1341 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1342 } else {
1343 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1344 && (mDevice->common.module->module_api_version
1345 >= KEYMASTER_MODULE_API_VERSION_0_2);
1346 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001347 }
1348
Kenny Root655b9582013-04-04 08:37:42 -07001349 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1350 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001351 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001352 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001353
Chad Brubaker72593ee2015-05-12 10:42:00 -07001354 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001355 if (responseCode == NO_ERROR) {
1356 return responseCode;
1357 }
1358
1359 // If this is one of the legacy UID->UID mappings, use it.
1360 uid_t euid = get_keystore_euid(uid);
1361 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001362 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001363 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001364 if (responseCode == NO_ERROR) {
1365 return responseCode;
1366 }
1367 }
1368
1369 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001370 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001371 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001372 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001373 if (end[0] != '_' || end[1] == 0) {
1374 return KEY_NOT_FOUND;
1375 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001376 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001377 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001378 if (!hasGrant(filepath8.string(), uid)) {
1379 return responseCode;
1380 }
1381
1382 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001383 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001384 }
1385
1386 /**
1387 * Returns any existing UserState or creates it if it doesn't exist.
1388 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001389 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001390 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1391 it != mMasterKeys.end(); it++) {
1392 UserState* state = *it;
1393 if (state->getUserId() == userId) {
1394 return state;
1395 }
1396 }
1397
1398 UserState* userState = new UserState(userId);
1399 if (!userState->initialize()) {
1400 /* There's not much we can do if initialization fails. Trying to
1401 * unlock the keystore for that user will fail as well, so any
1402 * subsequent request for this user will just return SYSTEM_ERROR.
1403 */
1404 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1405 }
1406 mMasterKeys.add(userState);
1407 return userState;
1408 }
1409
1410 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001411 * Returns any existing UserState or creates it if it doesn't exist.
1412 */
1413 UserState* getUserStateByUid(uid_t uid) {
1414 uid_t userId = get_user_id(uid);
1415 return getUserState(userId);
1416 }
1417
1418 /**
Kenny Root655b9582013-04-04 08:37:42 -07001419 * Returns NULL if the UserState doesn't already exist.
1420 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001421 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001422 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1423 it != mMasterKeys.end(); it++) {
1424 UserState* state = *it;
1425 if (state->getUserId() == userId) {
1426 return state;
1427 }
1428 }
1429
1430 return NULL;
1431 }
1432
Chad Brubaker72593ee2015-05-12 10:42:00 -07001433 /**
1434 * Returns NULL if the UserState doesn't already exist.
1435 */
1436 const UserState* getUserStateByUid(uid_t uid) const {
1437 uid_t userId = get_user_id(uid);
1438 return getUserState(userId);
1439 }
1440
Kenny Roota91203b2012-02-15 15:00:46 -08001441private:
Kenny Root655b9582013-04-04 08:37:42 -07001442 static const char* sOldMasterKey;
1443 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001444 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001445 Entropy* mEntropy;
1446
Chad Brubaker67d2a502015-03-11 17:21:18 +00001447 keymaster1_device_t* mDevice;
1448 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001449
Kenny Root655b9582013-04-04 08:37:42 -07001450 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001451
Kenny Root655b9582013-04-04 08:37:42 -07001452 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001453
Kenny Root655b9582013-04-04 08:37:42 -07001454 typedef struct {
1455 uint32_t version;
1456 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001457
Kenny Root655b9582013-04-04 08:37:42 -07001458 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001459
Kenny Root655b9582013-04-04 08:37:42 -07001460 const grant_t* getGrant(const char* filename, uid_t uid) const {
1461 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1462 it != mGrants.end(); it++) {
1463 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001464 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001465 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001466 return grant;
1467 }
1468 }
Kenny Root70e3a862012-02-15 17:20:23 -08001469 return NULL;
1470 }
1471
Kenny Root822c3a92012-03-23 16:34:39 -07001472 /**
1473 * Upgrade code. This will upgrade the key from the current version
1474 * to whatever is newest.
1475 */
Kenny Root655b9582013-04-04 08:37:42 -07001476 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1477 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001478 bool updated = false;
1479 uint8_t version = oldVersion;
1480
1481 /* From V0 -> V1: All old types were unknown */
1482 if (version == 0) {
1483 ALOGV("upgrading to version 1 and setting type %d", type);
1484
1485 blob->setType(type);
1486 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001487 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001488 }
1489 version = 1;
1490 updated = true;
1491 }
1492
Kenny Rootf9119d62013-04-03 09:22:15 -07001493 /* From V1 -> V2: All old keys were encrypted */
1494 if (version == 1) {
1495 ALOGV("upgrading to version 2");
1496
1497 blob->setEncrypted(true);
1498 version = 2;
1499 updated = true;
1500 }
1501
Kenny Root822c3a92012-03-23 16:34:39 -07001502 /*
1503 * If we've updated, set the key blob to the right version
1504 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001505 */
Kenny Root822c3a92012-03-23 16:34:39 -07001506 if (updated) {
1507 ALOGV("updated and writing file %s", filename);
1508 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001509 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001510
1511 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001512 }
1513
1514 /**
1515 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1516 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1517 * Then it overwrites the original blob with the new blob
1518 * format that is returned from the keymaster.
1519 */
Kenny Root655b9582013-04-04 08:37:42 -07001520 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001521 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1522 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1523 if (b.get() == NULL) {
1524 ALOGE("Problem instantiating BIO");
1525 return SYSTEM_ERROR;
1526 }
1527
1528 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1529 if (pkey.get() == NULL) {
1530 ALOGE("Couldn't read old PEM file");
1531 return SYSTEM_ERROR;
1532 }
1533
1534 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1535 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1536 if (len < 0) {
1537 ALOGE("Couldn't measure PKCS#8 length");
1538 return SYSTEM_ERROR;
1539 }
1540
Kenny Root70c98892013-02-07 09:10:36 -08001541 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1542 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001543 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1544 ALOGE("Couldn't convert to PKCS#8");
1545 return SYSTEM_ERROR;
1546 }
1547
Chad Brubaker72593ee2015-05-12 10:42:00 -07001548 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001549 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001550 if (rc != NO_ERROR) {
1551 return rc;
1552 }
1553
Kenny Root655b9582013-04-04 08:37:42 -07001554 return get(filename, blob, TYPE_KEY_PAIR, uid);
1555 }
1556
1557 void readMetaData() {
1558 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1559 if (in < 0) {
1560 return;
1561 }
1562 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1563 if (fileLength != sizeof(mMetaData)) {
1564 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1565 sizeof(mMetaData));
1566 }
1567 close(in);
1568 }
1569
1570 void writeMetaData() {
1571 const char* tmpFileName = ".metadata.tmp";
1572 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1573 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1574 if (out < 0) {
1575 ALOGE("couldn't write metadata file: %s", strerror(errno));
1576 return;
1577 }
1578 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1579 if (fileLength != sizeof(mMetaData)) {
1580 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1581 sizeof(mMetaData));
1582 }
1583 close(out);
1584 rename(tmpFileName, sMetaDataFile);
1585 }
1586
1587 bool upgradeKeystore() {
1588 bool upgraded = false;
1589
1590 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001591 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001592
1593 // Initialize first so the directory is made.
1594 userState->initialize();
1595
1596 // Migrate the old .masterkey file to user 0.
1597 if (access(sOldMasterKey, R_OK) == 0) {
1598 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1599 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1600 return false;
1601 }
1602 }
1603
1604 // Initialize again in case we had a key.
1605 userState->initialize();
1606
1607 // Try to migrate existing keys.
1608 DIR* dir = opendir(".");
1609 if (!dir) {
1610 // Give up now; maybe we can upgrade later.
1611 ALOGE("couldn't open keystore's directory; something is wrong");
1612 return false;
1613 }
1614
1615 struct dirent* file;
1616 while ((file = readdir(dir)) != NULL) {
1617 // We only care about files.
1618 if (file->d_type != DT_REG) {
1619 continue;
1620 }
1621
1622 // Skip anything that starts with a "."
1623 if (file->d_name[0] == '.') {
1624 continue;
1625 }
1626
1627 // Find the current file's user.
1628 char* end;
1629 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1630 if (end[0] != '_' || end[1] == 0) {
1631 continue;
1632 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001633 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001634 if (otherUser->getUserId() != 0) {
1635 unlinkat(dirfd(dir), file->d_name, 0);
1636 }
1637
1638 // Rename the file into user directory.
1639 DIR* otherdir = opendir(otherUser->getUserDirName());
1640 if (otherdir == NULL) {
1641 ALOGW("couldn't open user directory for rename");
1642 continue;
1643 }
1644 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1645 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1646 }
1647 closedir(otherdir);
1648 }
1649 closedir(dir);
1650
1651 mMetaData.version = 1;
1652 upgraded = true;
1653 }
1654
1655 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001656 }
Kenny Roota91203b2012-02-15 15:00:46 -08001657};
1658
Kenny Root655b9582013-04-04 08:37:42 -07001659const char* KeyStore::sOldMasterKey = ".masterkey";
1660const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001661
Kenny Root1b0e3932013-09-05 13:06:32 -07001662const android::String16 KeyStore::sRSAKeyType("RSA");
1663
Kenny Root07438c82012-11-02 15:41:02 -07001664namespace android {
1665class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1666public:
1667 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001668 : mKeyStore(keyStore),
1669 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001670 {
Kenny Roota91203b2012-02-15 15:00:46 -08001671 }
Kenny Roota91203b2012-02-15 15:00:46 -08001672
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001673 void binderDied(const wp<IBinder>& who) {
1674 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1675 for (auto token: operations) {
1676 abort(token);
1677 }
Kenny Root822c3a92012-03-23 16:34:39 -07001678 }
Kenny Roota91203b2012-02-15 15:00:46 -08001679
Kenny Root07438c82012-11-02 15:41:02 -07001680 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001681 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001682 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001683 }
Kenny Roota91203b2012-02-15 15:00:46 -08001684
Chad Brubaker72593ee2015-05-12 10:42:00 -07001685 return mKeyStore->getState(get_user_id(IPCThreadState::self()->getCallingUid()));
Kenny Root298e7b12012-03-26 13:54:44 -07001686 }
1687
Kenny Root07438c82012-11-02 15:41:02 -07001688 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001689 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001690 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001691 }
Kenny Root07438c82012-11-02 15:41:02 -07001692
Chad Brubaker9489b792015-04-14 11:01:45 -07001693 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001694 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001695 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001696
Kenny Root655b9582013-04-04 08:37:42 -07001697 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001698 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001699 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001700 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001701 *item = NULL;
1702 *itemLength = 0;
1703 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001704 }
Kenny Roota91203b2012-02-15 15:00:46 -08001705
Kenny Root07438c82012-11-02 15:41:02 -07001706 *item = (uint8_t*) malloc(keyBlob.getLength());
1707 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1708 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001709
Kenny Root07438c82012-11-02 15:41:02 -07001710 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001711 }
1712
Kenny Rootf9119d62013-04-03 09:22:15 -07001713 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1714 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001715 targetUid = getEffectiveUid(targetUid);
1716 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1717 flags & KEYSTORE_FLAG_ENCRYPTED);
1718 if (result != ::NO_ERROR) {
1719 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001720 }
1721
Kenny Root07438c82012-11-02 15:41:02 -07001722 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001723 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001724
1725 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001726 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1727
Chad Brubaker72593ee2015-05-12 10:42:00 -07001728 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001729 }
1730
Kenny Root49468902013-03-19 13:41:33 -07001731 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001732 targetUid = getEffectiveUid(targetUid);
1733 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001734 return ::PERMISSION_DENIED;
1735 }
Kenny Root07438c82012-11-02 15:41:02 -07001736 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001737 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001738 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001739 }
1740
Kenny Root49468902013-03-19 13:41:33 -07001741 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001742 targetUid = getEffectiveUid(targetUid);
1743 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001744 return ::PERMISSION_DENIED;
1745 }
1746
Kenny Root07438c82012-11-02 15:41:02 -07001747 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001748 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001749
Kenny Root655b9582013-04-04 08:37:42 -07001750 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001751 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1752 }
1753 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001754 }
1755
Kenny Root49468902013-03-19 13:41:33 -07001756 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001757 targetUid = getEffectiveUid(targetUid);
1758 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001759 return ::PERMISSION_DENIED;
1760 }
Kenny Root07438c82012-11-02 15:41:02 -07001761 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001762 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001763
Chad Brubaker72593ee2015-05-12 10:42:00 -07001764 if (mKeyStore->saw(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001765 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001766 }
Kenny Root07438c82012-11-02 15:41:02 -07001767 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001768 }
1769
Kenny Root07438c82012-11-02 15:41:02 -07001770 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001771 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001772 return ::PERMISSION_DENIED;
1773 }
1774
Chad Brubaker9489b792015-04-14 11:01:45 -07001775 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001776 mKeyStore->resetUser(get_user_id(callingUid), false);
1777 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001778 }
1779
Chad Brubaker96d6d782015-05-07 10:19:40 -07001780 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001781 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001782 return ::PERMISSION_DENIED;
1783 }
Kenny Root70e3a862012-02-15 17:20:23 -08001784
Kenny Root07438c82012-11-02 15:41:02 -07001785 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001786 // Flush the auth token table to prevent stale tokens from sticking
1787 // around.
1788 mAuthTokenTable.Clear();
1789
1790 if (password.size() == 0) {
1791 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001792 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001793 return ::NO_ERROR;
1794 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001795 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001796 case ::STATE_UNINITIALIZED: {
1797 // generate master key, encrypt with password, write to file,
1798 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001799 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001800 }
1801 case ::STATE_NO_ERROR: {
1802 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001803 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001804 }
1805 case ::STATE_LOCKED: {
1806 ALOGE("Changing user %d's password while locked, clearing old encryption",
1807 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001808 mKeyStore->resetUser(userId, true);
1809 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001810 }
Kenny Root07438c82012-11-02 15:41:02 -07001811 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001812 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001813 }
Kenny Root70e3a862012-02-15 17:20:23 -08001814 }
1815
Kenny Root07438c82012-11-02 15:41:02 -07001816 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001817 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001818 return ::PERMISSION_DENIED;
1819 }
Kenny Root70e3a862012-02-15 17:20:23 -08001820
Chad Brubaker72593ee2015-05-12 10:42:00 -07001821 uid_t userId = get_user_id(IPCThreadState::self()->getCallingUid());
1822 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001823 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001824 ALOGD("calling lock in state: %d", state);
1825 return state;
1826 }
1827
Chad Brubaker72593ee2015-05-12 10:42:00 -07001828 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001829 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001830 }
1831
Chad Brubaker96d6d782015-05-07 10:19:40 -07001832 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001833 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001834 return ::PERMISSION_DENIED;
1835 }
1836
Chad Brubaker72593ee2015-05-12 10:42:00 -07001837 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001838 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001839 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001840 return state;
1841 }
1842
1843 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001844 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001845 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001846 }
1847
Kenny Root07438c82012-11-02 15:41:02 -07001848 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001849 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001850 return -1;
1851 }
Kenny Root70e3a862012-02-15 17:20:23 -08001852
Chad Brubaker9489b792015-04-14 11:01:45 -07001853 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker72593ee2015-05-12 10:42:00 -07001854 return mKeyStore->isEmpty(get_user_id(callingUid)) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001855 }
1856
Kenny Root96427ba2013-08-16 14:02:41 -07001857 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1858 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001859 targetUid = getEffectiveUid(targetUid);
1860 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1861 flags & KEYSTORE_FLAG_ENCRYPTED);
1862 if (result != ::NO_ERROR) {
1863 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001864 }
Kenny Root07438c82012-11-02 15:41:02 -07001865 uint8_t* data;
1866 size_t dataLength;
1867 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001868 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001869
Chad Brubaker67d2a502015-03-11 17:21:18 +00001870 const keymaster1_device_t* device = mKeyStore->getDevice();
1871 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001872 if (device == NULL) {
1873 return ::SYSTEM_ERROR;
1874 }
1875
1876 if (device->generate_keypair == NULL) {
1877 return ::SYSTEM_ERROR;
1878 }
1879
Kenny Root17208e02013-09-04 13:56:03 -07001880 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001881 keymaster_dsa_keygen_params_t dsa_params;
1882 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001883
Kenny Root96427ba2013-08-16 14:02:41 -07001884 if (keySize == -1) {
1885 keySize = DSA_DEFAULT_KEY_SIZE;
1886 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1887 || keySize > DSA_MAX_KEY_SIZE) {
1888 ALOGI("invalid key size %d", keySize);
1889 return ::SYSTEM_ERROR;
1890 }
1891 dsa_params.key_size = keySize;
1892
1893 if (args->size() == 3) {
1894 sp<KeystoreArg> gArg = args->itemAt(0);
1895 sp<KeystoreArg> pArg = args->itemAt(1);
1896 sp<KeystoreArg> qArg = args->itemAt(2);
1897
1898 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1899 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1900 dsa_params.generator_len = gArg->size();
1901
1902 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1903 dsa_params.prime_p_len = pArg->size();
1904
1905 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1906 dsa_params.prime_q_len = qArg->size();
1907 } else {
1908 ALOGI("not all DSA parameters were read");
1909 return ::SYSTEM_ERROR;
1910 }
1911 } else if (args->size() != 0) {
1912 ALOGI("DSA args must be 3");
1913 return ::SYSTEM_ERROR;
1914 }
1915
Kenny Root1d448c02013-11-21 10:36:53 -08001916 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001917 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1918 } else {
1919 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001920 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1921 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001922 }
1923 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001924 keymaster_ec_keygen_params_t ec_params;
1925 memset(&ec_params, '\0', sizeof(ec_params));
1926
1927 if (keySize == -1) {
1928 keySize = EC_DEFAULT_KEY_SIZE;
1929 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1930 ALOGI("invalid key size %d", keySize);
1931 return ::SYSTEM_ERROR;
1932 }
1933 ec_params.field_size = keySize;
1934
Kenny Root1d448c02013-11-21 10:36:53 -08001935 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001936 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1937 } else {
1938 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001939 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001940 }
Kenny Root96427ba2013-08-16 14:02:41 -07001941 } else if (keyType == EVP_PKEY_RSA) {
1942 keymaster_rsa_keygen_params_t rsa_params;
1943 memset(&rsa_params, '\0', sizeof(rsa_params));
1944 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1945
1946 if (keySize == -1) {
1947 keySize = RSA_DEFAULT_KEY_SIZE;
1948 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1949 ALOGI("invalid key size %d", keySize);
1950 return ::SYSTEM_ERROR;
1951 }
1952 rsa_params.modulus_size = keySize;
1953
1954 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001955 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001956 return ::SYSTEM_ERROR;
1957 } else if (args->size() == 1) {
1958 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1959 if (pubExpBlob != NULL) {
1960 Unique_BIGNUM pubExpBn(
1961 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1962 pubExpBlob->size(), NULL));
1963 if (pubExpBn.get() == NULL) {
1964 ALOGI("Could not convert public exponent to BN");
1965 return ::SYSTEM_ERROR;
1966 }
1967 unsigned long pubExp = BN_get_word(pubExpBn.get());
1968 if (pubExp == 0xFFFFFFFFL) {
1969 ALOGI("cannot represent public exponent as a long value");
1970 return ::SYSTEM_ERROR;
1971 }
1972 rsa_params.public_exponent = pubExp;
1973 }
1974 }
1975
1976 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1977 } else {
1978 ALOGW("Unsupported key type %d", keyType);
1979 rc = -1;
1980 }
1981
Kenny Root07438c82012-11-02 15:41:02 -07001982 if (rc) {
1983 return ::SYSTEM_ERROR;
1984 }
1985
Kenny Root655b9582013-04-04 08:37:42 -07001986 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07001987 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001988
1989 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1990 free(data);
1991
Kenny Rootee8068b2013-10-07 09:49:15 -07001992 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001993 keyBlob.setFallback(isFallback);
1994
Chad Brubaker72593ee2015-05-12 10:42:00 -07001995 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001996 }
1997
Kenny Rootf9119d62013-04-03 09:22:15 -07001998 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1999 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002000 targetUid = getEffectiveUid(targetUid);
2001 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2002 flags & KEYSTORE_FLAG_ENCRYPTED);
2003 if (result != ::NO_ERROR) {
2004 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002005 }
Kenny Root07438c82012-11-02 15:41:02 -07002006 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002007 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002008
Chad Brubaker72593ee2015-05-12 10:42:00 -07002009 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2010 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002011 }
2012
Kenny Root07438c82012-11-02 15:41:02 -07002013 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2014 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002015 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002016 return ::PERMISSION_DENIED;
2017 }
Kenny Root07438c82012-11-02 15:41:02 -07002018
Chad Brubaker9489b792015-04-14 11:01:45 -07002019 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002020 Blob keyBlob;
2021 String8 name8(name);
2022
Kenny Rootd38a0b02013-02-13 12:59:14 -08002023 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002024
Kenny Root655b9582013-04-04 08:37:42 -07002025 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002026 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002027 if (responseCode != ::NO_ERROR) {
2028 return responseCode;
2029 }
2030
Chad Brubaker67d2a502015-03-11 17:21:18 +00002031 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002032 if (device == NULL) {
2033 ALOGE("no keymaster device; cannot sign");
2034 return ::SYSTEM_ERROR;
2035 }
2036
2037 if (device->sign_data == NULL) {
2038 ALOGE("device doesn't implement signing");
2039 return ::SYSTEM_ERROR;
2040 }
2041
2042 keymaster_rsa_sign_params_t params;
2043 params.digest_type = DIGEST_NONE;
2044 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002045 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002046 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002047 if (rc) {
2048 ALOGW("device couldn't sign data");
2049 return ::SYSTEM_ERROR;
2050 }
2051
2052 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002053 }
2054
Kenny Root07438c82012-11-02 15:41:02 -07002055 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2056 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002057 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002058 return ::PERMISSION_DENIED;
2059 }
Kenny Root70e3a862012-02-15 17:20:23 -08002060
Chad Brubaker9489b792015-04-14 11:01:45 -07002061 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002062 Blob keyBlob;
2063 String8 name8(name);
2064 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002065
Kenny Root655b9582013-04-04 08:37:42 -07002066 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002067 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002068 if (responseCode != ::NO_ERROR) {
2069 return responseCode;
2070 }
Kenny Root70e3a862012-02-15 17:20:23 -08002071
Chad Brubaker67d2a502015-03-11 17:21:18 +00002072 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002073 if (device == NULL) {
2074 return ::SYSTEM_ERROR;
2075 }
Kenny Root70e3a862012-02-15 17:20:23 -08002076
Kenny Root07438c82012-11-02 15:41:02 -07002077 if (device->verify_data == NULL) {
2078 return ::SYSTEM_ERROR;
2079 }
Kenny Root70e3a862012-02-15 17:20:23 -08002080
Kenny Root07438c82012-11-02 15:41:02 -07002081 keymaster_rsa_sign_params_t params;
2082 params.digest_type = DIGEST_NONE;
2083 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002084
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002085 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2086 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002087 if (rc) {
2088 return ::SYSTEM_ERROR;
2089 } else {
2090 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002091 }
2092 }
Kenny Root07438c82012-11-02 15:41:02 -07002093
2094 /*
2095 * TODO: The abstraction between things stored in hardware and regular blobs
2096 * of data stored on the filesystem should be moved down to keystore itself.
2097 * Unfortunately the Java code that calls this has naming conventions that it
2098 * knows about. Ideally keystore shouldn't be used to store random blobs of
2099 * data.
2100 *
2101 * Until that happens, it's necessary to have a separate "get_pubkey" and
2102 * "del_key" since the Java code doesn't really communicate what it's
2103 * intentions are.
2104 */
2105 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002106 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002107 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002108 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002109 return ::PERMISSION_DENIED;
2110 }
Kenny Root07438c82012-11-02 15:41:02 -07002111
Kenny Root07438c82012-11-02 15:41:02 -07002112 Blob keyBlob;
2113 String8 name8(name);
2114
Kenny Rootd38a0b02013-02-13 12:59:14 -08002115 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002116
Kenny Root655b9582013-04-04 08:37:42 -07002117 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002118 TYPE_KEY_PAIR);
2119 if (responseCode != ::NO_ERROR) {
2120 return responseCode;
2121 }
2122
Chad Brubaker67d2a502015-03-11 17:21:18 +00002123 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002124 if (device == NULL) {
2125 return ::SYSTEM_ERROR;
2126 }
2127
2128 if (device->get_keypair_public == NULL) {
2129 ALOGE("device has no get_keypair_public implementation!");
2130 return ::SYSTEM_ERROR;
2131 }
2132
Kenny Root17208e02013-09-04 13:56:03 -07002133 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002134 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2135 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002136 if (rc) {
2137 return ::SYSTEM_ERROR;
2138 }
2139
2140 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002141 }
Kenny Root07438c82012-11-02 15:41:02 -07002142
Kenny Root49468902013-03-19 13:41:33 -07002143 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002144 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002145 }
2146
2147 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002148 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002149 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2150 if (result != ::NO_ERROR) {
2151 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002152 }
2153
2154 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002155 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002156
Kenny Root655b9582013-04-04 08:37:42 -07002157 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002158 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2159 }
2160
Kenny Root655b9582013-04-04 08:37:42 -07002161 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002162 return ::NO_ERROR;
2163 }
2164
2165 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002166 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002167 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2168 if (result != ::NO_ERROR) {
2169 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002170 }
2171
2172 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002173 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002174
Kenny Root655b9582013-04-04 08:37:42 -07002175 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002176 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2177 }
2178
Kenny Root655b9582013-04-04 08:37:42 -07002179 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002180 }
2181
2182 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002183 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002184 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002185 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002186 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002187 }
Kenny Root07438c82012-11-02 15:41:02 -07002188
2189 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002190 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002191
Kenny Root655b9582013-04-04 08:37:42 -07002192 if (access(filename.string(), R_OK) == -1) {
2193 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002194 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002195 }
2196
Kenny Root655b9582013-04-04 08:37:42 -07002197 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002198 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002199 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002200 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002201 }
2202
2203 struct stat s;
2204 int ret = fstat(fd, &s);
2205 close(fd);
2206 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002207 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002208 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002209 }
2210
Kenny Root36a9e232013-02-04 14:24:15 -08002211 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002212 }
2213
Kenny Rootd53bc922013-03-21 14:10:15 -07002214 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2215 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002216 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002217 pid_t spid = IPCThreadState::self()->getCallingPid();
2218 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002219 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002220 return -1L;
2221 }
2222
Chad Brubaker72593ee2015-05-12 10:42:00 -07002223 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002224 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002225 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002226 return state;
2227 }
2228
Kenny Rootd53bc922013-03-21 14:10:15 -07002229 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2230 srcUid = callingUid;
2231 } else if (!is_granted_to(callingUid, srcUid)) {
2232 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002233 return ::PERMISSION_DENIED;
2234 }
2235
Kenny Rootd53bc922013-03-21 14:10:15 -07002236 if (destUid == -1) {
2237 destUid = callingUid;
2238 }
2239
2240 if (srcUid != destUid) {
2241 if (static_cast<uid_t>(srcUid) != callingUid) {
2242 ALOGD("can only duplicate from caller to other or to same uid: "
2243 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2244 return ::PERMISSION_DENIED;
2245 }
2246
2247 if (!is_granted_to(callingUid, destUid)) {
2248 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2249 return ::PERMISSION_DENIED;
2250 }
2251 }
2252
2253 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002254 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002255
Kenny Rootd53bc922013-03-21 14:10:15 -07002256 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002257 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002258
Kenny Root655b9582013-04-04 08:37:42 -07002259 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2260 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002261 return ::SYSTEM_ERROR;
2262 }
2263
Kenny Rootd53bc922013-03-21 14:10:15 -07002264 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002265 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002266 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002267 if (responseCode != ::NO_ERROR) {
2268 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002269 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002270
Chad Brubaker72593ee2015-05-12 10:42:00 -07002271 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002272 }
2273
Kenny Root1b0e3932013-09-05 13:06:32 -07002274 int32_t is_hardware_backed(const String16& keyType) {
2275 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002276 }
2277
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002278 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002279 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002280 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002281 return ::PERMISSION_DENIED;
2282 }
2283
Robin Lee4b84fdc2014-09-24 11:56:57 +01002284 String8 prefix = String8::format("%u_", targetUid);
2285 Vector<String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07002286 if (mKeyStore->saw(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002287 return ::SYSTEM_ERROR;
2288 }
2289
Robin Lee4b84fdc2014-09-24 11:56:57 +01002290 for (uint32_t i = 0; i < aliases.size(); i++) {
2291 String8 name8(aliases[i]);
2292 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002293 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002294 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002295 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002296 }
2297
Robin Lee4b84fdc2014-09-24 11:56:57 +01002298 int32_t reset_uid(int32_t targetUid) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002299 // TODO: Remove this method from the binder interface
Chad Brubaker9489b792015-04-14 11:01:45 -07002300 targetUid = getEffectiveUid(targetUid);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002301 return onUserPasswordChanged(get_user_id(targetUid), String16(""));
Robin Lee4e865752014-08-19 17:37:55 +01002302 }
2303
2304 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002305 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002306 return ::PERMISSION_DENIED;
2307 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002308 uid_t sourceUser = get_user_id(sourceUid);
2309 uid_t targetUser = get_user_id(targetUid);
Chad Brubaker9489b792015-04-14 11:01:45 -07002310
Chad Brubaker72593ee2015-05-12 10:42:00 -07002311 if (sourceUser == targetUser) {
Robin Lee4e865752014-08-19 17:37:55 +01002312 return ::SYSTEM_ERROR;
2313 }
2314
2315 // Initialise user keystore with existing master key held in-memory
Chad Brubaker72593ee2015-05-12 10:42:00 -07002316 return mKeyStore->copyMasterKey(sourceUser, targetUser);
Robin Lee4e865752014-08-19 17:37:55 +01002317 }
2318
2319 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002320 targetUid = getEffectiveUid(targetUid);
2321 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002322 return ::PERMISSION_DENIED;
2323 }
Robin Lee4e865752014-08-19 17:37:55 +01002324 const String8 password8(pw);
Chad Brubaker72593ee2015-05-12 10:42:00 -07002325 uid_t userId = get_user_id(targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002326
Chad Brubaker72593ee2015-05-12 10:42:00 -07002327 switch (mKeyStore->getState(userId)) {
Robin Lee4e865752014-08-19 17:37:55 +01002328 case ::STATE_UNINITIALIZED: {
2329 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002330 return mKeyStore->initializeUser(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002331 }
2332 case ::STATE_NO_ERROR: {
2333 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002334 return mKeyStore->writeMasterKey(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002335 }
2336 case ::STATE_LOCKED: {
2337 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002338 return mKeyStore->readMasterKey(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002339 }
2340 }
2341 return ::SYSTEM_ERROR;
2342 }
2343
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002344 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2345 const keymaster1_device_t* device = mKeyStore->getDevice();
2346 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2347 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2348 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2349 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2350 device->add_rng_entropy != NULL) {
2351 devResult = device->add_rng_entropy(device, data, dataLength);
2352 }
2353 if (fallback->add_rng_entropy) {
2354 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2355 }
2356 if (devResult) {
2357 return devResult;
2358 }
2359 if (fallbackResult) {
2360 return fallbackResult;
2361 }
2362 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002363 }
2364
Chad Brubaker17d68b92015-02-05 22:04:16 -08002365 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002366 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2367 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002368 uid = getEffectiveUid(uid);
2369 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2370 flags & KEYSTORE_FLAG_ENCRYPTED);
2371 if (rc != ::NO_ERROR) {
2372 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002373 }
2374
Chad Brubaker9489b792015-04-14 11:01:45 -07002375 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002376 bool isFallback = false;
2377 keymaster_key_blob_t blob;
2378 keymaster_key_characteristics_t *out = NULL;
2379
2380 const keymaster1_device_t* device = mKeyStore->getDevice();
2381 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2382 if (device == NULL) {
2383 return ::SYSTEM_ERROR;
2384 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002385 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002386 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2387 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002388 if (!entropy) {
2389 rc = KM_ERROR_OK;
2390 } else if (device->add_rng_entropy) {
2391 rc = device->add_rng_entropy(device, entropy, entropyLength);
2392 } else {
2393 rc = KM_ERROR_UNIMPLEMENTED;
2394 }
2395 if (rc == KM_ERROR_OK) {
2396 rc = device->generate_key(device, params.params.data(), params.params.size(),
2397 &blob, &out);
2398 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002399 }
2400 // If the HW device didn't support generate_key or generate_key failed
2401 // fall back to the software implementation.
2402 if (rc && fallback->generate_key != NULL) {
2403 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002404 if (!entropy) {
2405 rc = KM_ERROR_OK;
2406 } else if (fallback->add_rng_entropy) {
2407 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2408 } else {
2409 rc = KM_ERROR_UNIMPLEMENTED;
2410 }
2411 if (rc == KM_ERROR_OK) {
2412 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2413 &blob,
2414 &out);
2415 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002416 }
2417
2418 if (out) {
2419 if (outCharacteristics) {
2420 outCharacteristics->characteristics = *out;
2421 } else {
2422 keymaster_free_characteristics(out);
2423 }
2424 free(out);
2425 }
2426
2427 if (rc) {
2428 return rc;
2429 }
2430
2431 String8 name8(name);
2432 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2433
2434 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2435 keyBlob.setFallback(isFallback);
2436 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2437
2438 free(const_cast<uint8_t*>(blob.key_material));
2439
Chad Brubaker72593ee2015-05-12 10:42:00 -07002440 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002441 }
2442
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002443 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002444 const keymaster_blob_t* clientId,
2445 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002446 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002447 if (!outCharacteristics) {
2448 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2449 }
2450
2451 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2452
2453 Blob keyBlob;
2454 String8 name8(name);
2455 int rc;
2456
2457 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2458 TYPE_KEYMASTER_10);
2459 if (responseCode != ::NO_ERROR) {
2460 return responseCode;
2461 }
2462 keymaster_key_blob_t key;
2463 key.key_material_size = keyBlob.getLength();
2464 key.key_material = keyBlob.getValue();
2465 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2466 keymaster_key_characteristics_t *out = NULL;
2467 if (!dev->get_key_characteristics) {
2468 ALOGW("device does not implement get_key_characteristics");
2469 return KM_ERROR_UNIMPLEMENTED;
2470 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002471 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002472 if (out) {
2473 outCharacteristics->characteristics = *out;
2474 free(out);
2475 }
2476 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002477 }
2478
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002479 int32_t importKey(const String16& name, const KeymasterArguments& params,
2480 keymaster_key_format_t format, const uint8_t *keyData,
2481 size_t keyLength, int uid, int flags,
2482 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002483 uid = getEffectiveUid(uid);
2484 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2485 flags & KEYSTORE_FLAG_ENCRYPTED);
2486 if (rc != ::NO_ERROR) {
2487 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002488 }
2489
Chad Brubaker9489b792015-04-14 11:01:45 -07002490 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002491 bool isFallback = false;
2492 keymaster_key_blob_t blob;
2493 keymaster_key_characteristics_t *out = NULL;
2494
2495 const keymaster1_device_t* device = mKeyStore->getDevice();
2496 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2497 if (device == NULL) {
2498 return ::SYSTEM_ERROR;
2499 }
2500 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2501 device->import_key != NULL) {
2502 rc = device->import_key(device, params.params.data(), params.params.size(),
2503 format, keyData, keyLength, &blob, &out);
2504 }
2505 if (rc && fallback->import_key != NULL) {
2506 isFallback = true;
2507 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2508 format, keyData, keyLength, &blob, &out);
2509 }
2510 if (out) {
2511 if (outCharacteristics) {
2512 outCharacteristics->characteristics = *out;
2513 } else {
2514 keymaster_free_characteristics(out);
2515 }
2516 free(out);
2517 }
2518 if (rc) {
2519 return rc;
2520 }
2521
2522 String8 name8(name);
2523 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2524
2525 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2526 keyBlob.setFallback(isFallback);
2527 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2528
2529 free((void*) blob.key_material);
2530
Chad Brubaker72593ee2015-05-12 10:42:00 -07002531 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002532 }
2533
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002534 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002535 const keymaster_blob_t* clientId,
2536 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002537
2538 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2539
2540 Blob keyBlob;
2541 String8 name8(name);
2542 int rc;
2543
2544 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2545 TYPE_KEYMASTER_10);
2546 if (responseCode != ::NO_ERROR) {
2547 result->resultCode = responseCode;
2548 return;
2549 }
2550 keymaster_key_blob_t key;
2551 key.key_material_size = keyBlob.getLength();
2552 key.key_material = keyBlob.getValue();
2553 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2554 if (!dev->export_key) {
2555 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2556 return;
2557 }
2558 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002559 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002560 &ptr, &result->dataLength);
2561 result->exportData.reset(ptr);
2562 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002563 }
2564
Chad Brubakerad6514a2015-04-09 14:00:26 -07002565
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002566 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002567 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2568 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002569 if (!result || !outParams) {
2570 ALOGE("Unexpected null arguments to begin()");
2571 return;
2572 }
2573 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2574 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2575 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2576 result->resultCode = ::PERMISSION_DENIED;
2577 return;
2578 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002579 if (!checkAllowedOperationParams(params.params)) {
2580 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2581 return;
2582 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002583 Blob keyBlob;
2584 String8 name8(name);
2585 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2586 TYPE_KEYMASTER_10);
2587 if (responseCode != ::NO_ERROR) {
2588 result->resultCode = responseCode;
2589 return;
2590 }
2591 keymaster_key_blob_t key;
2592 key.key_material_size = keyBlob.getLength();
2593 key.key_material = keyBlob.getValue();
2594 keymaster_key_param_t* out;
2595 size_t outSize;
2596 keymaster_operation_handle_t handle;
2597 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002598 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002599 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002600 Unique_keymaster_key_characteristics characteristics;
2601 characteristics.reset(new keymaster_key_characteristics_t);
2602 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2603 if (err) {
2604 result->resultCode = err;
2605 return;
2606 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002607 const hw_auth_token_t* authToken = NULL;
2608 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002609 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002610 // If per-operation auth is needed we need to begin the operation and
2611 // the client will need to authorize that operation before calling
2612 // update. Any other auth issues stop here.
2613 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2614 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002615 return;
2616 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002617 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002618 // Add entropy to the device first.
2619 if (entropy) {
2620 if (dev->add_rng_entropy) {
2621 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2622 } else {
2623 err = KM_ERROR_UNIMPLEMENTED;
2624 }
2625 if (err) {
2626 result->resultCode = err;
2627 return;
2628 }
2629 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002630 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2631 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002632
2633 // If there are too many operations abort the oldest operation that was
2634 // started as pruneable and try again.
2635 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2636 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2637 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2638 if (abort(oldest) != ::NO_ERROR) {
2639 break;
2640 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002641 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002642 &handle);
2643 }
2644 if (err) {
2645 result->resultCode = err;
2646 return;
2647 }
2648 if (out) {
2649 outParams->params.assign(out, out + outSize);
2650 free(out);
2651 }
2652
Chad Brubakerad6514a2015-04-09 14:00:26 -07002653 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2654 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002655 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002656 if (authToken) {
2657 mOperationMap.setOperationAuthToken(operationToken, authToken);
2658 }
2659 // Return the authentication lookup result. If this is a per operation
2660 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2661 // application should get an auth token using the handle before the
2662 // first call to update, which will fail if keystore hasn't received the
2663 // auth token.
2664 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002665 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002666 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002667 }
2668
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002669 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2670 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002671 if (!checkAllowedOperationParams(params.params)) {
2672 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2673 return;
2674 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002675 const keymaster1_device_t* dev;
2676 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002677 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002678 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2679 return;
2680 }
2681 uint8_t* output_buf = NULL;
2682 size_t output_length = 0;
2683 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002684 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002685 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2686 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002687 result->resultCode = authResult;
2688 return;
2689 }
2690 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2691 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002692 result->data.reset(output_buf);
2693 result->dataLength = output_length;
2694 result->inputConsumed = consumed;
2695 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002696 }
2697
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002698 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2699 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002700 if (!checkAllowedOperationParams(params.params)) {
2701 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2702 return;
2703 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002704 const keymaster1_device_t* dev;
2705 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002706 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002707 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2708 return;
2709 }
2710 uint8_t* output_buf = NULL;
2711 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002712 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002713 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2714 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002715 result->resultCode = authResult;
2716 return;
2717 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002718
Chad Brubaker06801e02015-03-31 15:13:13 -07002719 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2720 signature, signatureLength, &output_buf,
2721 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002722 // Remove the operation regardless of the result
2723 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002724 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002725 result->data.reset(output_buf);
2726 result->dataLength = output_length;
2727 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002728 }
2729
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002730 int32_t abort(const sp<IBinder>& token) {
2731 const keymaster1_device_t* dev;
2732 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002733 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002734 return KM_ERROR_INVALID_OPERATION_HANDLE;
2735 }
2736 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002737 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002738 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002739 rc = KM_ERROR_UNIMPLEMENTED;
2740 } else {
2741 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002742 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002743 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002744 if (rc) {
2745 return rc;
2746 }
2747 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002748 }
2749
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002750 bool isOperationAuthorized(const sp<IBinder>& token) {
2751 const keymaster1_device_t* dev;
2752 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002753 const keymaster_key_characteristics_t* characteristics;
2754 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002755 return false;
2756 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002757 const hw_auth_token_t* authToken = NULL;
2758 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002759 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002760 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2761 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002762 }
2763
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002764 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002765 if (!checkBinderPermission(P_ADD_AUTH)) {
2766 ALOGW("addAuthToken: permission denied for %d",
2767 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002768 return ::PERMISSION_DENIED;
2769 }
2770 if (length != sizeof(hw_auth_token_t)) {
2771 return KM_ERROR_INVALID_ARGUMENT;
2772 }
2773 hw_auth_token_t* authToken = new hw_auth_token_t;
2774 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2775 // The table takes ownership of authToken.
2776 mAuthTokenTable.AddAuthenticationToken(authToken);
2777 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002778 }
2779
Kenny Root07438c82012-11-02 15:41:02 -07002780private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002781 static const int32_t UID_SELF = -1;
2782
2783 /**
2784 * Get the effective target uid for a binder operation that takes an
2785 * optional uid as the target.
2786 */
2787 inline uid_t getEffectiveUid(int32_t targetUid) {
2788 if (targetUid == UID_SELF) {
2789 return IPCThreadState::self()->getCallingUid();
2790 }
2791 return static_cast<uid_t>(targetUid);
2792 }
2793
2794 /**
2795 * Check if the caller of the current binder method has the required
2796 * permission and if acting on other uids the grants to do so.
2797 */
2798 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2799 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2800 pid_t spid = IPCThreadState::self()->getCallingPid();
2801 if (!has_permission(callingUid, permission, spid)) {
2802 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2803 return false;
2804 }
2805 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2806 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2807 return false;
2808 }
2809 return true;
2810 }
2811
2812 /**
2813 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002814 * permission and the target uid is the caller or the caller is system.
2815 */
2816 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2817 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2818 pid_t spid = IPCThreadState::self()->getCallingPid();
2819 if (!has_permission(callingUid, permission, spid)) {
2820 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2821 return false;
2822 }
2823 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2824 }
2825
2826 /**
2827 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002828 * permission or the target of the operation is the caller's uid. This is
2829 * for operation where the permission is only for cross-uid activity and all
2830 * uids are allowed to act on their own (ie: clearing all entries for a
2831 * given uid).
2832 */
2833 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2834 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2835 if (getEffectiveUid(targetUid) == callingUid) {
2836 return true;
2837 } else {
2838 return checkBinderPermission(permission, targetUid);
2839 }
2840 }
2841
2842 /**
2843 * Helper method to check that the caller has the required permission as
2844 * well as the keystore is in the unlocked state if checkUnlocked is true.
2845 *
2846 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2847 * otherwise the state of keystore when not unlocked and checkUnlocked is
2848 * true.
2849 */
2850 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2851 bool checkUnlocked = true) {
2852 if (!checkBinderPermission(permission, targetUid)) {
2853 return ::PERMISSION_DENIED;
2854 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002855 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002856 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2857 return state;
2858 }
2859
2860 return ::NO_ERROR;
2861
2862 }
2863
Kenny Root9d45d1c2013-02-14 10:32:30 -08002864 inline bool isKeystoreUnlocked(State state) {
2865 switch (state) {
2866 case ::STATE_NO_ERROR:
2867 return true;
2868 case ::STATE_UNINITIALIZED:
2869 case ::STATE_LOCKED:
2870 return false;
2871 }
2872 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002873 }
2874
Chad Brubaker67d2a502015-03-11 17:21:18 +00002875 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002876 const int32_t device_api = device->common.module->module_api_version;
2877 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2878 switch (keyType) {
2879 case TYPE_RSA:
2880 case TYPE_DSA:
2881 case TYPE_EC:
2882 return true;
2883 default:
2884 return false;
2885 }
2886 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2887 switch (keyType) {
2888 case TYPE_RSA:
2889 return true;
2890 case TYPE_DSA:
2891 return device->flags & KEYMASTER_SUPPORTS_DSA;
2892 case TYPE_EC:
2893 return device->flags & KEYMASTER_SUPPORTS_EC;
2894 default:
2895 return false;
2896 }
2897 } else {
2898 return keyType == TYPE_RSA;
2899 }
2900 }
2901
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002902 /**
2903 * Check that all keymaster_key_param_t's provided by the application are
2904 * allowed. Any parameter that keystore adds itself should be disallowed here.
2905 */
2906 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2907 for (auto param: params) {
2908 switch (param.tag) {
2909 case KM_TAG_AUTH_TOKEN:
2910 return false;
2911 default:
2912 break;
2913 }
2914 }
2915 return true;
2916 }
2917
2918 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2919 const keymaster1_device_t* dev,
2920 const std::vector<keymaster_key_param_t>& params,
2921 keymaster_key_characteristics_t* out) {
2922 UniquePtr<keymaster_blob_t> appId;
2923 UniquePtr<keymaster_blob_t> appData;
2924 for (auto param : params) {
2925 if (param.tag == KM_TAG_APPLICATION_ID) {
2926 appId.reset(new keymaster_blob_t);
2927 appId->data = param.blob.data;
2928 appId->data_length = param.blob.data_length;
2929 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2930 appData.reset(new keymaster_blob_t);
2931 appData->data = param.blob.data;
2932 appData->data_length = param.blob.data_length;
2933 }
2934 }
2935 keymaster_key_characteristics_t* result = NULL;
2936 if (!dev->get_key_characteristics) {
2937 return KM_ERROR_UNIMPLEMENTED;
2938 }
2939 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2940 appData.get(), &result);
2941 if (result) {
2942 *out = *result;
2943 free(result);
2944 }
2945 return error;
2946 }
2947
2948 /**
2949 * Get the auth token for this operation from the auth token table.
2950 *
2951 * Returns ::NO_ERROR if the auth token was set or none was required.
2952 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2953 * authorization token exists for that operation and
2954 * failOnTokenMissing is false.
2955 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2956 * token for the operation
2957 */
2958 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2959 keymaster_operation_handle_t handle,
2960 const hw_auth_token_t** authToken,
2961 bool failOnTokenMissing = true) {
2962
2963 std::vector<keymaster_key_param_t> allCharacteristics;
2964 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2965 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2966 }
2967 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2968 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2969 }
2970 keymaster::AuthTokenTable::Error err =
2971 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2972 allCharacteristics.size(), handle, authToken);
2973 switch (err) {
2974 case keymaster::AuthTokenTable::OK:
2975 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2976 return ::NO_ERROR;
2977 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2978 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2979 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2980 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2981 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2982 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2983 (int32_t) ::OP_AUTH_NEEDED;
2984 default:
2985 ALOGE("Unexpected FindAuthorization return value %d", err);
2986 return KM_ERROR_INVALID_ARGUMENT;
2987 }
2988 }
2989
2990 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2991 const hw_auth_token_t* token) {
2992 if (token) {
2993 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2994 reinterpret_cast<const uint8_t*>(token),
2995 sizeof(hw_auth_token_t)));
2996 }
2997 }
2998
2999 /**
3000 * Add the auth token for the operation to the param list if the operation
3001 * requires authorization. Uses the cached result in the OperationMap if available
3002 * otherwise gets the token from the AuthTokenTable and caches the result.
3003 *
3004 * Returns ::NO_ERROR if the auth token was added or not needed.
3005 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3006 * authenticated.
3007 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3008 * operation token.
3009 */
3010 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3011 std::vector<keymaster_key_param_t>* params) {
3012 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003013 mOperationMap.getOperationAuthToken(token, &authToken);
3014 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003015 const keymaster1_device_t* dev;
3016 keymaster_operation_handle_t handle;
3017 const keymaster_key_characteristics_t* characteristics = NULL;
3018 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3019 return KM_ERROR_INVALID_OPERATION_HANDLE;
3020 }
3021 int32_t result = getAuthToken(characteristics, handle, &authToken);
3022 if (result != ::NO_ERROR) {
3023 return result;
3024 }
3025 if (authToken) {
3026 mOperationMap.setOperationAuthToken(token, authToken);
3027 }
3028 }
3029 addAuthToParams(params, authToken);
3030 return ::NO_ERROR;
3031 }
3032
Kenny Root07438c82012-11-02 15:41:02 -07003033 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003034 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003035 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003036};
3037
3038}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003039
3040int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003041 if (argc < 2) {
3042 ALOGE("A directory must be specified!");
3043 return 1;
3044 }
3045 if (chdir(argv[1]) == -1) {
3046 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3047 return 1;
3048 }
3049
3050 Entropy entropy;
3051 if (!entropy.open()) {
3052 return 1;
3053 }
Kenny Root70e3a862012-02-15 17:20:23 -08003054
Shawn Willden80843db2015-02-24 09:31:25 -07003055 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003056 if (keymaster_device_initialize(&dev)) {
3057 ALOGE("keystore keymaster could not be initialized; exiting");
3058 return 1;
3059 }
3060
Chad Brubaker67d2a502015-03-11 17:21:18 +00003061 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003062 if (fallback_keymaster_device_initialize(&fallback)) {
3063 ALOGE("software keymaster could not be initialized; exiting");
3064 return 1;
3065 }
3066
Riley Spahneaabae92014-06-30 12:39:52 -07003067 ks_is_selinux_enabled = is_selinux_enabled();
3068 if (ks_is_selinux_enabled) {
3069 union selinux_callback cb;
3070 cb.func_log = selinux_log_callback;
3071 selinux_set_callback(SELINUX_CB_LOG, cb);
3072 if (getcon(&tctx) != 0) {
3073 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3074 return -1;
3075 }
3076 } else {
3077 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3078 }
3079
Chad Brubaker67d2a502015-03-11 17:21:18 +00003080 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003081 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003082 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3083 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3084 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3085 if (ret != android::OK) {
3086 ALOGE("Couldn't register binder service!");
3087 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003088 }
Kenny Root07438c82012-11-02 15:41:02 -07003089
3090 /*
3091 * We're the only thread in existence, so we're just going to process
3092 * Binder transaction as a single-threaded program.
3093 */
3094 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003095
3096 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003097 return 1;
3098}