blob: 384f15887d7f43b4f46b7b6d01871aa2b8961ea0 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker919cb2a2015-02-05 21:58:25 -080046#include <keymaster/soft_keymaster_device.h>
Shawn Willden9e5016a2015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Shawn Willden9e5016a2015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willdenef572b62015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Chad Brubaker94436162015-05-12 15:18:26 -0700155 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100156 P_GET = 1 << 1,
157 P_INSERT = 1 << 2,
158 P_DELETE = 1 << 3,
159 P_EXIST = 1 << 4,
Chad Brubaker94436162015-05-12 15:18:26 -0700160 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100161 P_RESET = 1 << 6,
162 P_PASSWORD = 1 << 7,
163 P_LOCK = 1 << 8,
164 P_UNLOCK = 1 << 9,
Chad Brubaker94436162015-05-12 15:18:26 -0700165 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100166 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,
Chad Brubaker94436162015-05-12 15:18:26 -0700171 P_ADD_AUTH = 1 << 16,
172 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700173} perm_t;
174
175static struct user_euid {
176 uid_t uid;
177 uid_t euid;
178} user_euids[] = {
179 {AID_VPN, AID_SYSTEM},
180 {AID_WIFI, AID_SYSTEM},
181 {AID_ROOT, AID_SYSTEM},
182};
183
Riley Spahneaabae92014-06-30 12:39:52 -0700184/* perm_labels associcated with keystore_key SELinux class verbs. */
185const char *perm_labels[] = {
Chad Brubaker94436162015-05-12 15:18:26 -0700186 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700187 "get",
188 "insert",
189 "delete",
190 "exist",
Chad Brubaker94436162015-05-12 15:18:26 -0700191 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700192 "reset",
193 "password",
194 "lock",
195 "unlock",
Chad Brubaker94436162015-05-12 15:18:26 -0700196 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700197 "sign",
198 "verify",
199 "grant",
200 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100201 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700202 "add_auth",
Chad Brubakerfd777e72015-05-12 10:43:10 -0700203 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700204};
205
Kenny Root07438c82012-11-02 15:41:02 -0700206static struct user_perm {
207 uid_t uid;
208 perm_t perms;
209} user_perms[] = {
210 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
211 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
212 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
213 {AID_ROOT, static_cast<perm_t>(P_GET) },
214};
215
Chad Brubaker94436162015-05-12 15:18:26 -0700216static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
217 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700218
Riley Spahneaabae92014-06-30 12:39:52 -0700219static char *tctx;
220static int ks_is_selinux_enabled;
221
222static const char *get_perm_label(perm_t perm) {
223 unsigned int index = ffs(perm);
224 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
225 return perm_labels[index - 1];
226 } else {
227 ALOGE("Keystore: Failed to retrieve permission label.\n");
228 abort();
229 }
230}
231
Kenny Root655b9582013-04-04 08:37:42 -0700232/**
233 * Returns the app ID (in the Android multi-user sense) for the current
234 * UNIX UID.
235 */
236static uid_t get_app_id(uid_t uid) {
237 return uid % AID_USER;
238}
239
240/**
241 * Returns the user ID (in the Android multi-user sense) for the current
242 * UNIX UID.
243 */
244static uid_t get_user_id(uid_t uid) {
245 return uid / AID_USER;
246}
247
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700248static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700249 if (!ks_is_selinux_enabled) {
250 return true;
251 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000252
Riley Spahneaabae92014-06-30 12:39:52 -0700253 char *sctx = NULL;
254 const char *selinux_class = "keystore_key";
255 const char *str_perm = get_perm_label(perm);
256
257 if (!str_perm) {
258 return false;
259 }
260
261 if (getpidcon(spid, &sctx) != 0) {
262 ALOGE("SELinux: Failed to get source pid context.\n");
263 return false;
264 }
265
266 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
267 NULL) == 0;
268 freecon(sctx);
269 return allowed;
270}
271
272static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700273 // All system users are equivalent for multi-user support.
274 if (get_app_id(uid) == AID_SYSTEM) {
275 uid = AID_SYSTEM;
276 }
277
Kenny Root07438c82012-11-02 15:41:02 -0700278 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
279 struct user_perm user = user_perms[i];
280 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700281 return (user.perms & perm) &&
282 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700283 }
284 }
285
Riley Spahneaabae92014-06-30 12:39:52 -0700286 return (DEFAULT_PERMS & perm) &&
287 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700288}
289
Kenny Root49468902013-03-19 13:41:33 -0700290/**
291 * Returns the UID that the callingUid should act as. This is here for
292 * legacy support of the WiFi and VPN systems and should be removed
293 * when WiFi can operate in its own namespace.
294 */
Kenny Root07438c82012-11-02 15:41:02 -0700295static uid_t get_keystore_euid(uid_t uid) {
296 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
297 struct user_euid user = user_euids[i];
298 if (user.uid == uid) {
299 return user.euid;
300 }
301 }
302
303 return uid;
304}
305
Kenny Root49468902013-03-19 13:41:33 -0700306/**
307 * Returns true if the callingUid is allowed to interact in the targetUid's
308 * namespace.
309 */
310static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700311 if (callingUid == targetUid) {
312 return true;
313 }
Kenny Root49468902013-03-19 13:41:33 -0700314 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
315 struct user_euid user = user_euids[i];
316 if (user.euid == callingUid && user.uid == targetUid) {
317 return true;
318 }
319 }
320
321 return false;
322}
323
Kenny Roota91203b2012-02-15 15:00:46 -0800324/* Here is the encoding of keys. This is necessary in order to allow arbitrary
325 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
326 * into two bytes. The first byte is one of [+-.] which represents the first
327 * two bits of the character. The second byte encodes the rest of the bits into
328 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
329 * that Base64 cannot be used here due to the need of prefix match on keys. */
330
Kenny Root655b9582013-04-04 08:37:42 -0700331static size_t encode_key_length(const android::String8& keyName) {
332 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
333 size_t length = keyName.length();
334 for (int i = length; i > 0; --i, ++in) {
335 if (*in < '0' || *in > '~') {
336 ++length;
337 }
338 }
339 return length;
340}
341
Kenny Root07438c82012-11-02 15:41:02 -0700342static int encode_key(char* out, const android::String8& keyName) {
343 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
344 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800345 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700346 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800347 *out = '+' + (*in >> 6);
348 *++out = '0' + (*in & 0x3F);
349 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700350 } else {
351 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800352 }
353 }
354 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800355 return length;
356}
357
Kenny Root07438c82012-11-02 15:41:02 -0700358/*
359 * Converts from the "escaped" format on disk to actual name.
360 * This will be smaller than the input string.
361 *
362 * Characters that should combine with the next at the end will be truncated.
363 */
364static size_t decode_key_length(const char* in, size_t length) {
365 size_t outLength = 0;
366
367 for (const char* end = in + length; in < end; in++) {
368 /* This combines with the next character. */
369 if (*in < '0' || *in > '~') {
370 continue;
371 }
372
373 outLength++;
374 }
375 return outLength;
376}
377
378static void decode_key(char* out, const char* in, size_t length) {
379 for (const char* end = in + length; in < end; in++) {
380 if (*in < '0' || *in > '~') {
381 /* Truncate combining characters at the end. */
382 if (in + 1 >= end) {
383 break;
384 }
385
386 *out = (*in++ - '+') << 6;
387 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800388 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700389 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800390 }
391 }
392 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800393}
394
395static size_t readFully(int fd, uint8_t* data, size_t size) {
396 size_t remaining = size;
397 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800398 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800399 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800400 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800401 }
402 data += n;
403 remaining -= n;
404 }
405 return size;
406}
407
408static size_t writeFully(int fd, uint8_t* data, size_t size) {
409 size_t remaining = size;
410 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800411 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
412 if (n < 0) {
413 ALOGW("write failed: %s", strerror(errno));
414 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800415 }
416 data += n;
417 remaining -= n;
418 }
419 return size;
420}
421
422class Entropy {
423public:
424 Entropy() : mRandom(-1) {}
425 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800426 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800427 close(mRandom);
428 }
429 }
430
431 bool open() {
432 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800433 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
434 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800435 ALOGE("open: %s: %s", randomDevice, strerror(errno));
436 return false;
437 }
438 return true;
439 }
440
Kenny Root51878182012-03-13 12:53:19 -0700441 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800442 return (readFully(mRandom, data, size) == size);
443 }
444
445private:
446 int mRandom;
447};
448
449/* Here is the file format. There are two parts in blob.value, the secret and
450 * the description. The secret is stored in ciphertext, and its original size
451 * can be found in blob.length. The description is stored after the secret in
452 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700453 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700454 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800455 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
456 * and decryptBlob(). Thus they should not be accessed from outside. */
457
Kenny Root822c3a92012-03-23 16:34:39 -0700458/* ** Note to future implementors of encryption: **
459 * Currently this is the construction:
460 * metadata || Enc(MD5(data) || data)
461 *
462 * This should be the construction used for encrypting if re-implementing:
463 *
464 * Derive independent keys for encryption and MAC:
465 * Kenc = AES_encrypt(masterKey, "Encrypt")
466 * Kmac = AES_encrypt(masterKey, "MAC")
467 *
468 * Store this:
469 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
470 * HMAC(Kmac, metadata || Enc(data))
471 */
Kenny Roota91203b2012-02-15 15:00:46 -0800472struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700473 uint8_t version;
474 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700475 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800476 uint8_t info;
477 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700478 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800479 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700480 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800481 int32_t length; // in network byte order when encrypted
482 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
483};
484
Kenny Root822c3a92012-03-23 16:34:39 -0700485typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700486 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700487 TYPE_GENERIC = 1,
488 TYPE_MASTER_KEY = 2,
489 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800490 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700491} BlobType;
492
Kenny Rootf9119d62013-04-03 09:22:15 -0700493static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700494
Kenny Roota91203b2012-02-15 15:00:46 -0800495class Blob {
496public:
Kenny Root07438c82012-11-02 15:41:02 -0700497 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
498 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800499 mBlob.length = valueLength;
500 memcpy(mBlob.value, value, valueLength);
501
502 mBlob.info = infoLength;
503 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700504
Kenny Root07438c82012-11-02 15:41:02 -0700505 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700506 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700507
Kenny Rootee8068b2013-10-07 09:49:15 -0700508 if (type == TYPE_MASTER_KEY) {
509 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
510 } else {
511 mBlob.flags = KEYSTORE_FLAG_NONE;
512 }
Kenny Roota91203b2012-02-15 15:00:46 -0800513 }
514
515 Blob(blob b) {
516 mBlob = b;
517 }
518
519 Blob() {}
520
Kenny Root51878182012-03-13 12:53:19 -0700521 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800522 return mBlob.value;
523 }
524
Kenny Root51878182012-03-13 12:53:19 -0700525 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800526 return mBlob.length;
527 }
528
Kenny Root51878182012-03-13 12:53:19 -0700529 const uint8_t* getInfo() const {
530 return mBlob.value + mBlob.length;
531 }
532
533 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800534 return mBlob.info;
535 }
536
Kenny Root822c3a92012-03-23 16:34:39 -0700537 uint8_t getVersion() const {
538 return mBlob.version;
539 }
540
Kenny Rootf9119d62013-04-03 09:22:15 -0700541 bool isEncrypted() const {
542 if (mBlob.version < 2) {
543 return true;
544 }
545
546 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
547 }
548
549 void setEncrypted(bool encrypted) {
550 if (encrypted) {
551 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
552 } else {
553 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
554 }
555 }
556
Kenny Root17208e02013-09-04 13:56:03 -0700557 bool isFallback() const {
558 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
559 }
560
561 void setFallback(bool fallback) {
562 if (fallback) {
563 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
564 } else {
565 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
566 }
567 }
568
Kenny Root822c3a92012-03-23 16:34:39 -0700569 void setVersion(uint8_t version) {
570 mBlob.version = version;
571 }
572
573 BlobType getType() const {
574 return BlobType(mBlob.type);
575 }
576
577 void setType(BlobType type) {
578 mBlob.type = uint8_t(type);
579 }
580
Kenny Rootf9119d62013-04-03 09:22:15 -0700581 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
582 ALOGV("writing blob %s", filename);
583 if (isEncrypted()) {
584 if (state != STATE_NO_ERROR) {
585 ALOGD("couldn't insert encrypted blob while not unlocked");
586 return LOCKED;
587 }
588
589 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
590 ALOGW("Could not read random data for: %s", filename);
591 return SYSTEM_ERROR;
592 }
Kenny Roota91203b2012-02-15 15:00:46 -0800593 }
594
595 // data includes the value and the value's length
596 size_t dataLength = mBlob.length + sizeof(mBlob.length);
597 // pad data to the AES_BLOCK_SIZE
598 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
599 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
600 // encrypted data includes the digest value
601 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
602 // move info after space for padding
603 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
604 // zero padding area
605 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
606
607 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800608
Kenny Rootf9119d62013-04-03 09:22:15 -0700609 if (isEncrypted()) {
610 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800611
Kenny Rootf9119d62013-04-03 09:22:15 -0700612 uint8_t vector[AES_BLOCK_SIZE];
613 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
614 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
615 aes_key, vector, AES_ENCRYPT);
616 }
617
Kenny Roota91203b2012-02-15 15:00:46 -0800618 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
619 size_t fileLength = encryptedLength + headerLength + mBlob.info;
620
621 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800622 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
623 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
624 if (out < 0) {
625 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800626 return SYSTEM_ERROR;
627 }
628 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
629 if (close(out) != 0) {
630 return SYSTEM_ERROR;
631 }
632 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800633 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800634 unlink(tmpFileName);
635 return SYSTEM_ERROR;
636 }
Kenny Root150ca932012-11-14 14:29:02 -0800637 if (rename(tmpFileName, filename) == -1) {
638 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
639 return SYSTEM_ERROR;
640 }
641 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800642 }
643
Kenny Rootf9119d62013-04-03 09:22:15 -0700644 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
645 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800646 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
647 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800648 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
649 }
650 // fileLength may be less than sizeof(mBlob) since the in
651 // memory version has extra padding to tolerate rounding up to
652 // the AES_BLOCK_SIZE
653 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
654 if (close(in) != 0) {
655 return SYSTEM_ERROR;
656 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700657
658 if (isEncrypted() && (state != STATE_NO_ERROR)) {
659 return LOCKED;
660 }
661
Kenny Roota91203b2012-02-15 15:00:46 -0800662 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
663 if (fileLength < headerLength) {
664 return VALUE_CORRUPTED;
665 }
666
667 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700668 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800669 return VALUE_CORRUPTED;
670 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700671
672 ssize_t digestedLength;
673 if (isEncrypted()) {
674 if (encryptedLength % AES_BLOCK_SIZE != 0) {
675 return VALUE_CORRUPTED;
676 }
677
678 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
679 mBlob.vector, AES_DECRYPT);
680 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
681 uint8_t computedDigest[MD5_DIGEST_LENGTH];
682 MD5(mBlob.digested, digestedLength, computedDigest);
683 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
684 return VALUE_CORRUPTED;
685 }
686 } else {
687 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800688 }
689
690 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
691 mBlob.length = ntohl(mBlob.length);
692 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
693 return VALUE_CORRUPTED;
694 }
695 if (mBlob.info != 0) {
696 // move info from after padding to after data
697 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
698 }
Kenny Root07438c82012-11-02 15:41:02 -0700699 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800700 }
701
702private:
703 struct blob mBlob;
704};
705
Kenny Root655b9582013-04-04 08:37:42 -0700706class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800707public:
Kenny Root655b9582013-04-04 08:37:42 -0700708 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
709 asprintf(&mUserDir, "user_%u", mUserId);
710 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
711 }
712
713 ~UserState() {
714 free(mUserDir);
715 free(mMasterKeyFile);
716 }
717
718 bool initialize() {
719 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
720 ALOGE("Could not create directory '%s'", mUserDir);
721 return false;
722 }
723
724 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800725 setState(STATE_LOCKED);
726 } else {
727 setState(STATE_UNINITIALIZED);
728 }
Kenny Root70e3a862012-02-15 17:20:23 -0800729
Kenny Root655b9582013-04-04 08:37:42 -0700730 return true;
731 }
732
733 uid_t getUserId() const {
734 return mUserId;
735 }
736
737 const char* getUserDirName() const {
738 return mUserDir;
739 }
740
741 const char* getMasterKeyFileName() const {
742 return mMasterKeyFile;
743 }
744
745 void setState(State state) {
746 mState = state;
747 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
748 mRetry = MAX_RETRY;
749 }
Kenny Roota91203b2012-02-15 15:00:46 -0800750 }
751
Kenny Root51878182012-03-13 12:53:19 -0700752 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800753 return mState;
754 }
755
Kenny Root51878182012-03-13 12:53:19 -0700756 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800757 return mRetry;
758 }
759
Kenny Root655b9582013-04-04 08:37:42 -0700760 void zeroizeMasterKeysInMemory() {
761 memset(mMasterKey, 0, sizeof(mMasterKey));
762 memset(mSalt, 0, sizeof(mSalt));
763 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
764 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800765 }
766
Chad Brubakereecdd122015-05-07 10:19:40 -0700767 bool deleteMasterKey() {
768 setState(STATE_UNINITIALIZED);
769 zeroizeMasterKeysInMemory();
770 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
771 }
772
Kenny Root655b9582013-04-04 08:37:42 -0700773 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
774 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800775 return SYSTEM_ERROR;
776 }
Kenny Root655b9582013-04-04 08:37:42 -0700777 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800778 if (response != NO_ERROR) {
779 return response;
780 }
781 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700782 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800783 }
784
Robin Lee4e865752014-08-19 17:37:55 +0100785 ResponseCode copyMasterKey(UserState* src) {
786 if (mState != STATE_UNINITIALIZED) {
787 return ::SYSTEM_ERROR;
788 }
789 if (src->getState() != STATE_NO_ERROR) {
790 return ::SYSTEM_ERROR;
791 }
792 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
793 setupMasterKeys();
794 return ::NO_ERROR;
795 }
796
Kenny Root655b9582013-04-04 08:37:42 -0700797 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800798 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
799 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
800 AES_KEY passwordAesKey;
801 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700802 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700803 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800804 }
805
Kenny Root655b9582013-04-04 08:37:42 -0700806 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
807 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800808 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800809 return SYSTEM_ERROR;
810 }
811
812 // we read the raw blob to just to get the salt to generate
813 // the AES key, then we create the Blob to use with decryptBlob
814 blob rawBlob;
815 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
816 if (close(in) != 0) {
817 return SYSTEM_ERROR;
818 }
819 // find salt at EOF if present, otherwise we have an old file
820 uint8_t* salt;
821 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
822 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
823 } else {
824 salt = NULL;
825 }
826 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
827 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
828 AES_KEY passwordAesKey;
829 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
830 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700831 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
832 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800833 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700834 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800835 }
836 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
837 // if salt was missing, generate one and write a new master key file with the salt.
838 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700839 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800840 return SYSTEM_ERROR;
841 }
Kenny Root655b9582013-04-04 08:37:42 -0700842 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800843 }
844 if (response == NO_ERROR) {
845 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
846 setupMasterKeys();
847 }
848 return response;
849 }
850 if (mRetry <= 0) {
851 reset();
852 return UNINITIALIZED;
853 }
854 --mRetry;
855 switch (mRetry) {
856 case 0: return WRONG_PASSWORD_0;
857 case 1: return WRONG_PASSWORD_1;
858 case 2: return WRONG_PASSWORD_2;
859 case 3: return WRONG_PASSWORD_3;
860 default: return WRONG_PASSWORD_3;
861 }
862 }
863
Kenny Root655b9582013-04-04 08:37:42 -0700864 AES_KEY* getEncryptionKey() {
865 return &mMasterKeyEncryption;
866 }
867
868 AES_KEY* getDecryptionKey() {
869 return &mMasterKeyDecryption;
870 }
871
Kenny Roota91203b2012-02-15 15:00:46 -0800872 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700873 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800874 if (!dir) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700875 // If the directory doesn't exist then nothing to do.
876 if (errno == ENOENT) {
877 return true;
878 }
Kenny Root655b9582013-04-04 08:37:42 -0700879 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800880 return false;
881 }
Kenny Root655b9582013-04-04 08:37:42 -0700882
883 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800884 while ((file = readdir(dir)) != NULL) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700885 // skip . and ..
886 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700887 continue;
888 }
889
890 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800891 }
892 closedir(dir);
893 return true;
894 }
895
Kenny Root655b9582013-04-04 08:37:42 -0700896private:
897 static const int MASTER_KEY_SIZE_BYTES = 16;
898 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
899
900 static const int MAX_RETRY = 4;
901 static const size_t SALT_SIZE = 16;
902
903 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
904 uint8_t* salt) {
905 size_t saltSize;
906 if (salt != NULL) {
907 saltSize = SALT_SIZE;
908 } else {
909 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
910 salt = (uint8_t*) "keystore";
911 // sizeof = 9, not strlen = 8
912 saltSize = sizeof("keystore");
913 }
914
915 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
916 saltSize, 8192, keySize, key);
917 }
918
919 bool generateSalt(Entropy* entropy) {
920 return entropy->generate_random_data(mSalt, sizeof(mSalt));
921 }
922
923 bool generateMasterKey(Entropy* entropy) {
924 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
925 return false;
926 }
927 if (!generateSalt(entropy)) {
928 return false;
929 }
930 return true;
931 }
932
933 void setupMasterKeys() {
934 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
935 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
936 setState(STATE_NO_ERROR);
937 }
938
939 uid_t mUserId;
940
941 char* mUserDir;
942 char* mMasterKeyFile;
943
944 State mState;
945 int8_t mRetry;
946
947 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
948 uint8_t mSalt[SALT_SIZE];
949
950 AES_KEY mMasterKeyEncryption;
951 AES_KEY mMasterKeyDecryption;
952};
953
954typedef struct {
955 uint32_t uid;
956 const uint8_t* filename;
957} grant_t;
958
959class KeyStore {
960public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800961 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700962 : mEntropy(entropy)
963 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800964 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700965 {
966 memset(&mMetaData, '\0', sizeof(mMetaData));
967 }
968
969 ~KeyStore() {
970 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
971 it != mGrants.end(); it++) {
972 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700973 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800974 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700975
976 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
977 it != mMasterKeys.end(); it++) {
978 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700979 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800980 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700981 }
982
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800983 /**
984 * Depending on the hardware keymaster version is this may return a
985 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
986 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
987 * be guarded by a check on the device's version.
988 */
989 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700990 return mDevice;
991 }
992
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800993 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800994 return mFallbackDevice;
995 }
996
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800997 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800998 return blob.isFallback() ? mFallbackDevice: mDevice;
999 }
1000
Kenny Root655b9582013-04-04 08:37:42 -07001001 ResponseCode initialize() {
1002 readMetaData();
1003 if (upgradeKeystore()) {
1004 writeMetaData();
1005 }
1006
1007 return ::NO_ERROR;
1008 }
1009
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001010 State getState(uid_t userId) {
1011 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001012 }
1013
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001014 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1015 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001016 return userState->initialize(pw, mEntropy);
1017 }
1018
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001019 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1020 UserState *userState = getUserState(dstUser);
1021 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001022 return userState->copyMasterKey(initState);
1023 }
1024
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001025 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1026 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001027 return userState->writeMasterKey(pw, mEntropy);
1028 }
1029
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001030 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1031 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001032 return userState->readMasterKey(pw, mEntropy);
1033 }
1034
1035 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001036 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001037 encode_key(encoded, keyName);
1038 return android::String8(encoded);
1039 }
1040
1041 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001042 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001043 encode_key(encoded, keyName);
1044 return android::String8::format("%u_%s", uid, encoded);
1045 }
1046
1047 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001048 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001049 encode_key(encoded, keyName);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001050 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001051 encoded);
1052 }
1053
Chad Brubakereecdd122015-05-07 10:19:40 -07001054 /*
1055 * Delete entries owned by userId. If keepUnencryptedEntries is true
1056 * then only encrypted entries will be removed, otherwise all entries will
1057 * be removed.
1058 */
1059 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001060 android::String8 prefix("");
1061 android::Vector<android::String16> aliases;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001062 UserState* userState = getUserState(userId);
Chad Brubaker94436162015-05-12 15:18:26 -07001063 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001064 return;
1065 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001066 for (uint32_t i = 0; i < aliases.size(); i++) {
1067 android::String8 filename(aliases[i]);
1068 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubakereecdd122015-05-07 10:19:40 -07001069 getKeyName(filename).string());
1070 bool shouldDelete = true;
1071 if (keepUnenryptedEntries) {
1072 Blob blob;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001073 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001074
Chad Brubakereecdd122015-05-07 10:19:40 -07001075 /* get can fail if the blob is encrypted and the state is
1076 * not unlocked, only skip deleting blobs that were loaded and
1077 * who are not encrypted. If there are blobs we fail to read for
1078 * other reasons err on the safe side and delete them since we
1079 * can't tell if they're encrypted.
1080 */
1081 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1082 }
1083 if (shouldDelete) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001084 del(filename, ::TYPE_ANY, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001085 }
1086 }
1087 if (!userState->deleteMasterKey()) {
1088 ALOGE("Failed to delete user %d's master key", userId);
1089 }
1090 if (!keepUnenryptedEntries) {
1091 if(!userState->reset()) {
1092 ALOGE("Failed to remove user %d's directory", userId);
1093 }
1094 }
Kenny Root655b9582013-04-04 08:37:42 -07001095 }
1096
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001097 bool isEmpty(uid_t userId) const {
1098 const UserState* userState = getUserState(userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001099 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001100 return true;
1101 }
1102
1103 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001104 if (!dir) {
1105 return true;
1106 }
Kenny Root31e27462014-09-10 11:28:03 -07001107
Kenny Roota91203b2012-02-15 15:00:46 -08001108 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001109 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001110 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001111 // We only care about files.
1112 if (file->d_type != DT_REG) {
1113 continue;
1114 }
1115
1116 // Skip anything that starts with a "."
1117 if (file->d_name[0] == '.') {
1118 continue;
1119 }
1120
Kenny Root31e27462014-09-10 11:28:03 -07001121 result = false;
1122 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001123 }
1124 closedir(dir);
1125 return result;
1126 }
1127
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001128 void lock(uid_t userId) {
1129 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001130 userState->zeroizeMasterKeysInMemory();
1131 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001132 }
1133
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001134 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1135 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001136 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1137 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001138 if (rc != NO_ERROR) {
1139 return rc;
1140 }
1141
1142 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001143 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001144 /* If we upgrade the key, we need to write it to disk again. Then
1145 * it must be read it again since the blob is encrypted each time
1146 * it's written.
1147 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001148 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1149 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001150 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1151 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001152 return rc;
1153 }
1154 }
Kenny Root822c3a92012-03-23 16:34:39 -07001155 }
1156
Kenny Root17208e02013-09-04 13:56:03 -07001157 /*
1158 * This will upgrade software-backed keys to hardware-backed keys when
1159 * the HAL for the device supports the newer key types.
1160 */
1161 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1162 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1163 && keyBlob->isFallback()) {
1164 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001165 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001166
1167 // The HAL allowed the import, reget the key to have the "fresh"
1168 // version.
1169 if (imported == NO_ERROR) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001170 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001171 }
1172 }
1173
Kenny Rootd53bc922013-03-21 14:10:15 -07001174 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001175 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1176 return KEY_NOT_FOUND;
1177 }
1178
1179 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001180 }
1181
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001182 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1183 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001184 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1185 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001186 }
1187
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001188 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001189 Blob keyBlob;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001190 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001191 if (rc != ::NO_ERROR) {
1192 return rc;
1193 }
1194
1195 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1196 // A device doesn't have to implement delete_keypair.
1197 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1198 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1199 rc = ::SYSTEM_ERROR;
1200 }
1201 }
1202 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001203 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1204 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1205 if (dev->delete_key) {
1206 keymaster_key_blob_t blob;
1207 blob.key_material = keyBlob.getValue();
1208 blob.key_material_size = keyBlob.getLength();
1209 dev->delete_key(dev, &blob);
1210 }
1211 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001212 if (rc != ::NO_ERROR) {
1213 return rc;
1214 }
1215
1216 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1217 }
1218
Chad Brubaker94436162015-05-12 15:18:26 -07001219 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001220 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001221
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001222 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001223 size_t n = prefix.length();
1224
1225 DIR* dir = opendir(userState->getUserDirName());
1226 if (!dir) {
1227 ALOGW("can't open directory for user: %s", strerror(errno));
1228 return ::SYSTEM_ERROR;
1229 }
1230
1231 struct dirent* file;
1232 while ((file = readdir(dir)) != NULL) {
1233 // We only care about files.
1234 if (file->d_type != DT_REG) {
1235 continue;
1236 }
1237
1238 // Skip anything that starts with a "."
1239 if (file->d_name[0] == '.') {
1240 continue;
1241 }
1242
1243 if (!strncmp(prefix.string(), file->d_name, n)) {
1244 const char* p = &file->d_name[n];
1245 size_t plen = strlen(p);
1246
1247 size_t extra = decode_key_length(p, plen);
1248 char *match = (char*) malloc(extra + 1);
1249 if (match != NULL) {
1250 decode_key(match, p, plen);
1251 matches->push(android::String16(match, extra));
1252 free(match);
1253 } else {
1254 ALOGW("could not allocate match of size %zd", extra);
1255 }
1256 }
1257 }
1258 closedir(dir);
1259 return ::NO_ERROR;
1260 }
1261
Kenny Root07438c82012-11-02 15:41:02 -07001262 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001263 const grant_t* existing = getGrant(filename, granteeUid);
1264 if (existing == NULL) {
1265 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001266 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001267 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001268 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001269 }
1270 }
1271
Kenny Root07438c82012-11-02 15:41:02 -07001272 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001273 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1274 it != mGrants.end(); it++) {
1275 grant_t* grant = *it;
1276 if (grant->uid == granteeUid
1277 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1278 mGrants.erase(it);
1279 return true;
1280 }
Kenny Root70e3a862012-02-15 17:20:23 -08001281 }
Kenny Root70e3a862012-02-15 17:20:23 -08001282 return false;
1283 }
1284
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001285 bool hasGrant(const char* filename, const uid_t uid) const {
1286 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001287 }
1288
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001289 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001290 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001291 uint8_t* data;
1292 size_t dataLength;
1293 int rc;
1294
1295 if (mDevice->import_keypair == NULL) {
1296 ALOGE("Keymaster doesn't support import!");
1297 return SYSTEM_ERROR;
1298 }
1299
Kenny Root17208e02013-09-04 13:56:03 -07001300 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001301 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001302 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001303 /*
1304 * Maybe the device doesn't support this type of key. Try to use the
1305 * software fallback keymaster implementation. This is a little bit
1306 * lazier than checking the PKCS#8 key type, but the software
1307 * implementation will do that anyway.
1308 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001309 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001310 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001311
1312 if (rc) {
1313 ALOGE("Error while importing keypair: %d", rc);
1314 return SYSTEM_ERROR;
1315 }
Kenny Root822c3a92012-03-23 16:34:39 -07001316 }
1317
1318 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1319 free(data);
1320
Kenny Rootf9119d62013-04-03 09:22:15 -07001321 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001322 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001323
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001324 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001325 }
1326
Kenny Root1b0e3932013-09-05 13:06:32 -07001327 bool isHardwareBacked(const android::String16& keyType) const {
1328 if (mDevice == NULL) {
1329 ALOGW("can't get keymaster device");
1330 return false;
1331 }
1332
1333 if (sRSAKeyType == keyType) {
1334 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1335 } else {
1336 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1337 && (mDevice->common.module->module_api_version
1338 >= KEYMASTER_MODULE_API_VERSION_0_2);
1339 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001340 }
1341
Kenny Root655b9582013-04-04 08:37:42 -07001342 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1343 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001344 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001345 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001346
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001347 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001348 if (responseCode == NO_ERROR) {
1349 return responseCode;
1350 }
1351
1352 // If this is one of the legacy UID->UID mappings, use it.
1353 uid_t euid = get_keystore_euid(uid);
1354 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001355 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001356 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001357 if (responseCode == NO_ERROR) {
1358 return responseCode;
1359 }
1360 }
1361
1362 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001363 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001364 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001365 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001366 if (end[0] != '_' || end[1] == 0) {
1367 return KEY_NOT_FOUND;
1368 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001369 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001370 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001371 if (!hasGrant(filepath8.string(), uid)) {
1372 return responseCode;
1373 }
1374
1375 // It is a granted key. Try to load it.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001376 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001377 }
1378
1379 /**
1380 * Returns any existing UserState or creates it if it doesn't exist.
1381 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001382 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001383 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1384 it != mMasterKeys.end(); it++) {
1385 UserState* state = *it;
1386 if (state->getUserId() == userId) {
1387 return state;
1388 }
1389 }
1390
1391 UserState* userState = new UserState(userId);
1392 if (!userState->initialize()) {
1393 /* There's not much we can do if initialization fails. Trying to
1394 * unlock the keystore for that user will fail as well, so any
1395 * subsequent request for this user will just return SYSTEM_ERROR.
1396 */
1397 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1398 }
1399 mMasterKeys.add(userState);
1400 return userState;
1401 }
1402
1403 /**
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001404 * Returns any existing UserState or creates it if it doesn't exist.
1405 */
1406 UserState* getUserStateByUid(uid_t uid) {
1407 uid_t userId = get_user_id(uid);
1408 return getUserState(userId);
1409 }
1410
1411 /**
Kenny Root655b9582013-04-04 08:37:42 -07001412 * Returns NULL if the UserState doesn't already exist.
1413 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001414 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001415 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1416 it != mMasterKeys.end(); it++) {
1417 UserState* state = *it;
1418 if (state->getUserId() == userId) {
1419 return state;
1420 }
1421 }
1422
1423 return NULL;
1424 }
1425
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001426 /**
1427 * Returns NULL if the UserState doesn't already exist.
1428 */
1429 const UserState* getUserStateByUid(uid_t uid) const {
1430 uid_t userId = get_user_id(uid);
1431 return getUserState(userId);
1432 }
1433
Kenny Roota91203b2012-02-15 15:00:46 -08001434private:
Kenny Root655b9582013-04-04 08:37:42 -07001435 static const char* sOldMasterKey;
1436 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001437 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001438 Entropy* mEntropy;
1439
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001440 keymaster1_device_t* mDevice;
1441 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001442
Kenny Root655b9582013-04-04 08:37:42 -07001443 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001444
Kenny Root655b9582013-04-04 08:37:42 -07001445 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001446
Kenny Root655b9582013-04-04 08:37:42 -07001447 typedef struct {
1448 uint32_t version;
1449 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001450
Kenny Root655b9582013-04-04 08:37:42 -07001451 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001452
Kenny Root655b9582013-04-04 08:37:42 -07001453 const grant_t* getGrant(const char* filename, uid_t uid) const {
1454 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1455 it != mGrants.end(); it++) {
1456 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001457 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001458 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001459 return grant;
1460 }
1461 }
Kenny Root70e3a862012-02-15 17:20:23 -08001462 return NULL;
1463 }
1464
Kenny Root822c3a92012-03-23 16:34:39 -07001465 /**
1466 * Upgrade code. This will upgrade the key from the current version
1467 * to whatever is newest.
1468 */
Kenny Root655b9582013-04-04 08:37:42 -07001469 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1470 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001471 bool updated = false;
1472 uint8_t version = oldVersion;
1473
1474 /* From V0 -> V1: All old types were unknown */
1475 if (version == 0) {
1476 ALOGV("upgrading to version 1 and setting type %d", type);
1477
1478 blob->setType(type);
1479 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001480 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001481 }
1482 version = 1;
1483 updated = true;
1484 }
1485
Kenny Rootf9119d62013-04-03 09:22:15 -07001486 /* From V1 -> V2: All old keys were encrypted */
1487 if (version == 1) {
1488 ALOGV("upgrading to version 2");
1489
1490 blob->setEncrypted(true);
1491 version = 2;
1492 updated = true;
1493 }
1494
Kenny Root822c3a92012-03-23 16:34:39 -07001495 /*
1496 * If we've updated, set the key blob to the right version
1497 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001498 */
Kenny Root822c3a92012-03-23 16:34:39 -07001499 if (updated) {
1500 ALOGV("updated and writing file %s", filename);
1501 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001502 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001503
1504 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001505 }
1506
1507 /**
1508 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1509 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1510 * Then it overwrites the original blob with the new blob
1511 * format that is returned from the keymaster.
1512 */
Kenny Root655b9582013-04-04 08:37:42 -07001513 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001514 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1515 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1516 if (b.get() == NULL) {
1517 ALOGE("Problem instantiating BIO");
1518 return SYSTEM_ERROR;
1519 }
1520
1521 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1522 if (pkey.get() == NULL) {
1523 ALOGE("Couldn't read old PEM file");
1524 return SYSTEM_ERROR;
1525 }
1526
1527 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1528 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1529 if (len < 0) {
1530 ALOGE("Couldn't measure PKCS#8 length");
1531 return SYSTEM_ERROR;
1532 }
1533
Kenny Root70c98892013-02-07 09:10:36 -08001534 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1535 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001536 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1537 ALOGE("Couldn't convert to PKCS#8");
1538 return SYSTEM_ERROR;
1539 }
1540
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001541 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001542 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001543 if (rc != NO_ERROR) {
1544 return rc;
1545 }
1546
Kenny Root655b9582013-04-04 08:37:42 -07001547 return get(filename, blob, TYPE_KEY_PAIR, uid);
1548 }
1549
1550 void readMetaData() {
1551 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1552 if (in < 0) {
1553 return;
1554 }
1555 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1556 if (fileLength != sizeof(mMetaData)) {
1557 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1558 sizeof(mMetaData));
1559 }
1560 close(in);
1561 }
1562
1563 void writeMetaData() {
1564 const char* tmpFileName = ".metadata.tmp";
1565 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1566 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1567 if (out < 0) {
1568 ALOGE("couldn't write metadata file: %s", strerror(errno));
1569 return;
1570 }
1571 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1572 if (fileLength != sizeof(mMetaData)) {
1573 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1574 sizeof(mMetaData));
1575 }
1576 close(out);
1577 rename(tmpFileName, sMetaDataFile);
1578 }
1579
1580 bool upgradeKeystore() {
1581 bool upgraded = false;
1582
1583 if (mMetaData.version == 0) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001584 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001585
1586 // Initialize first so the directory is made.
1587 userState->initialize();
1588
1589 // Migrate the old .masterkey file to user 0.
1590 if (access(sOldMasterKey, R_OK) == 0) {
1591 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1592 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1593 return false;
1594 }
1595 }
1596
1597 // Initialize again in case we had a key.
1598 userState->initialize();
1599
1600 // Try to migrate existing keys.
1601 DIR* dir = opendir(".");
1602 if (!dir) {
1603 // Give up now; maybe we can upgrade later.
1604 ALOGE("couldn't open keystore's directory; something is wrong");
1605 return false;
1606 }
1607
1608 struct dirent* file;
1609 while ((file = readdir(dir)) != NULL) {
1610 // We only care about files.
1611 if (file->d_type != DT_REG) {
1612 continue;
1613 }
1614
1615 // Skip anything that starts with a "."
1616 if (file->d_name[0] == '.') {
1617 continue;
1618 }
1619
1620 // Find the current file's user.
1621 char* end;
1622 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1623 if (end[0] != '_' || end[1] == 0) {
1624 continue;
1625 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001626 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001627 if (otherUser->getUserId() != 0) {
1628 unlinkat(dirfd(dir), file->d_name, 0);
1629 }
1630
1631 // Rename the file into user directory.
1632 DIR* otherdir = opendir(otherUser->getUserDirName());
1633 if (otherdir == NULL) {
1634 ALOGW("couldn't open user directory for rename");
1635 continue;
1636 }
1637 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1638 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1639 }
1640 closedir(otherdir);
1641 }
1642 closedir(dir);
1643
1644 mMetaData.version = 1;
1645 upgraded = true;
1646 }
1647
1648 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001649 }
Kenny Roota91203b2012-02-15 15:00:46 -08001650};
1651
Kenny Root655b9582013-04-04 08:37:42 -07001652const char* KeyStore::sOldMasterKey = ".masterkey";
1653const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001654
Kenny Root1b0e3932013-09-05 13:06:32 -07001655const android::String16 KeyStore::sRSAKeyType("RSA");
1656
Kenny Root07438c82012-11-02 15:41:02 -07001657namespace android {
1658class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1659public:
1660 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001661 : mKeyStore(keyStore),
1662 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001663 {
Kenny Roota91203b2012-02-15 15:00:46 -08001664 }
Kenny Roota91203b2012-02-15 15:00:46 -08001665
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001666 void binderDied(const wp<IBinder>& who) {
1667 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1668 for (auto token: operations) {
1669 abort(token);
1670 }
Kenny Root822c3a92012-03-23 16:34:39 -07001671 }
Kenny Roota91203b2012-02-15 15:00:46 -08001672
Chad Brubaker94436162015-05-12 15:18:26 -07001673 int32_t getState(int32_t userId) {
1674 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001675 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001676 }
Kenny Roota91203b2012-02-15 15:00:46 -08001677
Chad Brubaker94436162015-05-12 15:18:26 -07001678 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001679 }
1680
Kenny Root07438c82012-11-02 15:41:02 -07001681 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001682 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001683 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001684 }
Kenny Root07438c82012-11-02 15:41:02 -07001685
Chad Brubaker9489b792015-04-14 11:01:45 -07001686 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001687 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001688 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001689
Kenny Root655b9582013-04-04 08:37:42 -07001690 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001691 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001692 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001693 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001694 *item = NULL;
1695 *itemLength = 0;
1696 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001697 }
Kenny Roota91203b2012-02-15 15:00:46 -08001698
Kenny Root07438c82012-11-02 15:41:02 -07001699 *item = (uint8_t*) malloc(keyBlob.getLength());
1700 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1701 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001702
Kenny Root07438c82012-11-02 15:41:02 -07001703 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001704 }
1705
Kenny Rootf9119d62013-04-03 09:22:15 -07001706 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1707 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001708 targetUid = getEffectiveUid(targetUid);
1709 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1710 flags & KEYSTORE_FLAG_ENCRYPTED);
1711 if (result != ::NO_ERROR) {
1712 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001713 }
1714
Kenny Root07438c82012-11-02 15:41:02 -07001715 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001716 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001717
1718 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001719 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1720
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001721 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001722 }
1723
Kenny Root49468902013-03-19 13:41:33 -07001724 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001725 targetUid = getEffectiveUid(targetUid);
1726 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001727 return ::PERMISSION_DENIED;
1728 }
Kenny Root07438c82012-11-02 15:41:02 -07001729 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001730 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001731 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001732 }
1733
Kenny Root49468902013-03-19 13:41:33 -07001734 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001735 targetUid = getEffectiveUid(targetUid);
1736 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001737 return ::PERMISSION_DENIED;
1738 }
1739
Kenny Root07438c82012-11-02 15:41:02 -07001740 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001741 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001742
Kenny Root655b9582013-04-04 08:37:42 -07001743 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001744 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1745 }
1746 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001747 }
1748
Chad Brubaker94436162015-05-12 15:18:26 -07001749 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001750 targetUid = getEffectiveUid(targetUid);
Chad Brubaker94436162015-05-12 15:18:26 -07001751 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001752 return ::PERMISSION_DENIED;
1753 }
Kenny Root07438c82012-11-02 15:41:02 -07001754 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001755 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001756
Chad Brubaker94436162015-05-12 15:18:26 -07001757 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001758 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001759 }
Kenny Root07438c82012-11-02 15:41:02 -07001760 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001761 }
1762
Kenny Root07438c82012-11-02 15:41:02 -07001763 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001764 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001765 return ::PERMISSION_DENIED;
1766 }
1767
Chad Brubaker9489b792015-04-14 11:01:45 -07001768 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubakereecdd122015-05-07 10:19:40 -07001769 mKeyStore->resetUser(get_user_id(callingUid), false);
1770 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001771 }
1772
Chad Brubakereecdd122015-05-07 10:19:40 -07001773 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001774 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001775 return ::PERMISSION_DENIED;
1776 }
Kenny Root70e3a862012-02-15 17:20:23 -08001777
Kenny Root07438c82012-11-02 15:41:02 -07001778 const String8 password8(password);
Chad Brubakereecdd122015-05-07 10:19:40 -07001779 // Flush the auth token table to prevent stale tokens from sticking
1780 // around.
1781 mAuthTokenTable.Clear();
1782
1783 if (password.size() == 0) {
1784 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001785 mKeyStore->resetUser(userId, true);
Chad Brubakereecdd122015-05-07 10:19:40 -07001786 return ::NO_ERROR;
1787 } else {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001788 switch (mKeyStore->getState(userId)) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001789 case ::STATE_UNINITIALIZED: {
1790 // generate master key, encrypt with password, write to file,
1791 // initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001792 return mKeyStore->initializeUser(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001793 }
1794 case ::STATE_NO_ERROR: {
1795 // rewrite master key with new password.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001796 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001797 }
1798 case ::STATE_LOCKED: {
1799 ALOGE("Changing user %d's password while locked, clearing old encryption",
1800 userId);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001801 mKeyStore->resetUser(userId, true);
1802 return mKeyStore->initializeUser(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001803 }
Kenny Root07438c82012-11-02 15:41:02 -07001804 }
Chad Brubakereecdd122015-05-07 10:19:40 -07001805 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001806 }
Kenny Root70e3a862012-02-15 17:20:23 -08001807 }
1808
Chad Brubakerfd777e72015-05-12 10:43:10 -07001809 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1810 if (!checkBinderPermission(P_USER_CHANGED)) {
1811 return ::PERMISSION_DENIED;
1812 }
1813
1814 // Sanity check that the new user has an empty keystore.
1815 if (!mKeyStore->isEmpty(userId)) {
Chad Brubaker8df54382015-05-12 19:18:40 -07001816 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
Chad Brubakerfd777e72015-05-12 10:43:10 -07001817 }
1818 // Unconditionally clear the keystore, just to be safe.
1819 mKeyStore->resetUser(userId, false);
1820
1821 // If the user has a parent user then use the parent's
1822 // masterkey/password, otherwise there's nothing to do.
1823 if (parentId != -1) {
1824 return mKeyStore->copyMasterKey(parentId, userId);
1825 } else {
1826 return ::NO_ERROR;
1827 }
1828 }
1829
1830 int32_t onUserRemoved(int32_t userId) {
1831 if (!checkBinderPermission(P_USER_CHANGED)) {
1832 return ::PERMISSION_DENIED;
1833 }
1834
1835 mKeyStore->resetUser(userId, false);
1836 return ::NO_ERROR;
1837 }
1838
Chad Brubaker94436162015-05-12 15:18:26 -07001839 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001840 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001841 return ::PERMISSION_DENIED;
1842 }
Kenny Root70e3a862012-02-15 17:20:23 -08001843
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001844 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001845 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001846 ALOGD("calling lock in state: %d", state);
1847 return state;
1848 }
1849
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001850 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001851 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001852 }
1853
Chad Brubakereecdd122015-05-07 10:19:40 -07001854 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001855 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001856 return ::PERMISSION_DENIED;
1857 }
1858
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001859 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001860 if (state != ::STATE_LOCKED) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001861 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001862 return state;
1863 }
1864
1865 const String8 password8(pw);
Chad Brubakereecdd122015-05-07 10:19:40 -07001866 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001867 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001868 }
1869
Chad Brubaker94436162015-05-12 15:18:26 -07001870 bool isEmpty(int32_t userId) {
1871 if (!checkBinderPermission(P_IS_EMPTY)) {
1872 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001873 }
Kenny Root70e3a862012-02-15 17:20:23 -08001874
Chad Brubaker94436162015-05-12 15:18:26 -07001875 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001876 }
1877
Kenny Root96427ba2013-08-16 14:02:41 -07001878 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1879 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001880 targetUid = getEffectiveUid(targetUid);
1881 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1882 flags & KEYSTORE_FLAG_ENCRYPTED);
1883 if (result != ::NO_ERROR) {
1884 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001885 }
Kenny Root07438c82012-11-02 15:41:02 -07001886 uint8_t* data;
1887 size_t dataLength;
1888 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001889 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001890
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001891 const keymaster1_device_t* device = mKeyStore->getDevice();
1892 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001893 if (device == NULL) {
1894 return ::SYSTEM_ERROR;
1895 }
1896
1897 if (device->generate_keypair == NULL) {
1898 return ::SYSTEM_ERROR;
1899 }
1900
Kenny Root17208e02013-09-04 13:56:03 -07001901 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001902 keymaster_dsa_keygen_params_t dsa_params;
1903 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001904
Kenny Root96427ba2013-08-16 14:02:41 -07001905 if (keySize == -1) {
1906 keySize = DSA_DEFAULT_KEY_SIZE;
1907 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1908 || keySize > DSA_MAX_KEY_SIZE) {
1909 ALOGI("invalid key size %d", keySize);
1910 return ::SYSTEM_ERROR;
1911 }
1912 dsa_params.key_size = keySize;
1913
1914 if (args->size() == 3) {
1915 sp<KeystoreArg> gArg = args->itemAt(0);
1916 sp<KeystoreArg> pArg = args->itemAt(1);
1917 sp<KeystoreArg> qArg = args->itemAt(2);
1918
1919 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1920 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1921 dsa_params.generator_len = gArg->size();
1922
1923 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1924 dsa_params.prime_p_len = pArg->size();
1925
1926 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1927 dsa_params.prime_q_len = qArg->size();
1928 } else {
1929 ALOGI("not all DSA parameters were read");
1930 return ::SYSTEM_ERROR;
1931 }
1932 } else if (args->size() != 0) {
1933 ALOGI("DSA args must be 3");
1934 return ::SYSTEM_ERROR;
1935 }
1936
Kenny Root1d448c02013-11-21 10:36:53 -08001937 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001938 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1939 } else {
1940 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001941 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1942 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001943 }
1944 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001945 keymaster_ec_keygen_params_t ec_params;
1946 memset(&ec_params, '\0', sizeof(ec_params));
1947
1948 if (keySize == -1) {
1949 keySize = EC_DEFAULT_KEY_SIZE;
1950 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1951 ALOGI("invalid key size %d", keySize);
1952 return ::SYSTEM_ERROR;
1953 }
1954 ec_params.field_size = keySize;
1955
Kenny Root1d448c02013-11-21 10:36:53 -08001956 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001957 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1958 } else {
1959 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001960 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001961 }
Kenny Root96427ba2013-08-16 14:02:41 -07001962 } else if (keyType == EVP_PKEY_RSA) {
1963 keymaster_rsa_keygen_params_t rsa_params;
1964 memset(&rsa_params, '\0', sizeof(rsa_params));
1965 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1966
1967 if (keySize == -1) {
1968 keySize = RSA_DEFAULT_KEY_SIZE;
1969 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1970 ALOGI("invalid key size %d", keySize);
1971 return ::SYSTEM_ERROR;
1972 }
1973 rsa_params.modulus_size = keySize;
1974
1975 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001976 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001977 return ::SYSTEM_ERROR;
1978 } else if (args->size() == 1) {
1979 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1980 if (pubExpBlob != NULL) {
1981 Unique_BIGNUM pubExpBn(
1982 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1983 pubExpBlob->size(), NULL));
1984 if (pubExpBn.get() == NULL) {
1985 ALOGI("Could not convert public exponent to BN");
1986 return ::SYSTEM_ERROR;
1987 }
1988 unsigned long pubExp = BN_get_word(pubExpBn.get());
1989 if (pubExp == 0xFFFFFFFFL) {
1990 ALOGI("cannot represent public exponent as a long value");
1991 return ::SYSTEM_ERROR;
1992 }
1993 rsa_params.public_exponent = pubExp;
1994 }
1995 }
1996
1997 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1998 } else {
1999 ALOGW("Unsupported key type %d", keyType);
2000 rc = -1;
2001 }
2002
Kenny Root07438c82012-11-02 15:41:02 -07002003 if (rc) {
2004 return ::SYSTEM_ERROR;
2005 }
2006
Kenny Root655b9582013-04-04 08:37:42 -07002007 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07002008 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002009
2010 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2011 free(data);
2012
Kenny Rootee8068b2013-10-07 09:49:15 -07002013 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002014 keyBlob.setFallback(isFallback);
2015
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002016 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08002017 }
2018
Kenny Rootf9119d62013-04-03 09:22:15 -07002019 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2020 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002021 targetUid = getEffectiveUid(targetUid);
2022 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2023 flags & KEYSTORE_FLAG_ENCRYPTED);
2024 if (result != ::NO_ERROR) {
2025 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002026 }
Kenny Root07438c82012-11-02 15:41:02 -07002027 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002028 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002029
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002030 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2031 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002032 }
2033
Kenny Root07438c82012-11-02 15:41:02 -07002034 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2035 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002036 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002037 return ::PERMISSION_DENIED;
2038 }
Kenny Root07438c82012-11-02 15:41:02 -07002039
Chad Brubaker9489b792015-04-14 11:01:45 -07002040 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002041 Blob keyBlob;
2042 String8 name8(name);
2043
Kenny Rootd38a0b02013-02-13 12:59:14 -08002044 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002045
Kenny Root655b9582013-04-04 08:37:42 -07002046 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002047 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002048 if (responseCode != ::NO_ERROR) {
2049 return responseCode;
2050 }
2051
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002052 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002053 if (device == NULL) {
2054 ALOGE("no keymaster device; cannot sign");
2055 return ::SYSTEM_ERROR;
2056 }
2057
2058 if (device->sign_data == NULL) {
2059 ALOGE("device doesn't implement signing");
2060 return ::SYSTEM_ERROR;
2061 }
2062
2063 keymaster_rsa_sign_params_t params;
2064 params.digest_type = DIGEST_NONE;
2065 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002066 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002067 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002068 if (rc) {
2069 ALOGW("device couldn't sign data");
2070 return ::SYSTEM_ERROR;
2071 }
2072
2073 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002074 }
2075
Kenny Root07438c82012-11-02 15:41:02 -07002076 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2077 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002078 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002079 return ::PERMISSION_DENIED;
2080 }
Kenny Root70e3a862012-02-15 17:20:23 -08002081
Chad Brubaker9489b792015-04-14 11:01:45 -07002082 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002083 Blob keyBlob;
2084 String8 name8(name);
2085 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002086
Kenny Root655b9582013-04-04 08:37:42 -07002087 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002088 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002089 if (responseCode != ::NO_ERROR) {
2090 return responseCode;
2091 }
Kenny Root70e3a862012-02-15 17:20:23 -08002092
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002093 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002094 if (device == NULL) {
2095 return ::SYSTEM_ERROR;
2096 }
Kenny Root70e3a862012-02-15 17:20:23 -08002097
Kenny Root07438c82012-11-02 15:41:02 -07002098 if (device->verify_data == NULL) {
2099 return ::SYSTEM_ERROR;
2100 }
Kenny Root70e3a862012-02-15 17:20:23 -08002101
Kenny Root07438c82012-11-02 15:41:02 -07002102 keymaster_rsa_sign_params_t params;
2103 params.digest_type = DIGEST_NONE;
2104 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002105
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002106 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2107 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002108 if (rc) {
2109 return ::SYSTEM_ERROR;
2110 } else {
2111 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002112 }
2113 }
Kenny Root07438c82012-11-02 15:41:02 -07002114
2115 /*
2116 * TODO: The abstraction between things stored in hardware and regular blobs
2117 * of data stored on the filesystem should be moved down to keystore itself.
2118 * Unfortunately the Java code that calls this has naming conventions that it
2119 * knows about. Ideally keystore shouldn't be used to store random blobs of
2120 * data.
2121 *
2122 * Until that happens, it's necessary to have a separate "get_pubkey" and
2123 * "del_key" since the Java code doesn't really communicate what it's
2124 * intentions are.
2125 */
2126 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002127 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002128 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002129 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002130 return ::PERMISSION_DENIED;
2131 }
Kenny Root07438c82012-11-02 15:41:02 -07002132
Kenny Root07438c82012-11-02 15:41:02 -07002133 Blob keyBlob;
2134 String8 name8(name);
2135
Kenny Rootd38a0b02013-02-13 12:59:14 -08002136 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002137
Kenny Root655b9582013-04-04 08:37:42 -07002138 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002139 TYPE_KEY_PAIR);
2140 if (responseCode != ::NO_ERROR) {
2141 return responseCode;
2142 }
2143
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002144 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002145 if (device == NULL) {
2146 return ::SYSTEM_ERROR;
2147 }
2148
2149 if (device->get_keypair_public == NULL) {
2150 ALOGE("device has no get_keypair_public implementation!");
2151 return ::SYSTEM_ERROR;
2152 }
2153
Kenny Root17208e02013-09-04 13:56:03 -07002154 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002155 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2156 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002157 if (rc) {
2158 return ::SYSTEM_ERROR;
2159 }
2160
2161 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002162 }
Kenny Root07438c82012-11-02 15:41:02 -07002163
Kenny Root07438c82012-11-02 15:41:02 -07002164 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002165 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002166 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2167 if (result != ::NO_ERROR) {
2168 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002169 }
2170
2171 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002172 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002173
Kenny Root655b9582013-04-04 08:37:42 -07002174 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002175 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2176 }
2177
Kenny Root655b9582013-04-04 08:37:42 -07002178 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002179 return ::NO_ERROR;
2180 }
2181
2182 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002183 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002184 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2185 if (result != ::NO_ERROR) {
2186 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002187 }
2188
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) {
Kenny Root07438c82012-11-02 15:41:02 -07002193 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2194 }
2195
Kenny Root655b9582013-04-04 08:37:42 -07002196 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002197 }
2198
2199 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002200 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002201 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002202 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002203 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002204 }
Kenny Root07438c82012-11-02 15:41:02 -07002205
2206 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002207 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002208
Kenny Root655b9582013-04-04 08:37:42 -07002209 if (access(filename.string(), R_OK) == -1) {
2210 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002211 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002212 }
2213
Kenny Root655b9582013-04-04 08:37:42 -07002214 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002215 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002216 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002217 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002218 }
2219
2220 struct stat s;
2221 int ret = fstat(fd, &s);
2222 close(fd);
2223 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002224 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002225 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002226 }
2227
Kenny Root36a9e232013-02-04 14:24:15 -08002228 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002229 }
2230
Kenny Rootd53bc922013-03-21 14:10:15 -07002231 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2232 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002233 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002234 pid_t spid = IPCThreadState::self()->getCallingPid();
2235 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002236 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002237 return -1L;
2238 }
2239
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002240 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002241 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002242 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002243 return state;
2244 }
2245
Kenny Rootd53bc922013-03-21 14:10:15 -07002246 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2247 srcUid = callingUid;
2248 } else if (!is_granted_to(callingUid, srcUid)) {
2249 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002250 return ::PERMISSION_DENIED;
2251 }
2252
Kenny Rootd53bc922013-03-21 14:10:15 -07002253 if (destUid == -1) {
2254 destUid = callingUid;
2255 }
2256
2257 if (srcUid != destUid) {
2258 if (static_cast<uid_t>(srcUid) != callingUid) {
2259 ALOGD("can only duplicate from caller to other or to same uid: "
2260 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2261 return ::PERMISSION_DENIED;
2262 }
2263
2264 if (!is_granted_to(callingUid, destUid)) {
2265 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2266 return ::PERMISSION_DENIED;
2267 }
2268 }
2269
2270 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002271 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002272
Kenny Rootd53bc922013-03-21 14:10:15 -07002273 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002274 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002275
Kenny Root655b9582013-04-04 08:37:42 -07002276 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2277 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002278 return ::SYSTEM_ERROR;
2279 }
2280
Kenny Rootd53bc922013-03-21 14:10:15 -07002281 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002282 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002283 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 if (responseCode != ::NO_ERROR) {
2285 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002286 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002287
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002288 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002289 }
2290
Kenny Root1b0e3932013-09-05 13:06:32 -07002291 int32_t is_hardware_backed(const String16& keyType) {
2292 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002293 }
2294
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002295 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002296 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubaker01771ae2015-05-01 10:21:27 -07002297 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002298 return ::PERMISSION_DENIED;
2299 }
2300
Robin Lee4b84fdc2014-09-24 11:56:57 +01002301 String8 prefix = String8::format("%u_", targetUid);
2302 Vector<String16> aliases;
Chad Brubaker94436162015-05-12 15:18:26 -07002303 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002304 return ::SYSTEM_ERROR;
2305 }
2306
Robin Lee4b84fdc2014-09-24 11:56:57 +01002307 for (uint32_t i = 0; i < aliases.size(); i++) {
2308 String8 name8(aliases[i]);
2309 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002310 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002311 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002312 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002313 }
2314
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002315 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2316 const keymaster1_device_t* device = mKeyStore->getDevice();
2317 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2318 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2319 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2320 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2321 device->add_rng_entropy != NULL) {
2322 devResult = device->add_rng_entropy(device, data, dataLength);
2323 }
2324 if (fallback->add_rng_entropy) {
2325 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2326 }
2327 if (devResult) {
2328 return devResult;
2329 }
2330 if (fallbackResult) {
2331 return fallbackResult;
2332 }
2333 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002334 }
2335
Chad Brubaker17d68b92015-02-05 22:04:16 -08002336 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002337 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2338 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002339 uid = getEffectiveUid(uid);
2340 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2341 flags & KEYSTORE_FLAG_ENCRYPTED);
2342 if (rc != ::NO_ERROR) {
2343 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002344 }
2345
Chad Brubaker9489b792015-04-14 11:01:45 -07002346 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002347 bool isFallback = false;
2348 keymaster_key_blob_t blob;
2349 keymaster_key_characteristics_t *out = NULL;
2350
2351 const keymaster1_device_t* device = mKeyStore->getDevice();
2352 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2353 if (device == NULL) {
2354 return ::SYSTEM_ERROR;
2355 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002356 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002357 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2358 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002359 if (!entropy) {
2360 rc = KM_ERROR_OK;
2361 } else if (device->add_rng_entropy) {
2362 rc = device->add_rng_entropy(device, entropy, entropyLength);
2363 } else {
2364 rc = KM_ERROR_UNIMPLEMENTED;
2365 }
2366 if (rc == KM_ERROR_OK) {
2367 rc = device->generate_key(device, params.params.data(), params.params.size(),
2368 &blob, &out);
2369 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002370 }
2371 // If the HW device didn't support generate_key or generate_key failed
2372 // fall back to the software implementation.
2373 if (rc && fallback->generate_key != NULL) {
2374 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002375 if (!entropy) {
2376 rc = KM_ERROR_OK;
2377 } else if (fallback->add_rng_entropy) {
2378 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2379 } else {
2380 rc = KM_ERROR_UNIMPLEMENTED;
2381 }
2382 if (rc == KM_ERROR_OK) {
2383 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2384 &blob,
2385 &out);
2386 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002387 }
2388
2389 if (out) {
2390 if (outCharacteristics) {
2391 outCharacteristics->characteristics = *out;
2392 } else {
2393 keymaster_free_characteristics(out);
2394 }
2395 free(out);
2396 }
2397
2398 if (rc) {
2399 return rc;
2400 }
2401
2402 String8 name8(name);
2403 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2404
2405 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2406 keyBlob.setFallback(isFallback);
2407 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2408
2409 free(const_cast<uint8_t*>(blob.key_material));
2410
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002411 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002412 }
2413
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002414 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002415 const keymaster_blob_t* clientId,
2416 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002417 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002418 if (!outCharacteristics) {
2419 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2420 }
2421
2422 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2423
2424 Blob keyBlob;
2425 String8 name8(name);
2426 int rc;
2427
2428 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2429 TYPE_KEYMASTER_10);
2430 if (responseCode != ::NO_ERROR) {
2431 return responseCode;
2432 }
2433 keymaster_key_blob_t key;
2434 key.key_material_size = keyBlob.getLength();
2435 key.key_material = keyBlob.getValue();
2436 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2437 keymaster_key_characteristics_t *out = NULL;
2438 if (!dev->get_key_characteristics) {
2439 ALOGW("device does not implement get_key_characteristics");
2440 return KM_ERROR_UNIMPLEMENTED;
2441 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002442 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002443 if (out) {
2444 outCharacteristics->characteristics = *out;
2445 free(out);
2446 }
2447 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002448 }
2449
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002450 int32_t importKey(const String16& name, const KeymasterArguments& params,
2451 keymaster_key_format_t format, const uint8_t *keyData,
2452 size_t keyLength, int uid, int flags,
2453 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002454 uid = getEffectiveUid(uid);
2455 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2456 flags & KEYSTORE_FLAG_ENCRYPTED);
2457 if (rc != ::NO_ERROR) {
2458 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002459 }
2460
Chad Brubaker9489b792015-04-14 11:01:45 -07002461 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002462 bool isFallback = false;
2463 keymaster_key_blob_t blob;
2464 keymaster_key_characteristics_t *out = NULL;
2465
2466 const keymaster1_device_t* device = mKeyStore->getDevice();
2467 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2468 if (device == NULL) {
2469 return ::SYSTEM_ERROR;
2470 }
2471 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2472 device->import_key != NULL) {
2473 rc = device->import_key(device, params.params.data(), params.params.size(),
2474 format, keyData, keyLength, &blob, &out);
2475 }
2476 if (rc && fallback->import_key != NULL) {
2477 isFallback = true;
2478 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2479 format, keyData, keyLength, &blob, &out);
2480 }
2481 if (out) {
2482 if (outCharacteristics) {
2483 outCharacteristics->characteristics = *out;
2484 } else {
2485 keymaster_free_characteristics(out);
2486 }
2487 free(out);
2488 }
2489 if (rc) {
2490 return rc;
2491 }
2492
2493 String8 name8(name);
2494 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2495
2496 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2497 keyBlob.setFallback(isFallback);
2498 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2499
2500 free((void*) blob.key_material);
2501
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002502 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002503 }
2504
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002505 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002506 const keymaster_blob_t* clientId,
2507 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002508
2509 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2510
2511 Blob keyBlob;
2512 String8 name8(name);
2513 int rc;
2514
2515 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2516 TYPE_KEYMASTER_10);
2517 if (responseCode != ::NO_ERROR) {
2518 result->resultCode = responseCode;
2519 return;
2520 }
2521 keymaster_key_blob_t key;
2522 key.key_material_size = keyBlob.getLength();
2523 key.key_material = keyBlob.getValue();
2524 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2525 if (!dev->export_key) {
2526 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2527 return;
2528 }
2529 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002530 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002531 &ptr, &result->dataLength);
2532 result->exportData.reset(ptr);
2533 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002534 }
2535
Chad Brubakerad6514a2015-04-09 14:00:26 -07002536
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002537 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002538 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2539 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002540 if (!result || !outParams) {
2541 ALOGE("Unexpected null arguments to begin()");
2542 return;
2543 }
2544 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2545 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2546 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2547 result->resultCode = ::PERMISSION_DENIED;
2548 return;
2549 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002550 if (!checkAllowedOperationParams(params.params)) {
2551 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2552 return;
2553 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002554 Blob keyBlob;
2555 String8 name8(name);
2556 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2557 TYPE_KEYMASTER_10);
2558 if (responseCode != ::NO_ERROR) {
2559 result->resultCode = responseCode;
2560 return;
2561 }
2562 keymaster_key_blob_t key;
2563 key.key_material_size = keyBlob.getLength();
2564 key.key_material = keyBlob.getValue();
2565 keymaster_key_param_t* out;
2566 size_t outSize;
2567 keymaster_operation_handle_t handle;
2568 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002569 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002570 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002571 Unique_keymaster_key_characteristics characteristics;
2572 characteristics.reset(new keymaster_key_characteristics_t);
2573 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2574 if (err) {
2575 result->resultCode = err;
2576 return;
2577 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002578 const hw_auth_token_t* authToken = NULL;
2579 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002580 /*failOnTokenMissing*/ false);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002581 // If per-operation auth is needed we need to begin the operation and
2582 // the client will need to authorize that operation before calling
2583 // update. Any other auth issues stop here.
2584 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2585 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002586 return;
2587 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002588 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002589 // Add entropy to the device first.
2590 if (entropy) {
2591 if (dev->add_rng_entropy) {
2592 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2593 } else {
2594 err = KM_ERROR_UNIMPLEMENTED;
2595 }
2596 if (err) {
2597 result->resultCode = err;
2598 return;
2599 }
2600 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002601 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2602 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002603
2604 // If there are too many operations abort the oldest operation that was
2605 // started as pruneable and try again.
2606 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2607 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2608 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2609 if (abort(oldest) != ::NO_ERROR) {
2610 break;
2611 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002612 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002613 &handle);
2614 }
2615 if (err) {
2616 result->resultCode = err;
2617 return;
2618 }
2619 if (out) {
2620 outParams->params.assign(out, out + outSize);
2621 free(out);
2622 }
2623
Chad Brubakerad6514a2015-04-09 14:00:26 -07002624 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2625 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002626 pruneable);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002627 if (authToken) {
2628 mOperationMap.setOperationAuthToken(operationToken, authToken);
2629 }
2630 // Return the authentication lookup result. If this is a per operation
2631 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2632 // application should get an auth token using the handle before the
2633 // first call to update, which will fail if keystore hasn't received the
2634 // auth token.
2635 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002636 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002637 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002638 }
2639
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002640 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2641 size_t dataLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002642 if (!checkAllowedOperationParams(params.params)) {
2643 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2644 return;
2645 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002646 const keymaster1_device_t* dev;
2647 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002648 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002649 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2650 return;
2651 }
2652 uint8_t* output_buf = NULL;
2653 size_t output_length = 0;
2654 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002655 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002656 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2657 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002658 result->resultCode = authResult;
2659 return;
2660 }
2661 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2662 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002663 result->data.reset(output_buf);
2664 result->dataLength = output_length;
2665 result->inputConsumed = consumed;
2666 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002667 }
2668
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002669 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker8cfb8ac2015-05-29 12:30:19 -07002670 const uint8_t* signature, size_t signatureLength,
2671 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002672 if (!checkAllowedOperationParams(params.params)) {
2673 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2674 return;
2675 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002676 const keymaster1_device_t* dev;
2677 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002678 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002679 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2680 return;
2681 }
2682 uint8_t* output_buf = NULL;
2683 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002684 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-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 }
Chad Brubaker8cfb8ac2015-05-29 12:30:19 -07002690 keymaster_error_t err;
2691 if (entropy) {
2692 if (dev->add_rng_entropy) {
2693 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2694 } else {
2695 err = KM_ERROR_UNIMPLEMENTED;
2696 }
2697 if (err) {
2698 result->resultCode = err;
2699 return;
2700 }
2701 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002702
Chad Brubaker8cfb8ac2015-05-29 12:30:19 -07002703 err = dev->finish(dev, handle, opParams.data(), opParams.size(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002704 signature, signatureLength, &output_buf,
2705 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002706 // Remove the operation regardless of the result
2707 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002708 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002709 result->data.reset(output_buf);
2710 result->dataLength = output_length;
2711 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002712 }
2713
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002714 int32_t abort(const sp<IBinder>& token) {
2715 const keymaster1_device_t* dev;
2716 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002717 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002718 return KM_ERROR_INVALID_OPERATION_HANDLE;
2719 }
2720 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002721 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002722 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002723 rc = KM_ERROR_UNIMPLEMENTED;
2724 } else {
2725 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002726 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002727 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002728 if (rc) {
2729 return rc;
2730 }
2731 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002732 }
2733
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002734 bool isOperationAuthorized(const sp<IBinder>& token) {
2735 const keymaster1_device_t* dev;
2736 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002737 const keymaster_key_characteristics_t* characteristics;
2738 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002739 return false;
2740 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002741 const hw_auth_token_t* authToken = NULL;
2742 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002743 std::vector<keymaster_key_param_t> ignored;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002744 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2745 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002746 }
2747
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002748 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002749 if (!checkBinderPermission(P_ADD_AUTH)) {
2750 ALOGW("addAuthToken: permission denied for %d",
2751 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002752 return ::PERMISSION_DENIED;
2753 }
2754 if (length != sizeof(hw_auth_token_t)) {
2755 return KM_ERROR_INVALID_ARGUMENT;
2756 }
2757 hw_auth_token_t* authToken = new hw_auth_token_t;
2758 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2759 // The table takes ownership of authToken.
2760 mAuthTokenTable.AddAuthenticationToken(authToken);
2761 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002762 }
2763
Kenny Root07438c82012-11-02 15:41:02 -07002764private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002765 static const int32_t UID_SELF = -1;
2766
2767 /**
2768 * Get the effective target uid for a binder operation that takes an
2769 * optional uid as the target.
2770 */
2771 inline uid_t getEffectiveUid(int32_t targetUid) {
2772 if (targetUid == UID_SELF) {
2773 return IPCThreadState::self()->getCallingUid();
2774 }
2775 return static_cast<uid_t>(targetUid);
2776 }
2777
2778 /**
2779 * Check if the caller of the current binder method has the required
2780 * permission and if acting on other uids the grants to do so.
2781 */
2782 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2783 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2784 pid_t spid = IPCThreadState::self()->getCallingPid();
2785 if (!has_permission(callingUid, permission, spid)) {
2786 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2787 return false;
2788 }
2789 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2790 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2791 return false;
2792 }
2793 return true;
2794 }
2795
2796 /**
2797 * Check if the caller of the current binder method has the required
Chad Brubaker01771ae2015-05-01 10:21:27 -07002798 * permission and the target uid is the caller or the caller is system.
2799 */
2800 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2801 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2802 pid_t spid = IPCThreadState::self()->getCallingPid();
2803 if (!has_permission(callingUid, permission, spid)) {
2804 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2805 return false;
2806 }
2807 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2808 }
2809
2810 /**
2811 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002812 * permission or the target of the operation is the caller's uid. This is
2813 * for operation where the permission is only for cross-uid activity and all
2814 * uids are allowed to act on their own (ie: clearing all entries for a
2815 * given uid).
2816 */
2817 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2818 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2819 if (getEffectiveUid(targetUid) == callingUid) {
2820 return true;
2821 } else {
2822 return checkBinderPermission(permission, targetUid);
2823 }
2824 }
2825
2826 /**
2827 * Helper method to check that the caller has the required permission as
2828 * well as the keystore is in the unlocked state if checkUnlocked is true.
2829 *
2830 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2831 * otherwise the state of keystore when not unlocked and checkUnlocked is
2832 * true.
2833 */
2834 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2835 bool checkUnlocked = true) {
2836 if (!checkBinderPermission(permission, targetUid)) {
2837 return ::PERMISSION_DENIED;
2838 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002839 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002840 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2841 return state;
2842 }
2843
2844 return ::NO_ERROR;
2845
2846 }
2847
Kenny Root9d45d1c2013-02-14 10:32:30 -08002848 inline bool isKeystoreUnlocked(State state) {
2849 switch (state) {
2850 case ::STATE_NO_ERROR:
2851 return true;
2852 case ::STATE_UNINITIALIZED:
2853 case ::STATE_LOCKED:
2854 return false;
2855 }
2856 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002857 }
2858
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002859 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002860 const int32_t device_api = device->common.module->module_api_version;
2861 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2862 switch (keyType) {
2863 case TYPE_RSA:
2864 case TYPE_DSA:
2865 case TYPE_EC:
2866 return true;
2867 default:
2868 return false;
2869 }
2870 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2871 switch (keyType) {
2872 case TYPE_RSA:
2873 return true;
2874 case TYPE_DSA:
2875 return device->flags & KEYMASTER_SUPPORTS_DSA;
2876 case TYPE_EC:
2877 return device->flags & KEYMASTER_SUPPORTS_EC;
2878 default:
2879 return false;
2880 }
2881 } else {
2882 return keyType == TYPE_RSA;
2883 }
2884 }
2885
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002886 /**
2887 * Check that all keymaster_key_param_t's provided by the application are
2888 * allowed. Any parameter that keystore adds itself should be disallowed here.
2889 */
2890 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2891 for (auto param: params) {
2892 switch (param.tag) {
2893 case KM_TAG_AUTH_TOKEN:
2894 return false;
2895 default:
2896 break;
2897 }
2898 }
2899 return true;
2900 }
2901
2902 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2903 const keymaster1_device_t* dev,
2904 const std::vector<keymaster_key_param_t>& params,
2905 keymaster_key_characteristics_t* out) {
2906 UniquePtr<keymaster_blob_t> appId;
2907 UniquePtr<keymaster_blob_t> appData;
2908 for (auto param : params) {
2909 if (param.tag == KM_TAG_APPLICATION_ID) {
2910 appId.reset(new keymaster_blob_t);
2911 appId->data = param.blob.data;
2912 appId->data_length = param.blob.data_length;
2913 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2914 appData.reset(new keymaster_blob_t);
2915 appData->data = param.blob.data;
2916 appData->data_length = param.blob.data_length;
2917 }
2918 }
2919 keymaster_key_characteristics_t* result = NULL;
2920 if (!dev->get_key_characteristics) {
2921 return KM_ERROR_UNIMPLEMENTED;
2922 }
2923 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2924 appData.get(), &result);
2925 if (result) {
2926 *out = *result;
2927 free(result);
2928 }
2929 return error;
2930 }
2931
2932 /**
2933 * Get the auth token for this operation from the auth token table.
2934 *
2935 * Returns ::NO_ERROR if the auth token was set or none was required.
2936 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2937 * authorization token exists for that operation and
2938 * failOnTokenMissing is false.
2939 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2940 * token for the operation
2941 */
2942 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2943 keymaster_operation_handle_t handle,
2944 const hw_auth_token_t** authToken,
2945 bool failOnTokenMissing = true) {
2946
2947 std::vector<keymaster_key_param_t> allCharacteristics;
2948 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2949 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2950 }
2951 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2952 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2953 }
2954 keymaster::AuthTokenTable::Error err =
2955 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2956 allCharacteristics.size(), handle, authToken);
2957 switch (err) {
2958 case keymaster::AuthTokenTable::OK:
2959 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2960 return ::NO_ERROR;
2961 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2962 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2963 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2964 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2965 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2966 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2967 (int32_t) ::OP_AUTH_NEEDED;
2968 default:
2969 ALOGE("Unexpected FindAuthorization return value %d", err);
2970 return KM_ERROR_INVALID_ARGUMENT;
2971 }
2972 }
2973
2974 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2975 const hw_auth_token_t* token) {
2976 if (token) {
2977 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2978 reinterpret_cast<const uint8_t*>(token),
2979 sizeof(hw_auth_token_t)));
2980 }
2981 }
2982
2983 /**
2984 * Add the auth token for the operation to the param list if the operation
2985 * requires authorization. Uses the cached result in the OperationMap if available
2986 * otherwise gets the token from the AuthTokenTable and caches the result.
2987 *
2988 * Returns ::NO_ERROR if the auth token was added or not needed.
2989 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2990 * authenticated.
2991 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2992 * operation token.
2993 */
2994 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2995 std::vector<keymaster_key_param_t>* params) {
2996 const hw_auth_token_t* authToken = NULL;
Chad Brubaker6b541162015-04-29 19:58:34 -07002997 mOperationMap.getOperationAuthToken(token, &authToken);
2998 if (!authToken) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002999 const keymaster1_device_t* dev;
3000 keymaster_operation_handle_t handle;
3001 const keymaster_key_characteristics_t* characteristics = NULL;
3002 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3003 return KM_ERROR_INVALID_OPERATION_HANDLE;
3004 }
3005 int32_t result = getAuthToken(characteristics, handle, &authToken);
3006 if (result != ::NO_ERROR) {
3007 return result;
3008 }
3009 if (authToken) {
3010 mOperationMap.setOperationAuthToken(token, authToken);
3011 }
3012 }
3013 addAuthToParams(params, authToken);
3014 return ::NO_ERROR;
3015 }
3016
Kenny Root07438c82012-11-02 15:41:02 -07003017 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003018 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003019 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003020};
3021
3022}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003023
3024int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003025 if (argc < 2) {
3026 ALOGE("A directory must be specified!");
3027 return 1;
3028 }
3029 if (chdir(argv[1]) == -1) {
3030 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3031 return 1;
3032 }
3033
3034 Entropy entropy;
3035 if (!entropy.open()) {
3036 return 1;
3037 }
Kenny Root70e3a862012-02-15 17:20:23 -08003038
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07003039 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003040 if (keymaster_device_initialize(&dev)) {
3041 ALOGE("keystore keymaster could not be initialized; exiting");
3042 return 1;
3043 }
3044
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003045 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003046 if (fallback_keymaster_device_initialize(&fallback)) {
3047 ALOGE("software keymaster could not be initialized; exiting");
3048 return 1;
3049 }
3050
Riley Spahneaabae92014-06-30 12:39:52 -07003051 ks_is_selinux_enabled = is_selinux_enabled();
3052 if (ks_is_selinux_enabled) {
3053 union selinux_callback cb;
3054 cb.func_log = selinux_log_callback;
3055 selinux_set_callback(SELINUX_CB_LOG, cb);
3056 if (getcon(&tctx) != 0) {
3057 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3058 return -1;
3059 }
3060 } else {
3061 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3062 }
3063
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003064 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003065 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003066 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3067 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3068 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3069 if (ret != android::OK) {
3070 ALOGE("Couldn't register binder service!");
3071 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003072 }
Kenny Root07438c82012-11-02 15:41:02 -07003073
3074 /*
3075 * We're the only thread in existence, so we're just going to process
3076 * Binder transaction as a single-threaded program.
3077 */
3078 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003079
3080 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003081 return 1;
3082}