blob: 22089363530625cbf8ae44668f7d99038774bc88 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Shawn Willden80843db2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willden80843db2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Shawn Willden04006752015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker67d2a502015-03-11 17:21:18 +0000137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willden80843db2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Chad Brubakere6c3bfa2015-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 Brubakere6c3bfa2015-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 Brubakere6c3bfa2015-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 Brubakere6c3bfa2015-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 Brubakere6c3bfa2015-05-12 15:18:26 -0700186 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700187 "get",
188 "insert",
189 "delete",
190 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700191 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700192 "reset",
193 "password",
194 "lock",
195 "unlock",
Chad Brubakere6c3bfa2015-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 Brubakerc0f031a2015-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 Brubakere6c3bfa2015-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) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800499 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800500 mBlob.length = valueLength;
501 memcpy(mBlob.value, value, valueLength);
502
503 mBlob.info = infoLength;
504 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700505
Kenny Root07438c82012-11-02 15:41:02 -0700506 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700507 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700508
Kenny Rootee8068b2013-10-07 09:49:15 -0700509 if (type == TYPE_MASTER_KEY) {
510 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
511 } else {
512 mBlob.flags = KEYSTORE_FLAG_NONE;
513 }
Kenny Roota91203b2012-02-15 15:00:46 -0800514 }
515
516 Blob(blob b) {
517 mBlob = b;
518 }
519
Alex Klyubin1773b442015-02-20 12:33:33 -0800520 Blob() {
521 memset(&mBlob, 0, sizeof(mBlob));
522 }
Kenny Roota91203b2012-02-15 15:00:46 -0800523
Kenny Root51878182012-03-13 12:53:19 -0700524 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800525 return mBlob.value;
526 }
527
Kenny Root51878182012-03-13 12:53:19 -0700528 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800529 return mBlob.length;
530 }
531
Kenny Root51878182012-03-13 12:53:19 -0700532 const uint8_t* getInfo() const {
533 return mBlob.value + mBlob.length;
534 }
535
536 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 return mBlob.info;
538 }
539
Kenny Root822c3a92012-03-23 16:34:39 -0700540 uint8_t getVersion() const {
541 return mBlob.version;
542 }
543
Kenny Rootf9119d62013-04-03 09:22:15 -0700544 bool isEncrypted() const {
545 if (mBlob.version < 2) {
546 return true;
547 }
548
549 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
550 }
551
552 void setEncrypted(bool encrypted) {
553 if (encrypted) {
554 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
555 } else {
556 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
557 }
558 }
559
Kenny Root17208e02013-09-04 13:56:03 -0700560 bool isFallback() const {
561 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
562 }
563
564 void setFallback(bool fallback) {
565 if (fallback) {
566 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
567 } else {
568 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
569 }
570 }
571
Kenny Root822c3a92012-03-23 16:34:39 -0700572 void setVersion(uint8_t version) {
573 mBlob.version = version;
574 }
575
576 BlobType getType() const {
577 return BlobType(mBlob.type);
578 }
579
580 void setType(BlobType type) {
581 mBlob.type = uint8_t(type);
582 }
583
Kenny Rootf9119d62013-04-03 09:22:15 -0700584 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
585 ALOGV("writing blob %s", filename);
586 if (isEncrypted()) {
587 if (state != STATE_NO_ERROR) {
588 ALOGD("couldn't insert encrypted blob while not unlocked");
589 return LOCKED;
590 }
591
592 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
593 ALOGW("Could not read random data for: %s", filename);
594 return SYSTEM_ERROR;
595 }
Kenny Roota91203b2012-02-15 15:00:46 -0800596 }
597
598 // data includes the value and the value's length
599 size_t dataLength = mBlob.length + sizeof(mBlob.length);
600 // pad data to the AES_BLOCK_SIZE
601 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
602 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
603 // encrypted data includes the digest value
604 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
605 // move info after space for padding
606 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
607 // zero padding area
608 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
609
610 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800611
Kenny Rootf9119d62013-04-03 09:22:15 -0700612 if (isEncrypted()) {
613 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800614
Kenny Rootf9119d62013-04-03 09:22:15 -0700615 uint8_t vector[AES_BLOCK_SIZE];
616 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
617 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
618 aes_key, vector, AES_ENCRYPT);
619 }
620
Kenny Roota91203b2012-02-15 15:00:46 -0800621 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
622 size_t fileLength = encryptedLength + headerLength + mBlob.info;
623
624 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800625 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
626 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
627 if (out < 0) {
628 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800629 return SYSTEM_ERROR;
630 }
631 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
632 if (close(out) != 0) {
633 return SYSTEM_ERROR;
634 }
635 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800636 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800637 unlink(tmpFileName);
638 return SYSTEM_ERROR;
639 }
Kenny Root150ca932012-11-14 14:29:02 -0800640 if (rename(tmpFileName, filename) == -1) {
641 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
642 return SYSTEM_ERROR;
643 }
644 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800645 }
646
Kenny Rootf9119d62013-04-03 09:22:15 -0700647 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
648 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800649 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
650 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800651 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
652 }
653 // fileLength may be less than sizeof(mBlob) since the in
654 // memory version has extra padding to tolerate rounding up to
655 // the AES_BLOCK_SIZE
656 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
657 if (close(in) != 0) {
658 return SYSTEM_ERROR;
659 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700660
661 if (isEncrypted() && (state != STATE_NO_ERROR)) {
662 return LOCKED;
663 }
664
Kenny Roota91203b2012-02-15 15:00:46 -0800665 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
666 if (fileLength < headerLength) {
667 return VALUE_CORRUPTED;
668 }
669
670 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700671 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800672 return VALUE_CORRUPTED;
673 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700674
675 ssize_t digestedLength;
676 if (isEncrypted()) {
677 if (encryptedLength % AES_BLOCK_SIZE != 0) {
678 return VALUE_CORRUPTED;
679 }
680
681 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
682 mBlob.vector, AES_DECRYPT);
683 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
684 uint8_t computedDigest[MD5_DIGEST_LENGTH];
685 MD5(mBlob.digested, digestedLength, computedDigest);
686 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
687 return VALUE_CORRUPTED;
688 }
689 } else {
690 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800691 }
692
693 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
694 mBlob.length = ntohl(mBlob.length);
695 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
696 return VALUE_CORRUPTED;
697 }
698 if (mBlob.info != 0) {
699 // move info from after padding to after data
700 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
701 }
Kenny Root07438c82012-11-02 15:41:02 -0700702 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800703 }
704
705private:
706 struct blob mBlob;
707};
708
Kenny Root655b9582013-04-04 08:37:42 -0700709class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800710public:
Kenny Root655b9582013-04-04 08:37:42 -0700711 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
712 asprintf(&mUserDir, "user_%u", mUserId);
713 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
714 }
715
716 ~UserState() {
717 free(mUserDir);
718 free(mMasterKeyFile);
719 }
720
721 bool initialize() {
722 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
723 ALOGE("Could not create directory '%s'", mUserDir);
724 return false;
725 }
726
727 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800728 setState(STATE_LOCKED);
729 } else {
730 setState(STATE_UNINITIALIZED);
731 }
Kenny Root70e3a862012-02-15 17:20:23 -0800732
Kenny Root655b9582013-04-04 08:37:42 -0700733 return true;
734 }
735
736 uid_t getUserId() const {
737 return mUserId;
738 }
739
740 const char* getUserDirName() const {
741 return mUserDir;
742 }
743
744 const char* getMasterKeyFileName() const {
745 return mMasterKeyFile;
746 }
747
748 void setState(State state) {
749 mState = state;
750 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
751 mRetry = MAX_RETRY;
752 }
Kenny Roota91203b2012-02-15 15:00:46 -0800753 }
754
Kenny Root51878182012-03-13 12:53:19 -0700755 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800756 return mState;
757 }
758
Kenny Root51878182012-03-13 12:53:19 -0700759 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800760 return mRetry;
761 }
762
Kenny Root655b9582013-04-04 08:37:42 -0700763 void zeroizeMasterKeysInMemory() {
764 memset(mMasterKey, 0, sizeof(mMasterKey));
765 memset(mSalt, 0, sizeof(mSalt));
766 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
767 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800768 }
769
Chad Brubaker96d6d782015-05-07 10:19:40 -0700770 bool deleteMasterKey() {
771 setState(STATE_UNINITIALIZED);
772 zeroizeMasterKeysInMemory();
773 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
774 }
775
Kenny Root655b9582013-04-04 08:37:42 -0700776 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
777 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800778 return SYSTEM_ERROR;
779 }
Kenny Root655b9582013-04-04 08:37:42 -0700780 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800781 if (response != NO_ERROR) {
782 return response;
783 }
784 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700785 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800786 }
787
Robin Lee4e865752014-08-19 17:37:55 +0100788 ResponseCode copyMasterKey(UserState* src) {
789 if (mState != STATE_UNINITIALIZED) {
790 return ::SYSTEM_ERROR;
791 }
792 if (src->getState() != STATE_NO_ERROR) {
793 return ::SYSTEM_ERROR;
794 }
795 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
796 setupMasterKeys();
797 return ::NO_ERROR;
798 }
799
Kenny Root655b9582013-04-04 08:37:42 -0700800 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800801 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
802 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
803 AES_KEY passwordAesKey;
804 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700805 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700806 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800807 }
808
Kenny Root655b9582013-04-04 08:37:42 -0700809 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
810 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800811 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800812 return SYSTEM_ERROR;
813 }
814
815 // we read the raw blob to just to get the salt to generate
816 // the AES key, then we create the Blob to use with decryptBlob
817 blob rawBlob;
818 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
819 if (close(in) != 0) {
820 return SYSTEM_ERROR;
821 }
822 // find salt at EOF if present, otherwise we have an old file
823 uint8_t* salt;
824 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
825 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
826 } else {
827 salt = NULL;
828 }
829 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
830 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
831 AES_KEY passwordAesKey;
832 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
833 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700834 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
835 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800836 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700837 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800838 }
839 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
840 // if salt was missing, generate one and write a new master key file with the salt.
841 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700842 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800843 return SYSTEM_ERROR;
844 }
Kenny Root655b9582013-04-04 08:37:42 -0700845 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800846 }
847 if (response == NO_ERROR) {
848 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
849 setupMasterKeys();
850 }
851 return response;
852 }
853 if (mRetry <= 0) {
854 reset();
855 return UNINITIALIZED;
856 }
857 --mRetry;
858 switch (mRetry) {
859 case 0: return WRONG_PASSWORD_0;
860 case 1: return WRONG_PASSWORD_1;
861 case 2: return WRONG_PASSWORD_2;
862 case 3: return WRONG_PASSWORD_3;
863 default: return WRONG_PASSWORD_3;
864 }
865 }
866
Kenny Root655b9582013-04-04 08:37:42 -0700867 AES_KEY* getEncryptionKey() {
868 return &mMasterKeyEncryption;
869 }
870
871 AES_KEY* getDecryptionKey() {
872 return &mMasterKeyDecryption;
873 }
874
Kenny Roota91203b2012-02-15 15:00:46 -0800875 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700876 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800877 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700878 // If the directory doesn't exist then nothing to do.
879 if (errno == ENOENT) {
880 return true;
881 }
Kenny Root655b9582013-04-04 08:37:42 -0700882 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800883 return false;
884 }
Kenny Root655b9582013-04-04 08:37:42 -0700885
886 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800887 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700888 // skip . and ..
889 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700890 continue;
891 }
892
893 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800894 }
895 closedir(dir);
896 return true;
897 }
898
Kenny Root655b9582013-04-04 08:37:42 -0700899private:
900 static const int MASTER_KEY_SIZE_BYTES = 16;
901 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
902
903 static const int MAX_RETRY = 4;
904 static const size_t SALT_SIZE = 16;
905
906 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
907 uint8_t* salt) {
908 size_t saltSize;
909 if (salt != NULL) {
910 saltSize = SALT_SIZE;
911 } else {
912 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
913 salt = (uint8_t*) "keystore";
914 // sizeof = 9, not strlen = 8
915 saltSize = sizeof("keystore");
916 }
917
918 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
919 saltSize, 8192, keySize, key);
920 }
921
922 bool generateSalt(Entropy* entropy) {
923 return entropy->generate_random_data(mSalt, sizeof(mSalt));
924 }
925
926 bool generateMasterKey(Entropy* entropy) {
927 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
928 return false;
929 }
930 if (!generateSalt(entropy)) {
931 return false;
932 }
933 return true;
934 }
935
936 void setupMasterKeys() {
937 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
938 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
939 setState(STATE_NO_ERROR);
940 }
941
942 uid_t mUserId;
943
944 char* mUserDir;
945 char* mMasterKeyFile;
946
947 State mState;
948 int8_t mRetry;
949
950 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
951 uint8_t mSalt[SALT_SIZE];
952
953 AES_KEY mMasterKeyEncryption;
954 AES_KEY mMasterKeyDecryption;
955};
956
957typedef struct {
958 uint32_t uid;
959 const uint8_t* filename;
960} grant_t;
961
962class KeyStore {
963public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000964 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700965 : mEntropy(entropy)
966 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800967 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700968 {
969 memset(&mMetaData, '\0', sizeof(mMetaData));
970 }
971
972 ~KeyStore() {
973 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
974 it != mGrants.end(); it++) {
975 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700976 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800977 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700978
979 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
980 it != mMasterKeys.end(); it++) {
981 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700982 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800983 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700984 }
985
Chad Brubaker67d2a502015-03-11 17:21:18 +0000986 /**
987 * Depending on the hardware keymaster version is this may return a
988 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
989 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
990 * be guarded by a check on the device's version.
991 */
992 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700993 return mDevice;
994 }
995
Chad Brubaker67d2a502015-03-11 17:21:18 +0000996 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800997 return mFallbackDevice;
998 }
999
Chad Brubaker67d2a502015-03-11 17:21:18 +00001000 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001001 return blob.isFallback() ? mFallbackDevice: mDevice;
1002 }
1003
Kenny Root655b9582013-04-04 08:37:42 -07001004 ResponseCode initialize() {
1005 readMetaData();
1006 if (upgradeKeystore()) {
1007 writeMetaData();
1008 }
1009
1010 return ::NO_ERROR;
1011 }
1012
Chad Brubaker72593ee2015-05-12 10:42:00 -07001013 State getState(uid_t userId) {
1014 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001015 }
1016
Chad Brubaker72593ee2015-05-12 10:42:00 -07001017 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1018 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001019 return userState->initialize(pw, mEntropy);
1020 }
1021
Chad Brubaker72593ee2015-05-12 10:42:00 -07001022 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1023 UserState *userState = getUserState(dstUser);
1024 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001025 return userState->copyMasterKey(initState);
1026 }
1027
Chad Brubaker72593ee2015-05-12 10:42:00 -07001028 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1029 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001030 return userState->writeMasterKey(pw, mEntropy);
1031 }
1032
Chad Brubaker72593ee2015-05-12 10:42:00 -07001033 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1034 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001035 return userState->readMasterKey(pw, mEntropy);
1036 }
1037
1038 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001039 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001040 encode_key(encoded, keyName);
1041 return android::String8(encoded);
1042 }
1043
1044 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001045 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001046 encode_key(encoded, keyName);
1047 return android::String8::format("%u_%s", uid, encoded);
1048 }
1049
1050 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001051 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001052 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001053 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001054 encoded);
1055 }
1056
Chad Brubaker96d6d782015-05-07 10:19:40 -07001057 /*
1058 * Delete entries owned by userId. If keepUnencryptedEntries is true
1059 * then only encrypted entries will be removed, otherwise all entries will
1060 * be removed.
1061 */
1062 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001063 android::String8 prefix("");
1064 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001065 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001066 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001067 return;
1068 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001069 for (uint32_t i = 0; i < aliases.size(); i++) {
1070 android::String8 filename(aliases[i]);
1071 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001072 getKeyName(filename).string());
1073 bool shouldDelete = true;
1074 if (keepUnenryptedEntries) {
1075 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001076 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001077
Chad Brubaker96d6d782015-05-07 10:19:40 -07001078 /* get can fail if the blob is encrypted and the state is
1079 * not unlocked, only skip deleting blobs that were loaded and
1080 * who are not encrypted. If there are blobs we fail to read for
1081 * other reasons err on the safe side and delete them since we
1082 * can't tell if they're encrypted.
1083 */
1084 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1085 }
1086 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001087 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001088 }
1089 }
1090 if (!userState->deleteMasterKey()) {
1091 ALOGE("Failed to delete user %d's master key", userId);
1092 }
1093 if (!keepUnenryptedEntries) {
1094 if(!userState->reset()) {
1095 ALOGE("Failed to remove user %d's directory", userId);
1096 }
1097 }
Kenny Root655b9582013-04-04 08:37:42 -07001098 }
1099
Chad Brubaker72593ee2015-05-12 10:42:00 -07001100 bool isEmpty(uid_t userId) const {
1101 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001102 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001103 return true;
1104 }
1105
1106 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001107 if (!dir) {
1108 return true;
1109 }
Kenny Root31e27462014-09-10 11:28:03 -07001110
Kenny Roota91203b2012-02-15 15:00:46 -08001111 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001112 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001113 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001114 // We only care about files.
1115 if (file->d_type != DT_REG) {
1116 continue;
1117 }
1118
1119 // Skip anything that starts with a "."
1120 if (file->d_name[0] == '.') {
1121 continue;
1122 }
1123
Kenny Root31e27462014-09-10 11:28:03 -07001124 result = false;
1125 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001126 }
1127 closedir(dir);
1128 return result;
1129 }
1130
Chad Brubaker72593ee2015-05-12 10:42:00 -07001131 void lock(uid_t userId) {
1132 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001133 userState->zeroizeMasterKeysInMemory();
1134 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001135 }
1136
Chad Brubaker72593ee2015-05-12 10:42:00 -07001137 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1138 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001139 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1140 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001141 if (rc != NO_ERROR) {
1142 return rc;
1143 }
1144
1145 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001146 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001147 /* If we upgrade the key, we need to write it to disk again. Then
1148 * it must be read it again since the blob is encrypted each time
1149 * it's written.
1150 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001151 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1152 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001153 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1154 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001155 return rc;
1156 }
1157 }
Kenny Root822c3a92012-03-23 16:34:39 -07001158 }
1159
Kenny Root17208e02013-09-04 13:56:03 -07001160 /*
1161 * This will upgrade software-backed keys to hardware-backed keys when
1162 * the HAL for the device supports the newer key types.
1163 */
1164 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1165 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1166 && keyBlob->isFallback()) {
1167 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001168 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001169
1170 // The HAL allowed the import, reget the key to have the "fresh"
1171 // version.
1172 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001173 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001174 }
1175 }
1176
Kenny Rootd53bc922013-03-21 14:10:15 -07001177 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001178 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1179 return KEY_NOT_FOUND;
1180 }
1181
1182 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001183 }
1184
Chad Brubaker72593ee2015-05-12 10:42:00 -07001185 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1186 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001187 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1188 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001189 }
1190
Chad Brubaker72593ee2015-05-12 10:42:00 -07001191 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001192 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001193 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001194 if (rc != ::NO_ERROR) {
1195 return rc;
1196 }
1197
1198 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1199 // A device doesn't have to implement delete_keypair.
1200 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1201 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1202 rc = ::SYSTEM_ERROR;
1203 }
1204 }
1205 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001206 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1207 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1208 if (dev->delete_key) {
1209 keymaster_key_blob_t blob;
1210 blob.key_material = keyBlob.getValue();
1211 blob.key_material_size = keyBlob.getLength();
1212 dev->delete_key(dev, &blob);
1213 }
1214 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001215 if (rc != ::NO_ERROR) {
1216 return rc;
1217 }
1218
1219 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1220 }
1221
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001222 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001223 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001224
Chad Brubaker72593ee2015-05-12 10:42:00 -07001225 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001226 size_t n = prefix.length();
1227
1228 DIR* dir = opendir(userState->getUserDirName());
1229 if (!dir) {
1230 ALOGW("can't open directory for user: %s", strerror(errno));
1231 return ::SYSTEM_ERROR;
1232 }
1233
1234 struct dirent* file;
1235 while ((file = readdir(dir)) != NULL) {
1236 // We only care about files.
1237 if (file->d_type != DT_REG) {
1238 continue;
1239 }
1240
1241 // Skip anything that starts with a "."
1242 if (file->d_name[0] == '.') {
1243 continue;
1244 }
1245
1246 if (!strncmp(prefix.string(), file->d_name, n)) {
1247 const char* p = &file->d_name[n];
1248 size_t plen = strlen(p);
1249
1250 size_t extra = decode_key_length(p, plen);
1251 char *match = (char*) malloc(extra + 1);
1252 if (match != NULL) {
1253 decode_key(match, p, plen);
1254 matches->push(android::String16(match, extra));
1255 free(match);
1256 } else {
1257 ALOGW("could not allocate match of size %zd", extra);
1258 }
1259 }
1260 }
1261 closedir(dir);
1262 return ::NO_ERROR;
1263 }
1264
Kenny Root07438c82012-11-02 15:41:02 -07001265 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001266 const grant_t* existing = getGrant(filename, granteeUid);
1267 if (existing == NULL) {
1268 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001269 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001270 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001271 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001272 }
1273 }
1274
Kenny Root07438c82012-11-02 15:41:02 -07001275 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001276 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1277 it != mGrants.end(); it++) {
1278 grant_t* grant = *it;
1279 if (grant->uid == granteeUid
1280 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1281 mGrants.erase(it);
1282 return true;
1283 }
Kenny Root70e3a862012-02-15 17:20:23 -08001284 }
Kenny Root70e3a862012-02-15 17:20:23 -08001285 return false;
1286 }
1287
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001288 bool hasGrant(const char* filename, const uid_t uid) const {
1289 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001290 }
1291
Chad Brubaker72593ee2015-05-12 10:42:00 -07001292 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001293 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001294 uint8_t* data;
1295 size_t dataLength;
1296 int rc;
1297
1298 if (mDevice->import_keypair == NULL) {
1299 ALOGE("Keymaster doesn't support import!");
1300 return SYSTEM_ERROR;
1301 }
1302
Kenny Root17208e02013-09-04 13:56:03 -07001303 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001304 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001305 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001306 /*
1307 * Maybe the device doesn't support this type of key. Try to use the
1308 * software fallback keymaster implementation. This is a little bit
1309 * lazier than checking the PKCS#8 key type, but the software
1310 * implementation will do that anyway.
1311 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001312 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001313 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001314
1315 if (rc) {
1316 ALOGE("Error while importing keypair: %d", rc);
1317 return SYSTEM_ERROR;
1318 }
Kenny Root822c3a92012-03-23 16:34:39 -07001319 }
1320
1321 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1322 free(data);
1323
Kenny Rootf9119d62013-04-03 09:22:15 -07001324 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001325 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001326
Chad Brubaker72593ee2015-05-12 10:42:00 -07001327 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001328 }
1329
Kenny Root1b0e3932013-09-05 13:06:32 -07001330 bool isHardwareBacked(const android::String16& keyType) const {
1331 if (mDevice == NULL) {
1332 ALOGW("can't get keymaster device");
1333 return false;
1334 }
1335
1336 if (sRSAKeyType == keyType) {
1337 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1338 } else {
1339 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1340 && (mDevice->common.module->module_api_version
1341 >= KEYMASTER_MODULE_API_VERSION_0_2);
1342 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001343 }
1344
Kenny Root655b9582013-04-04 08:37:42 -07001345 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1346 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001347 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001348 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001349
Chad Brubaker72593ee2015-05-12 10:42:00 -07001350 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001351 if (responseCode == NO_ERROR) {
1352 return responseCode;
1353 }
1354
1355 // If this is one of the legacy UID->UID mappings, use it.
1356 uid_t euid = get_keystore_euid(uid);
1357 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001358 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001359 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001360 if (responseCode == NO_ERROR) {
1361 return responseCode;
1362 }
1363 }
1364
1365 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001366 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001367 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001368 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001369 if (end[0] != '_' || end[1] == 0) {
1370 return KEY_NOT_FOUND;
1371 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001372 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001373 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001374 if (!hasGrant(filepath8.string(), uid)) {
1375 return responseCode;
1376 }
1377
1378 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001379 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001380 }
1381
1382 /**
1383 * Returns any existing UserState or creates it if it doesn't exist.
1384 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001385 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001386 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1387 it != mMasterKeys.end(); it++) {
1388 UserState* state = *it;
1389 if (state->getUserId() == userId) {
1390 return state;
1391 }
1392 }
1393
1394 UserState* userState = new UserState(userId);
1395 if (!userState->initialize()) {
1396 /* There's not much we can do if initialization fails. Trying to
1397 * unlock the keystore for that user will fail as well, so any
1398 * subsequent request for this user will just return SYSTEM_ERROR.
1399 */
1400 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1401 }
1402 mMasterKeys.add(userState);
1403 return userState;
1404 }
1405
1406 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001407 * Returns any existing UserState or creates it if it doesn't exist.
1408 */
1409 UserState* getUserStateByUid(uid_t uid) {
1410 uid_t userId = get_user_id(uid);
1411 return getUserState(userId);
1412 }
1413
1414 /**
Kenny Root655b9582013-04-04 08:37:42 -07001415 * Returns NULL if the UserState doesn't already exist.
1416 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001417 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001418 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1419 it != mMasterKeys.end(); it++) {
1420 UserState* state = *it;
1421 if (state->getUserId() == userId) {
1422 return state;
1423 }
1424 }
1425
1426 return NULL;
1427 }
1428
Chad Brubaker72593ee2015-05-12 10:42:00 -07001429 /**
1430 * Returns NULL if the UserState doesn't already exist.
1431 */
1432 const UserState* getUserStateByUid(uid_t uid) const {
1433 uid_t userId = get_user_id(uid);
1434 return getUserState(userId);
1435 }
1436
Kenny Roota91203b2012-02-15 15:00:46 -08001437private:
Kenny Root655b9582013-04-04 08:37:42 -07001438 static const char* sOldMasterKey;
1439 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001440 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001441 Entropy* mEntropy;
1442
Chad Brubaker67d2a502015-03-11 17:21:18 +00001443 keymaster1_device_t* mDevice;
1444 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001445
Kenny Root655b9582013-04-04 08:37:42 -07001446 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001447
Kenny Root655b9582013-04-04 08:37:42 -07001448 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001449
Kenny Root655b9582013-04-04 08:37:42 -07001450 typedef struct {
1451 uint32_t version;
1452 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001453
Kenny Root655b9582013-04-04 08:37:42 -07001454 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001455
Kenny Root655b9582013-04-04 08:37:42 -07001456 const grant_t* getGrant(const char* filename, uid_t uid) const {
1457 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1458 it != mGrants.end(); it++) {
1459 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001460 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001461 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001462 return grant;
1463 }
1464 }
Kenny Root70e3a862012-02-15 17:20:23 -08001465 return NULL;
1466 }
1467
Kenny Root822c3a92012-03-23 16:34:39 -07001468 /**
1469 * Upgrade code. This will upgrade the key from the current version
1470 * to whatever is newest.
1471 */
Kenny Root655b9582013-04-04 08:37:42 -07001472 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1473 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001474 bool updated = false;
1475 uint8_t version = oldVersion;
1476
1477 /* From V0 -> V1: All old types were unknown */
1478 if (version == 0) {
1479 ALOGV("upgrading to version 1 and setting type %d", type);
1480
1481 blob->setType(type);
1482 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001483 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001484 }
1485 version = 1;
1486 updated = true;
1487 }
1488
Kenny Rootf9119d62013-04-03 09:22:15 -07001489 /* From V1 -> V2: All old keys were encrypted */
1490 if (version == 1) {
1491 ALOGV("upgrading to version 2");
1492
1493 blob->setEncrypted(true);
1494 version = 2;
1495 updated = true;
1496 }
1497
Kenny Root822c3a92012-03-23 16:34:39 -07001498 /*
1499 * If we've updated, set the key blob to the right version
1500 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001501 */
Kenny Root822c3a92012-03-23 16:34:39 -07001502 if (updated) {
1503 ALOGV("updated and writing file %s", filename);
1504 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001505 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001506
1507 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001508 }
1509
1510 /**
1511 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1512 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1513 * Then it overwrites the original blob with the new blob
1514 * format that is returned from the keymaster.
1515 */
Kenny Root655b9582013-04-04 08:37:42 -07001516 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001517 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1518 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1519 if (b.get() == NULL) {
1520 ALOGE("Problem instantiating BIO");
1521 return SYSTEM_ERROR;
1522 }
1523
1524 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1525 if (pkey.get() == NULL) {
1526 ALOGE("Couldn't read old PEM file");
1527 return SYSTEM_ERROR;
1528 }
1529
1530 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1531 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1532 if (len < 0) {
1533 ALOGE("Couldn't measure PKCS#8 length");
1534 return SYSTEM_ERROR;
1535 }
1536
Kenny Root70c98892013-02-07 09:10:36 -08001537 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1538 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001539 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1540 ALOGE("Couldn't convert to PKCS#8");
1541 return SYSTEM_ERROR;
1542 }
1543
Chad Brubaker72593ee2015-05-12 10:42:00 -07001544 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001545 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001546 if (rc != NO_ERROR) {
1547 return rc;
1548 }
1549
Kenny Root655b9582013-04-04 08:37:42 -07001550 return get(filename, blob, TYPE_KEY_PAIR, uid);
1551 }
1552
1553 void readMetaData() {
1554 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1555 if (in < 0) {
1556 return;
1557 }
1558 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1559 if (fileLength != sizeof(mMetaData)) {
1560 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1561 sizeof(mMetaData));
1562 }
1563 close(in);
1564 }
1565
1566 void writeMetaData() {
1567 const char* tmpFileName = ".metadata.tmp";
1568 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1569 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1570 if (out < 0) {
1571 ALOGE("couldn't write metadata file: %s", strerror(errno));
1572 return;
1573 }
1574 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1575 if (fileLength != sizeof(mMetaData)) {
1576 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1577 sizeof(mMetaData));
1578 }
1579 close(out);
1580 rename(tmpFileName, sMetaDataFile);
1581 }
1582
1583 bool upgradeKeystore() {
1584 bool upgraded = false;
1585
1586 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001587 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001588
1589 // Initialize first so the directory is made.
1590 userState->initialize();
1591
1592 // Migrate the old .masterkey file to user 0.
1593 if (access(sOldMasterKey, R_OK) == 0) {
1594 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1595 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1596 return false;
1597 }
1598 }
1599
1600 // Initialize again in case we had a key.
1601 userState->initialize();
1602
1603 // Try to migrate existing keys.
1604 DIR* dir = opendir(".");
1605 if (!dir) {
1606 // Give up now; maybe we can upgrade later.
1607 ALOGE("couldn't open keystore's directory; something is wrong");
1608 return false;
1609 }
1610
1611 struct dirent* file;
1612 while ((file = readdir(dir)) != NULL) {
1613 // We only care about files.
1614 if (file->d_type != DT_REG) {
1615 continue;
1616 }
1617
1618 // Skip anything that starts with a "."
1619 if (file->d_name[0] == '.') {
1620 continue;
1621 }
1622
1623 // Find the current file's user.
1624 char* end;
1625 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1626 if (end[0] != '_' || end[1] == 0) {
1627 continue;
1628 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001629 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001630 if (otherUser->getUserId() != 0) {
1631 unlinkat(dirfd(dir), file->d_name, 0);
1632 }
1633
1634 // Rename the file into user directory.
1635 DIR* otherdir = opendir(otherUser->getUserDirName());
1636 if (otherdir == NULL) {
1637 ALOGW("couldn't open user directory for rename");
1638 continue;
1639 }
1640 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1641 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1642 }
1643 closedir(otherdir);
1644 }
1645 closedir(dir);
1646
1647 mMetaData.version = 1;
1648 upgraded = true;
1649 }
1650
1651 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001652 }
Kenny Roota91203b2012-02-15 15:00:46 -08001653};
1654
Kenny Root655b9582013-04-04 08:37:42 -07001655const char* KeyStore::sOldMasterKey = ".masterkey";
1656const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001657
Kenny Root1b0e3932013-09-05 13:06:32 -07001658const android::String16 KeyStore::sRSAKeyType("RSA");
1659
Kenny Root07438c82012-11-02 15:41:02 -07001660namespace android {
1661class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1662public:
1663 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001664 : mKeyStore(keyStore),
1665 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001666 {
Kenny Roota91203b2012-02-15 15:00:46 -08001667 }
Kenny Roota91203b2012-02-15 15:00:46 -08001668
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001669 void binderDied(const wp<IBinder>& who) {
1670 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1671 for (auto token: operations) {
1672 abort(token);
1673 }
Kenny Root822c3a92012-03-23 16:34:39 -07001674 }
Kenny Roota91203b2012-02-15 15:00:46 -08001675
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001676 int32_t getState(int32_t userId) {
1677 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001678 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001679 }
Kenny Roota91203b2012-02-15 15:00:46 -08001680
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001681 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001682 }
1683
Kenny Root07438c82012-11-02 15:41:02 -07001684 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001685 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001686 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001687 }
Kenny Root07438c82012-11-02 15:41:02 -07001688
Chad Brubaker9489b792015-04-14 11:01:45 -07001689 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001690 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001691 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001692
Kenny Root655b9582013-04-04 08:37:42 -07001693 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001694 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001695 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001696 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001697 *item = NULL;
1698 *itemLength = 0;
1699 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001700 }
Kenny Roota91203b2012-02-15 15:00:46 -08001701
Kenny Root07438c82012-11-02 15:41:02 -07001702 *item = (uint8_t*) malloc(keyBlob.getLength());
1703 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1704 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001705
Kenny Root07438c82012-11-02 15:41:02 -07001706 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001707 }
1708
Kenny Rootf9119d62013-04-03 09:22:15 -07001709 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1710 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001711 targetUid = getEffectiveUid(targetUid);
1712 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1713 flags & KEYSTORE_FLAG_ENCRYPTED);
1714 if (result != ::NO_ERROR) {
1715 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001716 }
1717
Kenny Root07438c82012-11-02 15:41:02 -07001718 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001719 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001720
1721 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001722 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1723
Chad Brubaker72593ee2015-05-12 10:42:00 -07001724 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001725 }
1726
Kenny Root49468902013-03-19 13:41:33 -07001727 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001728 targetUid = getEffectiveUid(targetUid);
1729 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001730 return ::PERMISSION_DENIED;
1731 }
Kenny Root07438c82012-11-02 15:41:02 -07001732 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001733 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001734 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001735 }
1736
Kenny Root49468902013-03-19 13:41:33 -07001737 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001738 targetUid = getEffectiveUid(targetUid);
1739 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001740 return ::PERMISSION_DENIED;
1741 }
1742
Kenny Root07438c82012-11-02 15:41:02 -07001743 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001744 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001745
Kenny Root655b9582013-04-04 08:37:42 -07001746 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001747 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1748 }
1749 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001750 }
1751
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001752 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001753 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001754 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001755 return ::PERMISSION_DENIED;
1756 }
Kenny Root07438c82012-11-02 15:41:02 -07001757 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001758 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001759
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001760 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001761 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001762 }
Kenny Root07438c82012-11-02 15:41:02 -07001763 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001764 }
1765
Kenny Root07438c82012-11-02 15:41:02 -07001766 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001767 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001768 return ::PERMISSION_DENIED;
1769 }
1770
Chad Brubaker9489b792015-04-14 11:01:45 -07001771 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001772 mKeyStore->resetUser(get_user_id(callingUid), false);
1773 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001774 }
1775
Chad Brubaker96d6d782015-05-07 10:19:40 -07001776 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001777 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001778 return ::PERMISSION_DENIED;
1779 }
Kenny Root70e3a862012-02-15 17:20:23 -08001780
Kenny Root07438c82012-11-02 15:41:02 -07001781 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001782 // Flush the auth token table to prevent stale tokens from sticking
1783 // around.
1784 mAuthTokenTable.Clear();
1785
1786 if (password.size() == 0) {
1787 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001788 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001789 return ::NO_ERROR;
1790 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001791 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001792 case ::STATE_UNINITIALIZED: {
1793 // generate master key, encrypt with password, write to file,
1794 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001795 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001796 }
1797 case ::STATE_NO_ERROR: {
1798 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001799 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001800 }
1801 case ::STATE_LOCKED: {
1802 ALOGE("Changing user %d's password while locked, clearing old encryption",
1803 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001804 mKeyStore->resetUser(userId, true);
1805 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001806 }
Kenny Root07438c82012-11-02 15:41:02 -07001807 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001808 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001809 }
Kenny Root70e3a862012-02-15 17:20:23 -08001810 }
1811
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001812 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1813 if (!checkBinderPermission(P_USER_CHANGED)) {
1814 return ::PERMISSION_DENIED;
1815 }
1816
1817 // Sanity check that the new user has an empty keystore.
1818 if (!mKeyStore->isEmpty(userId)) {
1819 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1820 }
1821 // Unconditionally clear the keystore, just to be safe.
1822 mKeyStore->resetUser(userId, false);
1823
1824 // If the user has a parent user then use the parent's
1825 // masterkey/password, otherwise there's nothing to do.
1826 if (parentId != -1) {
1827 return mKeyStore->copyMasterKey(parentId, userId);
1828 } else {
1829 return ::NO_ERROR;
1830 }
1831 }
1832
1833 int32_t onUserRemoved(int32_t userId) {
1834 if (!checkBinderPermission(P_USER_CHANGED)) {
1835 return ::PERMISSION_DENIED;
1836 }
1837
1838 mKeyStore->resetUser(userId, false);
1839 return ::NO_ERROR;
1840 }
1841
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001842 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001843 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001844 return ::PERMISSION_DENIED;
1845 }
Kenny Root70e3a862012-02-15 17:20:23 -08001846
Chad Brubaker72593ee2015-05-12 10:42:00 -07001847 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001848 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001849 ALOGD("calling lock in state: %d", state);
1850 return state;
1851 }
1852
Chad Brubaker72593ee2015-05-12 10:42:00 -07001853 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001854 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001855 }
1856
Chad Brubaker96d6d782015-05-07 10:19:40 -07001857 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001858 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001859 return ::PERMISSION_DENIED;
1860 }
1861
Chad Brubaker72593ee2015-05-12 10:42:00 -07001862 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001863 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001864 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001865 return state;
1866 }
1867
1868 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001869 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001870 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001871 }
1872
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001873 bool isEmpty(int32_t userId) {
1874 if (!checkBinderPermission(P_IS_EMPTY)) {
1875 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001876 }
Kenny Root70e3a862012-02-15 17:20:23 -08001877
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001878 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001879 }
1880
Kenny Root96427ba2013-08-16 14:02:41 -07001881 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1882 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001883 targetUid = getEffectiveUid(targetUid);
1884 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1885 flags & KEYSTORE_FLAG_ENCRYPTED);
1886 if (result != ::NO_ERROR) {
1887 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001888 }
Kenny Root07438c82012-11-02 15:41:02 -07001889 uint8_t* data;
1890 size_t dataLength;
1891 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001892 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001893
Chad Brubaker67d2a502015-03-11 17:21:18 +00001894 const keymaster1_device_t* device = mKeyStore->getDevice();
1895 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001896 if (device == NULL) {
1897 return ::SYSTEM_ERROR;
1898 }
1899
1900 if (device->generate_keypair == NULL) {
1901 return ::SYSTEM_ERROR;
1902 }
1903
Kenny Root17208e02013-09-04 13:56:03 -07001904 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001905 keymaster_dsa_keygen_params_t dsa_params;
1906 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001907
Kenny Root96427ba2013-08-16 14:02:41 -07001908 if (keySize == -1) {
1909 keySize = DSA_DEFAULT_KEY_SIZE;
1910 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1911 || keySize > DSA_MAX_KEY_SIZE) {
1912 ALOGI("invalid key size %d", keySize);
1913 return ::SYSTEM_ERROR;
1914 }
1915 dsa_params.key_size = keySize;
1916
1917 if (args->size() == 3) {
1918 sp<KeystoreArg> gArg = args->itemAt(0);
1919 sp<KeystoreArg> pArg = args->itemAt(1);
1920 sp<KeystoreArg> qArg = args->itemAt(2);
1921
1922 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1923 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1924 dsa_params.generator_len = gArg->size();
1925
1926 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1927 dsa_params.prime_p_len = pArg->size();
1928
1929 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1930 dsa_params.prime_q_len = qArg->size();
1931 } else {
1932 ALOGI("not all DSA parameters were read");
1933 return ::SYSTEM_ERROR;
1934 }
1935 } else if (args->size() != 0) {
1936 ALOGI("DSA args must be 3");
1937 return ::SYSTEM_ERROR;
1938 }
1939
Kenny Root1d448c02013-11-21 10:36:53 -08001940 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001941 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1942 } else {
1943 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001944 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1945 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001946 }
1947 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001948 keymaster_ec_keygen_params_t ec_params;
1949 memset(&ec_params, '\0', sizeof(ec_params));
1950
1951 if (keySize == -1) {
1952 keySize = EC_DEFAULT_KEY_SIZE;
1953 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1954 ALOGI("invalid key size %d", keySize);
1955 return ::SYSTEM_ERROR;
1956 }
1957 ec_params.field_size = keySize;
1958
Kenny Root1d448c02013-11-21 10:36:53 -08001959 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001960 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1961 } else {
1962 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001963 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001964 }
Kenny Root96427ba2013-08-16 14:02:41 -07001965 } else if (keyType == EVP_PKEY_RSA) {
1966 keymaster_rsa_keygen_params_t rsa_params;
1967 memset(&rsa_params, '\0', sizeof(rsa_params));
1968 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1969
1970 if (keySize == -1) {
1971 keySize = RSA_DEFAULT_KEY_SIZE;
1972 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1973 ALOGI("invalid key size %d", keySize);
1974 return ::SYSTEM_ERROR;
1975 }
1976 rsa_params.modulus_size = keySize;
1977
1978 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001979 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001980 return ::SYSTEM_ERROR;
1981 } else if (args->size() == 1) {
1982 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1983 if (pubExpBlob != NULL) {
1984 Unique_BIGNUM pubExpBn(
1985 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1986 pubExpBlob->size(), NULL));
1987 if (pubExpBn.get() == NULL) {
1988 ALOGI("Could not convert public exponent to BN");
1989 return ::SYSTEM_ERROR;
1990 }
1991 unsigned long pubExp = BN_get_word(pubExpBn.get());
1992 if (pubExp == 0xFFFFFFFFL) {
1993 ALOGI("cannot represent public exponent as a long value");
1994 return ::SYSTEM_ERROR;
1995 }
1996 rsa_params.public_exponent = pubExp;
1997 }
1998 }
1999
2000 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
2001 } else {
2002 ALOGW("Unsupported key type %d", keyType);
2003 rc = -1;
2004 }
2005
Kenny Root07438c82012-11-02 15:41:02 -07002006 if (rc) {
2007 return ::SYSTEM_ERROR;
2008 }
2009
Kenny Root655b9582013-04-04 08:37:42 -07002010 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07002011 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002012
2013 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2014 free(data);
2015
Kenny Rootee8068b2013-10-07 09:49:15 -07002016 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002017 keyBlob.setFallback(isFallback);
2018
Chad Brubaker72593ee2015-05-12 10:42:00 -07002019 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08002020 }
2021
Kenny Rootf9119d62013-04-03 09:22:15 -07002022 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2023 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002024 targetUid = getEffectiveUid(targetUid);
2025 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2026 flags & KEYSTORE_FLAG_ENCRYPTED);
2027 if (result != ::NO_ERROR) {
2028 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002029 }
Kenny Root07438c82012-11-02 15:41:02 -07002030 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002031 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002032
Chad Brubaker72593ee2015-05-12 10:42:00 -07002033 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2034 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002035 }
2036
Kenny Root07438c82012-11-02 15:41:02 -07002037 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2038 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002039 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002040 return ::PERMISSION_DENIED;
2041 }
Kenny Root07438c82012-11-02 15:41:02 -07002042
Chad Brubaker9489b792015-04-14 11:01:45 -07002043 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002044 Blob keyBlob;
2045 String8 name8(name);
2046
Kenny Rootd38a0b02013-02-13 12:59:14 -08002047 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002048
Kenny Root655b9582013-04-04 08:37:42 -07002049 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002050 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002051 if (responseCode != ::NO_ERROR) {
2052 return responseCode;
2053 }
2054
Chad Brubaker67d2a502015-03-11 17:21:18 +00002055 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002056 if (device == NULL) {
2057 ALOGE("no keymaster device; cannot sign");
2058 return ::SYSTEM_ERROR;
2059 }
2060
2061 if (device->sign_data == NULL) {
2062 ALOGE("device doesn't implement signing");
2063 return ::SYSTEM_ERROR;
2064 }
2065
2066 keymaster_rsa_sign_params_t params;
2067 params.digest_type = DIGEST_NONE;
2068 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002069 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002070 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002071 if (rc) {
2072 ALOGW("device couldn't sign data");
2073 return ::SYSTEM_ERROR;
2074 }
2075
2076 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002077 }
2078
Kenny Root07438c82012-11-02 15:41:02 -07002079 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2080 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002081 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002082 return ::PERMISSION_DENIED;
2083 }
Kenny Root70e3a862012-02-15 17:20:23 -08002084
Chad Brubaker9489b792015-04-14 11:01:45 -07002085 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002086 Blob keyBlob;
2087 String8 name8(name);
2088 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002089
Kenny Root655b9582013-04-04 08:37:42 -07002090 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002091 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002092 if (responseCode != ::NO_ERROR) {
2093 return responseCode;
2094 }
Kenny Root70e3a862012-02-15 17:20:23 -08002095
Chad Brubaker67d2a502015-03-11 17:21:18 +00002096 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002097 if (device == NULL) {
2098 return ::SYSTEM_ERROR;
2099 }
Kenny Root70e3a862012-02-15 17:20:23 -08002100
Kenny Root07438c82012-11-02 15:41:02 -07002101 if (device->verify_data == NULL) {
2102 return ::SYSTEM_ERROR;
2103 }
Kenny Root70e3a862012-02-15 17:20:23 -08002104
Kenny Root07438c82012-11-02 15:41:02 -07002105 keymaster_rsa_sign_params_t params;
2106 params.digest_type = DIGEST_NONE;
2107 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002108
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002109 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2110 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002111 if (rc) {
2112 return ::SYSTEM_ERROR;
2113 } else {
2114 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002115 }
2116 }
Kenny Root07438c82012-11-02 15:41:02 -07002117
2118 /*
2119 * TODO: The abstraction between things stored in hardware and regular blobs
2120 * of data stored on the filesystem should be moved down to keystore itself.
2121 * Unfortunately the Java code that calls this has naming conventions that it
2122 * knows about. Ideally keystore shouldn't be used to store random blobs of
2123 * data.
2124 *
2125 * Until that happens, it's necessary to have a separate "get_pubkey" and
2126 * "del_key" since the Java code doesn't really communicate what it's
2127 * intentions are.
2128 */
2129 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002130 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002131 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002132 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002133 return ::PERMISSION_DENIED;
2134 }
Kenny Root07438c82012-11-02 15:41:02 -07002135
Kenny Root07438c82012-11-02 15:41:02 -07002136 Blob keyBlob;
2137 String8 name8(name);
2138
Kenny Rootd38a0b02013-02-13 12:59:14 -08002139 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002140
Kenny Root655b9582013-04-04 08:37:42 -07002141 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002142 TYPE_KEY_PAIR);
2143 if (responseCode != ::NO_ERROR) {
2144 return responseCode;
2145 }
2146
Chad Brubaker67d2a502015-03-11 17:21:18 +00002147 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002148 if (device == NULL) {
2149 return ::SYSTEM_ERROR;
2150 }
2151
2152 if (device->get_keypair_public == NULL) {
2153 ALOGE("device has no get_keypair_public implementation!");
2154 return ::SYSTEM_ERROR;
2155 }
2156
Kenny Root17208e02013-09-04 13:56:03 -07002157 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002158 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2159 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002160 if (rc) {
2161 return ::SYSTEM_ERROR;
2162 }
2163
2164 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002165 }
Kenny Root07438c82012-11-02 15:41:02 -07002166
Kenny Root07438c82012-11-02 15:41:02 -07002167 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002168 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002169 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2170 if (result != ::NO_ERROR) {
2171 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002172 }
2173
2174 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002175 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002176
Kenny Root655b9582013-04-04 08:37:42 -07002177 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002178 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2179 }
2180
Kenny Root655b9582013-04-04 08:37:42 -07002181 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002182 return ::NO_ERROR;
2183 }
2184
2185 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002186 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002187 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2188 if (result != ::NO_ERROR) {
2189 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002190 }
2191
2192 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002193 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002194
Kenny Root655b9582013-04-04 08:37:42 -07002195 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002196 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2197 }
2198
Kenny Root655b9582013-04-04 08:37:42 -07002199 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002200 }
2201
2202 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002203 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002204 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002205 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002206 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002207 }
Kenny Root07438c82012-11-02 15:41:02 -07002208
2209 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002210 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002211
Kenny Root655b9582013-04-04 08:37:42 -07002212 if (access(filename.string(), R_OK) == -1) {
2213 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002214 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002215 }
2216
Kenny Root655b9582013-04-04 08:37:42 -07002217 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002218 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002219 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002220 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002221 }
2222
2223 struct stat s;
2224 int ret = fstat(fd, &s);
2225 close(fd);
2226 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002227 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002228 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002229 }
2230
Kenny Root36a9e232013-02-04 14:24:15 -08002231 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002232 }
2233
Kenny Rootd53bc922013-03-21 14:10:15 -07002234 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2235 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002236 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002237 pid_t spid = IPCThreadState::self()->getCallingPid();
2238 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002239 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002240 return -1L;
2241 }
2242
Chad Brubaker72593ee2015-05-12 10:42:00 -07002243 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002244 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002245 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002246 return state;
2247 }
2248
Kenny Rootd53bc922013-03-21 14:10:15 -07002249 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2250 srcUid = callingUid;
2251 } else if (!is_granted_to(callingUid, srcUid)) {
2252 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002253 return ::PERMISSION_DENIED;
2254 }
2255
Kenny Rootd53bc922013-03-21 14:10:15 -07002256 if (destUid == -1) {
2257 destUid = callingUid;
2258 }
2259
2260 if (srcUid != destUid) {
2261 if (static_cast<uid_t>(srcUid) != callingUid) {
2262 ALOGD("can only duplicate from caller to other or to same uid: "
2263 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2264 return ::PERMISSION_DENIED;
2265 }
2266
2267 if (!is_granted_to(callingUid, destUid)) {
2268 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2269 return ::PERMISSION_DENIED;
2270 }
2271 }
2272
2273 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002274 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002275
Kenny Rootd53bc922013-03-21 14:10:15 -07002276 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002277 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002278
Kenny Root655b9582013-04-04 08:37:42 -07002279 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2280 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002281 return ::SYSTEM_ERROR;
2282 }
2283
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002285 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002286 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002287 if (responseCode != ::NO_ERROR) {
2288 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002289 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002290
Chad Brubaker72593ee2015-05-12 10:42:00 -07002291 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002292 }
2293
Kenny Root1b0e3932013-09-05 13:06:32 -07002294 int32_t is_hardware_backed(const String16& keyType) {
2295 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002296 }
2297
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002298 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002299 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002300 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002301 return ::PERMISSION_DENIED;
2302 }
2303
Robin Lee4b84fdc2014-09-24 11:56:57 +01002304 String8 prefix = String8::format("%u_", targetUid);
2305 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002306 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002307 return ::SYSTEM_ERROR;
2308 }
2309
Robin Lee4b84fdc2014-09-24 11:56:57 +01002310 for (uint32_t i = 0; i < aliases.size(); i++) {
2311 String8 name8(aliases[i]);
2312 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002313 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002314 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002315 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002316 }
2317
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002318 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2319 const keymaster1_device_t* device = mKeyStore->getDevice();
2320 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2321 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2322 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2323 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2324 device->add_rng_entropy != NULL) {
2325 devResult = device->add_rng_entropy(device, data, dataLength);
2326 }
2327 if (fallback->add_rng_entropy) {
2328 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2329 }
2330 if (devResult) {
2331 return devResult;
2332 }
2333 if (fallbackResult) {
2334 return fallbackResult;
2335 }
2336 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002337 }
2338
Chad Brubaker17d68b92015-02-05 22:04:16 -08002339 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002340 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2341 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002342 uid = getEffectiveUid(uid);
2343 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2344 flags & KEYSTORE_FLAG_ENCRYPTED);
2345 if (rc != ::NO_ERROR) {
2346 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002347 }
2348
Chad Brubaker9489b792015-04-14 11:01:45 -07002349 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002350 bool isFallback = false;
2351 keymaster_key_blob_t blob;
2352 keymaster_key_characteristics_t *out = NULL;
2353
2354 const keymaster1_device_t* device = mKeyStore->getDevice();
2355 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002356 std::vector<keymaster_key_param_t> opParams(params.params);
2357 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002358 if (device == NULL) {
2359 return ::SYSTEM_ERROR;
2360 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002361 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002362 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2363 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002364 if (!entropy) {
2365 rc = KM_ERROR_OK;
2366 } else if (device->add_rng_entropy) {
2367 rc = device->add_rng_entropy(device, entropy, entropyLength);
2368 } else {
2369 rc = KM_ERROR_UNIMPLEMENTED;
2370 }
2371 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002372 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002373 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002374 }
2375 // If the HW device didn't support generate_key or generate_key failed
2376 // fall back to the software implementation.
2377 if (rc && fallback->generate_key != NULL) {
2378 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002379 if (!entropy) {
2380 rc = KM_ERROR_OK;
2381 } else if (fallback->add_rng_entropy) {
2382 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2383 } else {
2384 rc = KM_ERROR_UNIMPLEMENTED;
2385 }
2386 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002387 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002388 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002389 }
2390
2391 if (out) {
2392 if (outCharacteristics) {
2393 outCharacteristics->characteristics = *out;
2394 } else {
2395 keymaster_free_characteristics(out);
2396 }
2397 free(out);
2398 }
2399
2400 if (rc) {
2401 return rc;
2402 }
2403
2404 String8 name8(name);
2405 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2406
2407 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2408 keyBlob.setFallback(isFallback);
2409 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2410
2411 free(const_cast<uint8_t*>(blob.key_material));
2412
Chad Brubaker72593ee2015-05-12 10:42:00 -07002413 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002414 }
2415
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002416 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002417 const keymaster_blob_t* clientId,
2418 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002419 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002420 if (!outCharacteristics) {
2421 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2422 }
2423
2424 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2425
2426 Blob keyBlob;
2427 String8 name8(name);
2428 int rc;
2429
2430 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2431 TYPE_KEYMASTER_10);
2432 if (responseCode != ::NO_ERROR) {
2433 return responseCode;
2434 }
2435 keymaster_key_blob_t key;
2436 key.key_material_size = keyBlob.getLength();
2437 key.key_material = keyBlob.getValue();
2438 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2439 keymaster_key_characteristics_t *out = NULL;
2440 if (!dev->get_key_characteristics) {
2441 ALOGW("device does not implement get_key_characteristics");
2442 return KM_ERROR_UNIMPLEMENTED;
2443 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002444 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002445 if (out) {
2446 outCharacteristics->characteristics = *out;
2447 free(out);
2448 }
2449 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002450 }
2451
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002452 int32_t importKey(const String16& name, const KeymasterArguments& params,
2453 keymaster_key_format_t format, const uint8_t *keyData,
2454 size_t keyLength, int uid, int flags,
2455 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002456 uid = getEffectiveUid(uid);
2457 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2458 flags & KEYSTORE_FLAG_ENCRYPTED);
2459 if (rc != ::NO_ERROR) {
2460 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002461 }
2462
Chad Brubaker9489b792015-04-14 11:01:45 -07002463 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002464 bool isFallback = false;
2465 keymaster_key_blob_t blob;
2466 keymaster_key_characteristics_t *out = NULL;
2467
2468 const keymaster1_device_t* device = mKeyStore->getDevice();
2469 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002470 std::vector<keymaster_key_param_t> opParams(params.params);
2471 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2472 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002473 if (device == NULL) {
2474 return ::SYSTEM_ERROR;
2475 }
2476 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2477 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002478 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002479 }
2480 if (rc && fallback->import_key != NULL) {
2481 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002482 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002483 }
2484 if (out) {
2485 if (outCharacteristics) {
2486 outCharacteristics->characteristics = *out;
2487 } else {
2488 keymaster_free_characteristics(out);
2489 }
2490 free(out);
2491 }
2492 if (rc) {
2493 return rc;
2494 }
2495
2496 String8 name8(name);
2497 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2498
2499 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2500 keyBlob.setFallback(isFallback);
2501 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2502
2503 free((void*) blob.key_material);
2504
Chad Brubaker72593ee2015-05-12 10:42:00 -07002505 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002506 }
2507
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002508 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002509 const keymaster_blob_t* clientId,
2510 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002511
2512 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2513
2514 Blob keyBlob;
2515 String8 name8(name);
2516 int rc;
2517
2518 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2519 TYPE_KEYMASTER_10);
2520 if (responseCode != ::NO_ERROR) {
2521 result->resultCode = responseCode;
2522 return;
2523 }
2524 keymaster_key_blob_t key;
2525 key.key_material_size = keyBlob.getLength();
2526 key.key_material = keyBlob.getValue();
2527 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2528 if (!dev->export_key) {
2529 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2530 return;
2531 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002532 keymaster_blob_t output = {NULL, 0};
2533 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2534 result->exportData.reset(const_cast<uint8_t*>(output.data));
2535 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002536 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002537 }
2538
Chad Brubakerad6514a2015-04-09 14:00:26 -07002539
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002540 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002541 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002542 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002543 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2544 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2545 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2546 result->resultCode = ::PERMISSION_DENIED;
2547 return;
2548 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002549 if (!checkAllowedOperationParams(params.params)) {
2550 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2551 return;
2552 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002553 Blob keyBlob;
2554 String8 name8(name);
2555 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2556 TYPE_KEYMASTER_10);
2557 if (responseCode != ::NO_ERROR) {
2558 result->resultCode = responseCode;
2559 return;
2560 }
2561 keymaster_key_blob_t key;
2562 key.key_material_size = keyBlob.getLength();
2563 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002564 keymaster_operation_handle_t handle;
2565 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002566 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002567 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002568 Unique_keymaster_key_characteristics characteristics;
2569 characteristics.reset(new keymaster_key_characteristics_t);
2570 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2571 if (err) {
2572 result->resultCode = err;
2573 return;
2574 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002575 const hw_auth_token_t* authToken = NULL;
2576 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002577 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002578 // If per-operation auth is needed we need to begin the operation and
2579 // the client will need to authorize that operation before calling
2580 // update. Any other auth issues stop here.
2581 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2582 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002583 return;
2584 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002585 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002586 // Add entropy to the device first.
2587 if (entropy) {
2588 if (dev->add_rng_entropy) {
2589 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2590 } else {
2591 err = KM_ERROR_UNIMPLEMENTED;
2592 }
2593 if (err) {
2594 result->resultCode = err;
2595 return;
2596 }
2597 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002598 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2599 keymaster_key_param_set_t outParams = {NULL, 0};
2600 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002601
2602 // If there are too many operations abort the oldest operation that was
2603 // started as pruneable and try again.
2604 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2605 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2606 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2607 if (abort(oldest) != ::NO_ERROR) {
2608 break;
2609 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002610 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002611 }
2612 if (err) {
2613 result->resultCode = err;
2614 return;
2615 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002616
Chad Brubakerad6514a2015-04-09 14:00:26 -07002617 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2618 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002619 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002620 if (authToken) {
2621 mOperationMap.setOperationAuthToken(operationToken, authToken);
2622 }
2623 // Return the authentication lookup result. If this is a per operation
2624 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2625 // application should get an auth token using the handle before the
2626 // first call to update, which will fail if keystore hasn't received the
2627 // auth token.
2628 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002629 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002630 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002631 if (outParams.params) {
2632 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2633 free(outParams.params);
2634 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002635 }
2636
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002637 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2638 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002639 if (!checkAllowedOperationParams(params.params)) {
2640 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2641 return;
2642 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002643 const keymaster1_device_t* dev;
2644 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002645 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002646 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2647 return;
2648 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002649 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002650 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2651 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002652 result->resultCode = authResult;
2653 return;
2654 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002655 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2656 keymaster_blob_t input = {data, dataLength};
2657 size_t consumed = 0;
2658 keymaster_blob_t output = {NULL, 0};
2659 keymaster_key_param_set_t outParams = {NULL, 0};
2660
2661 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2662 &output);
2663 result->data.reset(const_cast<uint8_t*>(output.data));
2664 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002665 result->inputConsumed = consumed;
2666 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002667 if (outParams.params) {
2668 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2669 free(outParams.params);
2670 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002671 }
2672
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002673 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2674 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002675 if (!checkAllowedOperationParams(params.params)) {
2676 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2677 return;
2678 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002679 const keymaster1_device_t* dev;
2680 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002681 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002682 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2683 return;
2684 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002685 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002686 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2687 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002688 result->resultCode = authResult;
2689 return;
2690 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002691
Chad Brubaker57e106d2015-06-01 12:59:00 -07002692 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2693 keymaster_blob_t input = {signature, signatureLength};
2694 keymaster_blob_t output = {NULL, 0};
2695 keymaster_key_param_set_t outParams = {NULL, 0};
2696 keymaster_error_t err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002697 // Remove the operation regardless of the result
2698 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002699 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002700
2701 result->data.reset(const_cast<uint8_t*>(output.data));
2702 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002703 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002704 if (outParams.params) {
2705 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2706 free(outParams.params);
2707 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002708 }
2709
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002710 int32_t abort(const sp<IBinder>& token) {
2711 const keymaster1_device_t* dev;
2712 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002713 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002714 return KM_ERROR_INVALID_OPERATION_HANDLE;
2715 }
2716 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002717 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002718 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002719 rc = KM_ERROR_UNIMPLEMENTED;
2720 } else {
2721 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002722 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002723 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002724 if (rc) {
2725 return rc;
2726 }
2727 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002728 }
2729
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002730 bool isOperationAuthorized(const sp<IBinder>& token) {
2731 const keymaster1_device_t* dev;
2732 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002733 const keymaster_key_characteristics_t* characteristics;
2734 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002735 return false;
2736 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002737 const hw_auth_token_t* authToken = NULL;
2738 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002739 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002740 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2741 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002742 }
2743
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002744 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002745 if (!checkBinderPermission(P_ADD_AUTH)) {
2746 ALOGW("addAuthToken: permission denied for %d",
2747 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002748 return ::PERMISSION_DENIED;
2749 }
2750 if (length != sizeof(hw_auth_token_t)) {
2751 return KM_ERROR_INVALID_ARGUMENT;
2752 }
2753 hw_auth_token_t* authToken = new hw_auth_token_t;
2754 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2755 // The table takes ownership of authToken.
2756 mAuthTokenTable.AddAuthenticationToken(authToken);
2757 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002758 }
2759
Kenny Root07438c82012-11-02 15:41:02 -07002760private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002761 static const int32_t UID_SELF = -1;
2762
2763 /**
2764 * Get the effective target uid for a binder operation that takes an
2765 * optional uid as the target.
2766 */
2767 inline uid_t getEffectiveUid(int32_t targetUid) {
2768 if (targetUid == UID_SELF) {
2769 return IPCThreadState::self()->getCallingUid();
2770 }
2771 return static_cast<uid_t>(targetUid);
2772 }
2773
2774 /**
2775 * Check if the caller of the current binder method has the required
2776 * permission and if acting on other uids the grants to do so.
2777 */
2778 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2779 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2780 pid_t spid = IPCThreadState::self()->getCallingPid();
2781 if (!has_permission(callingUid, permission, spid)) {
2782 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2783 return false;
2784 }
2785 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2786 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2787 return false;
2788 }
2789 return true;
2790 }
2791
2792 /**
2793 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002794 * permission and the target uid is the caller or the caller is system.
2795 */
2796 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2797 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2798 pid_t spid = IPCThreadState::self()->getCallingPid();
2799 if (!has_permission(callingUid, permission, spid)) {
2800 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2801 return false;
2802 }
2803 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2804 }
2805
2806 /**
2807 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002808 * permission or the target of the operation is the caller's uid. This is
2809 * for operation where the permission is only for cross-uid activity and all
2810 * uids are allowed to act on their own (ie: clearing all entries for a
2811 * given uid).
2812 */
2813 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2814 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2815 if (getEffectiveUid(targetUid) == callingUid) {
2816 return true;
2817 } else {
2818 return checkBinderPermission(permission, targetUid);
2819 }
2820 }
2821
2822 /**
2823 * Helper method to check that the caller has the required permission as
2824 * well as the keystore is in the unlocked state if checkUnlocked is true.
2825 *
2826 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2827 * otherwise the state of keystore when not unlocked and checkUnlocked is
2828 * true.
2829 */
2830 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2831 bool checkUnlocked = true) {
2832 if (!checkBinderPermission(permission, targetUid)) {
2833 return ::PERMISSION_DENIED;
2834 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002835 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002836 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2837 return state;
2838 }
2839
2840 return ::NO_ERROR;
2841
2842 }
2843
Kenny Root9d45d1c2013-02-14 10:32:30 -08002844 inline bool isKeystoreUnlocked(State state) {
2845 switch (state) {
2846 case ::STATE_NO_ERROR:
2847 return true;
2848 case ::STATE_UNINITIALIZED:
2849 case ::STATE_LOCKED:
2850 return false;
2851 }
2852 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002853 }
2854
Chad Brubaker67d2a502015-03-11 17:21:18 +00002855 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002856 const int32_t device_api = device->common.module->module_api_version;
2857 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2858 switch (keyType) {
2859 case TYPE_RSA:
2860 case TYPE_DSA:
2861 case TYPE_EC:
2862 return true;
2863 default:
2864 return false;
2865 }
2866 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2867 switch (keyType) {
2868 case TYPE_RSA:
2869 return true;
2870 case TYPE_DSA:
2871 return device->flags & KEYMASTER_SUPPORTS_DSA;
2872 case TYPE_EC:
2873 return device->flags & KEYMASTER_SUPPORTS_EC;
2874 default:
2875 return false;
2876 }
2877 } else {
2878 return keyType == TYPE_RSA;
2879 }
2880 }
2881
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002882 /**
2883 * Check that all keymaster_key_param_t's provided by the application are
2884 * allowed. Any parameter that keystore adds itself should be disallowed here.
2885 */
2886 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2887 for (auto param: params) {
2888 switch (param.tag) {
2889 case KM_TAG_AUTH_TOKEN:
2890 return false;
2891 default:
2892 break;
2893 }
2894 }
2895 return true;
2896 }
2897
2898 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2899 const keymaster1_device_t* dev,
2900 const std::vector<keymaster_key_param_t>& params,
2901 keymaster_key_characteristics_t* out) {
2902 UniquePtr<keymaster_blob_t> appId;
2903 UniquePtr<keymaster_blob_t> appData;
2904 for (auto param : params) {
2905 if (param.tag == KM_TAG_APPLICATION_ID) {
2906 appId.reset(new keymaster_blob_t);
2907 appId->data = param.blob.data;
2908 appId->data_length = param.blob.data_length;
2909 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2910 appData.reset(new keymaster_blob_t);
2911 appData->data = param.blob.data;
2912 appData->data_length = param.blob.data_length;
2913 }
2914 }
2915 keymaster_key_characteristics_t* result = NULL;
2916 if (!dev->get_key_characteristics) {
2917 return KM_ERROR_UNIMPLEMENTED;
2918 }
2919 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2920 appData.get(), &result);
2921 if (result) {
2922 *out = *result;
2923 free(result);
2924 }
2925 return error;
2926 }
2927
2928 /**
2929 * Get the auth token for this operation from the auth token table.
2930 *
2931 * Returns ::NO_ERROR if the auth token was set or none was required.
2932 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2933 * authorization token exists for that operation and
2934 * failOnTokenMissing is false.
2935 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2936 * token for the operation
2937 */
2938 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2939 keymaster_operation_handle_t handle,
2940 const hw_auth_token_t** authToken,
2941 bool failOnTokenMissing = true) {
2942
2943 std::vector<keymaster_key_param_t> allCharacteristics;
2944 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2945 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2946 }
2947 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2948 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2949 }
2950 keymaster::AuthTokenTable::Error err =
2951 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2952 allCharacteristics.size(), handle, authToken);
2953 switch (err) {
2954 case keymaster::AuthTokenTable::OK:
2955 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2956 return ::NO_ERROR;
2957 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2958 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2959 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2960 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2961 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2962 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2963 (int32_t) ::OP_AUTH_NEEDED;
2964 default:
2965 ALOGE("Unexpected FindAuthorization return value %d", err);
2966 return KM_ERROR_INVALID_ARGUMENT;
2967 }
2968 }
2969
2970 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2971 const hw_auth_token_t* token) {
2972 if (token) {
2973 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2974 reinterpret_cast<const uint8_t*>(token),
2975 sizeof(hw_auth_token_t)));
2976 }
2977 }
2978
2979 /**
2980 * Add the auth token for the operation to the param list if the operation
2981 * requires authorization. Uses the cached result in the OperationMap if available
2982 * otherwise gets the token from the AuthTokenTable and caches the result.
2983 *
2984 * Returns ::NO_ERROR if the auth token was added or not needed.
2985 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2986 * authenticated.
2987 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2988 * operation token.
2989 */
2990 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2991 std::vector<keymaster_key_param_t>* params) {
2992 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002993 mOperationMap.getOperationAuthToken(token, &authToken);
2994 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002995 const keymaster1_device_t* dev;
2996 keymaster_operation_handle_t handle;
2997 const keymaster_key_characteristics_t* characteristics = NULL;
2998 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
2999 return KM_ERROR_INVALID_OPERATION_HANDLE;
3000 }
3001 int32_t result = getAuthToken(characteristics, handle, &authToken);
3002 if (result != ::NO_ERROR) {
3003 return result;
3004 }
3005 if (authToken) {
3006 mOperationMap.setOperationAuthToken(token, authToken);
3007 }
3008 }
3009 addAuthToParams(params, authToken);
3010 return ::NO_ERROR;
3011 }
3012
Kenny Root07438c82012-11-02 15:41:02 -07003013 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003014 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003015 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003016};
3017
3018}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003019
3020int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003021 if (argc < 2) {
3022 ALOGE("A directory must be specified!");
3023 return 1;
3024 }
3025 if (chdir(argv[1]) == -1) {
3026 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3027 return 1;
3028 }
3029
3030 Entropy entropy;
3031 if (!entropy.open()) {
3032 return 1;
3033 }
Kenny Root70e3a862012-02-15 17:20:23 -08003034
Shawn Willden80843db2015-02-24 09:31:25 -07003035 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003036 if (keymaster_device_initialize(&dev)) {
3037 ALOGE("keystore keymaster could not be initialized; exiting");
3038 return 1;
3039 }
3040
Chad Brubaker67d2a502015-03-11 17:21:18 +00003041 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003042 if (fallback_keymaster_device_initialize(&fallback)) {
3043 ALOGE("software keymaster could not be initialized; exiting");
3044 return 1;
3045 }
3046
Riley Spahneaabae92014-06-30 12:39:52 -07003047 ks_is_selinux_enabled = is_selinux_enabled();
3048 if (ks_is_selinux_enabled) {
3049 union selinux_callback cb;
3050 cb.func_log = selinux_log_callback;
3051 selinux_set_callback(SELINUX_CB_LOG, cb);
3052 if (getcon(&tctx) != 0) {
3053 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3054 return -1;
3055 }
3056 } else {
3057 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3058 }
3059
Chad Brubaker67d2a502015-03-11 17:21:18 +00003060 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003061 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003062 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3063 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3064 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3065 if (ret != android::OK) {
3066 ALOGE("Couldn't register binder service!");
3067 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003068 }
Kenny Root07438c82012-11-02 15:41:02 -07003069
3070 /*
3071 * We're the only thread in existence, so we're just going to process
3072 * Binder transaction as a single-threaded program.
3073 */
3074 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003075
3076 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003077 return 1;
3078}