blob: a65a34c293788dda356ea355ed5268d2a4c8dff3 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Kenny Root17208e02013-09-04 13:56:03 -070046#include <keymaster/softkeymaster.h>
Chad Brubaker919cb2a2015-02-05 21:58:25 -080047#include <keymaster/soft_keymaster_device.h>
Kenny Root17208e02013-09-04 13:56:03 -070048
Kenny Root26cfc082013-09-11 14:38:56 -070049#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070050#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080052
Kenny Root07438c82012-11-02 15:41:02 -070053#include <keystore/IKeystoreService.h>
54#include <binder/IPCThreadState.h>
55#include <binder/IServiceManager.h>
56
Kenny Roota91203b2012-02-15 15:00:46 -080057#include <cutils/log.h>
58#include <cutils/sockets.h>
59#include <private/android_filesystem_config.h>
60
Kenny Root07438c82012-11-02 15:41:02 -070061#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080062
Riley Spahneaabae92014-06-30 12:39:52 -070063#include <selinux/android.h>
64
Chad Brubakerd80c7b42015-03-31 11:04:28 -070065#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070066#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080067#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070068
Kenny Roota91203b2012-02-15 15:00:46 -080069/* KeyStore is a secured storage for key-value pairs. In this implementation,
70 * each file stores one key-value pair. Keys are encoded in file names, and
71 * values are encrypted with checksums. The encryption key is protected by a
72 * user-defined password. To keep things simple, buffers are always larger than
73 * the maximum space we needed, so boundary checks on buffers are omitted. */
74
75#define KEY_SIZE ((NAME_MAX - 15) / 2)
76#define VALUE_SIZE 32768
77#define PASSWORD_SIZE VALUE_SIZE
78
Kenny Root822c3a92012-03-23 16:34:39 -070079
Kenny Root96427ba2013-08-16 14:02:41 -070080struct BIGNUM_Delete {
81 void operator()(BIGNUM* p) const {
82 BN_free(p);
83 }
84};
85typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
86
Kenny Root822c3a92012-03-23 16:34:39 -070087struct BIO_Delete {
88 void operator()(BIO* p) const {
89 BIO_free(p);
90 }
91};
92typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
93
94struct EVP_PKEY_Delete {
95 void operator()(EVP_PKEY* p) const {
96 EVP_PKEY_free(p);
97 }
98};
99typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
100
101struct PKCS8_PRIV_KEY_INFO_Delete {
102 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
103 PKCS8_PRIV_KEY_INFO_free(p);
104 }
105};
106typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
107
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700108static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800109 int rc;
110
111 const hw_module_t* mod;
112 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
113 if (rc) {
114 ALOGE("could not find any keystore module");
115 goto out;
116 }
117
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700118 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800119 if (rc) {
120 ALOGE("could not open keymaster device in %s (%s)",
121 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
122 goto out;
123 }
124
125 return 0;
126
127out:
128 *dev = NULL;
129 return rc;
130}
131
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800132static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
133 keymaster::SoftKeymasterDevice* softkeymaster =
134 new keymaster::SoftKeymasterDevice();
135 // SoftKeymasterDevice is designed to make this cast safe.
136 *dev = reinterpret_cast<keymaster1_device_t*>(softkeymaster);
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800137 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800138}
139
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700140static void keymaster_device_release(keymaster0_device_t* dev) {
141 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800142}
143
Kenny Root07438c82012-11-02 15:41:02 -0700144/***************
145 * PERMISSIONS *
146 ***************/
147
148/* Here are the permissions, actions, users, and the main function. */
149typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100150 P_TEST = 1 << 0,
151 P_GET = 1 << 1,
152 P_INSERT = 1 << 2,
153 P_DELETE = 1 << 3,
154 P_EXIST = 1 << 4,
155 P_SAW = 1 << 5,
156 P_RESET = 1 << 6,
157 P_PASSWORD = 1 << 7,
158 P_LOCK = 1 << 8,
159 P_UNLOCK = 1 << 9,
160 P_ZERO = 1 << 10,
161 P_SIGN = 1 << 11,
162 P_VERIFY = 1 << 12,
163 P_GRANT = 1 << 13,
164 P_DUPLICATE = 1 << 14,
165 P_CLEAR_UID = 1 << 15,
166 P_RESET_UID = 1 << 16,
167 P_SYNC_UID = 1 << 17,
168 P_PASSWORD_UID = 1 << 18,
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700169 P_ADD_AUTH = 1 << 19,
Kenny Root07438c82012-11-02 15:41:02 -0700170} perm_t;
171
172static struct user_euid {
173 uid_t uid;
174 uid_t euid;
175} user_euids[] = {
176 {AID_VPN, AID_SYSTEM},
177 {AID_WIFI, AID_SYSTEM},
178 {AID_ROOT, AID_SYSTEM},
179};
180
Riley Spahneaabae92014-06-30 12:39:52 -0700181/* perm_labels associcated with keystore_key SELinux class verbs. */
182const char *perm_labels[] = {
183 "test",
184 "get",
185 "insert",
186 "delete",
187 "exist",
188 "saw",
189 "reset",
190 "password",
191 "lock",
192 "unlock",
193 "zero",
194 "sign",
195 "verify",
196 "grant",
197 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100198 "clear_uid",
199 "reset_uid",
200 "sync_uid",
201 "password_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700202 "add_auth",
Riley Spahneaabae92014-06-30 12:39:52 -0700203};
204
Kenny Root07438c82012-11-02 15:41:02 -0700205static struct user_perm {
206 uid_t uid;
207 perm_t perms;
208} user_perms[] = {
209 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
210 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
211 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
212 {AID_ROOT, static_cast<perm_t>(P_GET) },
213};
214
215static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
216 | P_VERIFY);
217
Riley Spahneaabae92014-06-30 12:39:52 -0700218static char *tctx;
219static int ks_is_selinux_enabled;
220
221static const char *get_perm_label(perm_t perm) {
222 unsigned int index = ffs(perm);
223 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
224 return perm_labels[index - 1];
225 } else {
226 ALOGE("Keystore: Failed to retrieve permission label.\n");
227 abort();
228 }
229}
230
Kenny Root655b9582013-04-04 08:37:42 -0700231/**
232 * Returns the app ID (in the Android multi-user sense) for the current
233 * UNIX UID.
234 */
235static uid_t get_app_id(uid_t uid) {
236 return uid % AID_USER;
237}
238
239/**
240 * Returns the user ID (in the Android multi-user sense) for the current
241 * UNIX UID.
242 */
243static uid_t get_user_id(uid_t uid) {
244 return uid / AID_USER;
245}
246
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700247static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700248 if (!ks_is_selinux_enabled) {
249 return true;
250 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000251
Riley Spahneaabae92014-06-30 12:39:52 -0700252 char *sctx = NULL;
253 const char *selinux_class = "keystore_key";
254 const char *str_perm = get_perm_label(perm);
255
256 if (!str_perm) {
257 return false;
258 }
259
260 if (getpidcon(spid, &sctx) != 0) {
261 ALOGE("SELinux: Failed to get source pid context.\n");
262 return false;
263 }
264
265 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
266 NULL) == 0;
267 freecon(sctx);
268 return allowed;
269}
270
271static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700272 // All system users are equivalent for multi-user support.
273 if (get_app_id(uid) == AID_SYSTEM) {
274 uid = AID_SYSTEM;
275 }
276
Kenny Root07438c82012-11-02 15:41:02 -0700277 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
278 struct user_perm user = user_perms[i];
279 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700280 return (user.perms & perm) &&
281 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700282 }
283 }
284
Riley Spahneaabae92014-06-30 12:39:52 -0700285 return (DEFAULT_PERMS & perm) &&
286 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700287}
288
Kenny Root49468902013-03-19 13:41:33 -0700289/**
290 * Returns the UID that the callingUid should act as. This is here for
291 * legacy support of the WiFi and VPN systems and should be removed
292 * when WiFi can operate in its own namespace.
293 */
Kenny Root07438c82012-11-02 15:41:02 -0700294static uid_t get_keystore_euid(uid_t uid) {
295 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
296 struct user_euid user = user_euids[i];
297 if (user.uid == uid) {
298 return user.euid;
299 }
300 }
301
302 return uid;
303}
304
Kenny Root49468902013-03-19 13:41:33 -0700305/**
306 * Returns true if the callingUid is allowed to interact in the targetUid's
307 * namespace.
308 */
309static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
310 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
311 struct user_euid user = user_euids[i];
312 if (user.euid == callingUid && user.uid == targetUid) {
313 return true;
314 }
315 }
316
317 return false;
318}
319
Kenny Root007cb232014-07-30 16:59:42 -0700320/**
321 * Allow the system to perform some privileged tasks that have to do with
322 * system maintenance. This should not be used for any function that uses
323 * the keys in any way (e.g., signing).
324 */
325static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
326 return callingUid == targetUid || callingUid == AID_SYSTEM;
327}
328
Kenny Roota91203b2012-02-15 15:00:46 -0800329/* Here is the encoding of keys. This is necessary in order to allow arbitrary
330 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
331 * into two bytes. The first byte is one of [+-.] which represents the first
332 * two bits of the character. The second byte encodes the rest of the bits into
333 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
334 * that Base64 cannot be used here due to the need of prefix match on keys. */
335
Kenny Root655b9582013-04-04 08:37:42 -0700336static size_t encode_key_length(const android::String8& keyName) {
337 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
338 size_t length = keyName.length();
339 for (int i = length; i > 0; --i, ++in) {
340 if (*in < '0' || *in > '~') {
341 ++length;
342 }
343 }
344 return length;
345}
346
Kenny Root07438c82012-11-02 15:41:02 -0700347static int encode_key(char* out, const android::String8& keyName) {
348 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
349 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800350 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700351 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800352 *out = '+' + (*in >> 6);
353 *++out = '0' + (*in & 0x3F);
354 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700355 } else {
356 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800357 }
358 }
359 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800360 return length;
361}
362
Kenny Root07438c82012-11-02 15:41:02 -0700363/*
364 * Converts from the "escaped" format on disk to actual name.
365 * This will be smaller than the input string.
366 *
367 * Characters that should combine with the next at the end will be truncated.
368 */
369static size_t decode_key_length(const char* in, size_t length) {
370 size_t outLength = 0;
371
372 for (const char* end = in + length; in < end; in++) {
373 /* This combines with the next character. */
374 if (*in < '0' || *in > '~') {
375 continue;
376 }
377
378 outLength++;
379 }
380 return outLength;
381}
382
383static void decode_key(char* out, const char* in, size_t length) {
384 for (const char* end = in + length; in < end; in++) {
385 if (*in < '0' || *in > '~') {
386 /* Truncate combining characters at the end. */
387 if (in + 1 >= end) {
388 break;
389 }
390
391 *out = (*in++ - '+') << 6;
392 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800393 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700394 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800395 }
396 }
397 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800398}
399
400static size_t readFully(int fd, uint8_t* data, size_t size) {
401 size_t remaining = size;
402 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800403 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800404 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800405 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800406 }
407 data += n;
408 remaining -= n;
409 }
410 return size;
411}
412
413static size_t writeFully(int fd, uint8_t* data, size_t size) {
414 size_t remaining = size;
415 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800416 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
417 if (n < 0) {
418 ALOGW("write failed: %s", strerror(errno));
419 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800420 }
421 data += n;
422 remaining -= n;
423 }
424 return size;
425}
426
427class Entropy {
428public:
429 Entropy() : mRandom(-1) {}
430 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800431 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800432 close(mRandom);
433 }
434 }
435
436 bool open() {
437 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800438 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
439 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800440 ALOGE("open: %s: %s", randomDevice, strerror(errno));
441 return false;
442 }
443 return true;
444 }
445
Kenny Root51878182012-03-13 12:53:19 -0700446 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800447 return (readFully(mRandom, data, size) == size);
448 }
449
450private:
451 int mRandom;
452};
453
454/* Here is the file format. There are two parts in blob.value, the secret and
455 * the description. The secret is stored in ciphertext, and its original size
456 * can be found in blob.length. The description is stored after the secret in
457 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700458 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700459 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800460 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
461 * and decryptBlob(). Thus they should not be accessed from outside. */
462
Kenny Root822c3a92012-03-23 16:34:39 -0700463/* ** Note to future implementors of encryption: **
464 * Currently this is the construction:
465 * metadata || Enc(MD5(data) || data)
466 *
467 * This should be the construction used for encrypting if re-implementing:
468 *
469 * Derive independent keys for encryption and MAC:
470 * Kenc = AES_encrypt(masterKey, "Encrypt")
471 * Kmac = AES_encrypt(masterKey, "MAC")
472 *
473 * Store this:
474 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
475 * HMAC(Kmac, metadata || Enc(data))
476 */
Kenny Roota91203b2012-02-15 15:00:46 -0800477struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700478 uint8_t version;
479 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700480 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800481 uint8_t info;
482 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700483 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800484 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700485 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800486 int32_t length; // in network byte order when encrypted
487 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
488};
489
Kenny Root822c3a92012-03-23 16:34:39 -0700490typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700491 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700492 TYPE_GENERIC = 1,
493 TYPE_MASTER_KEY = 2,
494 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800495 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700496} BlobType;
497
Kenny Rootf9119d62013-04-03 09:22:15 -0700498static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700499
Kenny Roota91203b2012-02-15 15:00:46 -0800500class Blob {
501public:
Kenny Root07438c82012-11-02 15:41:02 -0700502 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
503 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800504 mBlob.length = valueLength;
505 memcpy(mBlob.value, value, valueLength);
506
507 mBlob.info = infoLength;
508 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700509
Kenny Root07438c82012-11-02 15:41:02 -0700510 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700511 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700512
Kenny Rootee8068b2013-10-07 09:49:15 -0700513 if (type == TYPE_MASTER_KEY) {
514 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
515 } else {
516 mBlob.flags = KEYSTORE_FLAG_NONE;
517 }
Kenny Roota91203b2012-02-15 15:00:46 -0800518 }
519
520 Blob(blob b) {
521 mBlob = b;
522 }
523
524 Blob() {}
525
Kenny Root51878182012-03-13 12:53:19 -0700526 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800527 return mBlob.value;
528 }
529
Kenny Root51878182012-03-13 12:53:19 -0700530 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800531 return mBlob.length;
532 }
533
Kenny Root51878182012-03-13 12:53:19 -0700534 const uint8_t* getInfo() const {
535 return mBlob.value + mBlob.length;
536 }
537
538 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800539 return mBlob.info;
540 }
541
Kenny Root822c3a92012-03-23 16:34:39 -0700542 uint8_t getVersion() const {
543 return mBlob.version;
544 }
545
Kenny Rootf9119d62013-04-03 09:22:15 -0700546 bool isEncrypted() const {
547 if (mBlob.version < 2) {
548 return true;
549 }
550
551 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
552 }
553
554 void setEncrypted(bool encrypted) {
555 if (encrypted) {
556 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
557 } else {
558 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
559 }
560 }
561
Kenny Root17208e02013-09-04 13:56:03 -0700562 bool isFallback() const {
563 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
564 }
565
566 void setFallback(bool fallback) {
567 if (fallback) {
568 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
569 } else {
570 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
571 }
572 }
573
Kenny Root822c3a92012-03-23 16:34:39 -0700574 void setVersion(uint8_t version) {
575 mBlob.version = version;
576 }
577
578 BlobType getType() const {
579 return BlobType(mBlob.type);
580 }
581
582 void setType(BlobType type) {
583 mBlob.type = uint8_t(type);
584 }
585
Kenny Rootf9119d62013-04-03 09:22:15 -0700586 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
587 ALOGV("writing blob %s", filename);
588 if (isEncrypted()) {
589 if (state != STATE_NO_ERROR) {
590 ALOGD("couldn't insert encrypted blob while not unlocked");
591 return LOCKED;
592 }
593
594 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
595 ALOGW("Could not read random data for: %s", filename);
596 return SYSTEM_ERROR;
597 }
Kenny Roota91203b2012-02-15 15:00:46 -0800598 }
599
600 // data includes the value and the value's length
601 size_t dataLength = mBlob.length + sizeof(mBlob.length);
602 // pad data to the AES_BLOCK_SIZE
603 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
604 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
605 // encrypted data includes the digest value
606 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
607 // move info after space for padding
608 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
609 // zero padding area
610 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
611
612 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800613
Kenny Rootf9119d62013-04-03 09:22:15 -0700614 if (isEncrypted()) {
615 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800616
Kenny Rootf9119d62013-04-03 09:22:15 -0700617 uint8_t vector[AES_BLOCK_SIZE];
618 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
619 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
620 aes_key, vector, AES_ENCRYPT);
621 }
622
Kenny Roota91203b2012-02-15 15:00:46 -0800623 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
624 size_t fileLength = encryptedLength + headerLength + mBlob.info;
625
626 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800627 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
628 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
629 if (out < 0) {
630 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800631 return SYSTEM_ERROR;
632 }
633 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
634 if (close(out) != 0) {
635 return SYSTEM_ERROR;
636 }
637 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800638 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800639 unlink(tmpFileName);
640 return SYSTEM_ERROR;
641 }
Kenny Root150ca932012-11-14 14:29:02 -0800642 if (rename(tmpFileName, filename) == -1) {
643 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
644 return SYSTEM_ERROR;
645 }
646 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800647 }
648
Kenny Rootf9119d62013-04-03 09:22:15 -0700649 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
650 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800651 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
652 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800653 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
654 }
655 // fileLength may be less than sizeof(mBlob) since the in
656 // memory version has extra padding to tolerate rounding up to
657 // the AES_BLOCK_SIZE
658 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
659 if (close(in) != 0) {
660 return SYSTEM_ERROR;
661 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700662
663 if (isEncrypted() && (state != STATE_NO_ERROR)) {
664 return LOCKED;
665 }
666
Kenny Roota91203b2012-02-15 15:00:46 -0800667 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
668 if (fileLength < headerLength) {
669 return VALUE_CORRUPTED;
670 }
671
672 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700673 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800674 return VALUE_CORRUPTED;
675 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700676
677 ssize_t digestedLength;
678 if (isEncrypted()) {
679 if (encryptedLength % AES_BLOCK_SIZE != 0) {
680 return VALUE_CORRUPTED;
681 }
682
683 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
684 mBlob.vector, AES_DECRYPT);
685 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
686 uint8_t computedDigest[MD5_DIGEST_LENGTH];
687 MD5(mBlob.digested, digestedLength, computedDigest);
688 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
689 return VALUE_CORRUPTED;
690 }
691 } else {
692 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800693 }
694
695 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
696 mBlob.length = ntohl(mBlob.length);
697 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
698 return VALUE_CORRUPTED;
699 }
700 if (mBlob.info != 0) {
701 // move info from after padding to after data
702 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
703 }
Kenny Root07438c82012-11-02 15:41:02 -0700704 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800705 }
706
707private:
708 struct blob mBlob;
709};
710
Kenny Root655b9582013-04-04 08:37:42 -0700711class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800712public:
Kenny Root655b9582013-04-04 08:37:42 -0700713 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
714 asprintf(&mUserDir, "user_%u", mUserId);
715 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
716 }
717
718 ~UserState() {
719 free(mUserDir);
720 free(mMasterKeyFile);
721 }
722
723 bool initialize() {
724 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
725 ALOGE("Could not create directory '%s'", mUserDir);
726 return false;
727 }
728
729 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800730 setState(STATE_LOCKED);
731 } else {
732 setState(STATE_UNINITIALIZED);
733 }
Kenny Root70e3a862012-02-15 17:20:23 -0800734
Kenny Root655b9582013-04-04 08:37:42 -0700735 return true;
736 }
737
738 uid_t getUserId() const {
739 return mUserId;
740 }
741
742 const char* getUserDirName() const {
743 return mUserDir;
744 }
745
746 const char* getMasterKeyFileName() const {
747 return mMasterKeyFile;
748 }
749
750 void setState(State state) {
751 mState = state;
752 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
753 mRetry = MAX_RETRY;
754 }
Kenny Roota91203b2012-02-15 15:00:46 -0800755 }
756
Kenny Root51878182012-03-13 12:53:19 -0700757 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800758 return mState;
759 }
760
Kenny Root51878182012-03-13 12:53:19 -0700761 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800762 return mRetry;
763 }
764
Kenny Root655b9582013-04-04 08:37:42 -0700765 void zeroizeMasterKeysInMemory() {
766 memset(mMasterKey, 0, sizeof(mMasterKey));
767 memset(mSalt, 0, sizeof(mSalt));
768 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
769 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800770 }
771
Kenny Root655b9582013-04-04 08:37:42 -0700772 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
773 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800774 return SYSTEM_ERROR;
775 }
Kenny Root655b9582013-04-04 08:37:42 -0700776 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800777 if (response != NO_ERROR) {
778 return response;
779 }
780 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700781 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800782 }
783
Robin Lee4e865752014-08-19 17:37:55 +0100784 ResponseCode copyMasterKey(UserState* src) {
785 if (mState != STATE_UNINITIALIZED) {
786 return ::SYSTEM_ERROR;
787 }
788 if (src->getState() != STATE_NO_ERROR) {
789 return ::SYSTEM_ERROR;
790 }
791 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
792 setupMasterKeys();
793 return ::NO_ERROR;
794 }
795
Kenny Root655b9582013-04-04 08:37:42 -0700796 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800797 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
798 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
799 AES_KEY passwordAesKey;
800 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700801 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700802 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800803 }
804
Kenny Root655b9582013-04-04 08:37:42 -0700805 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
806 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800807 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800808 return SYSTEM_ERROR;
809 }
810
811 // we read the raw blob to just to get the salt to generate
812 // the AES key, then we create the Blob to use with decryptBlob
813 blob rawBlob;
814 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
815 if (close(in) != 0) {
816 return SYSTEM_ERROR;
817 }
818 // find salt at EOF if present, otherwise we have an old file
819 uint8_t* salt;
820 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
821 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
822 } else {
823 salt = NULL;
824 }
825 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
826 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
827 AES_KEY passwordAesKey;
828 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
829 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700830 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
831 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800832 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700833 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800834 }
835 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
836 // if salt was missing, generate one and write a new master key file with the salt.
837 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700838 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800839 return SYSTEM_ERROR;
840 }
Kenny Root655b9582013-04-04 08:37:42 -0700841 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800842 }
843 if (response == NO_ERROR) {
844 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
845 setupMasterKeys();
846 }
847 return response;
848 }
849 if (mRetry <= 0) {
850 reset();
851 return UNINITIALIZED;
852 }
853 --mRetry;
854 switch (mRetry) {
855 case 0: return WRONG_PASSWORD_0;
856 case 1: return WRONG_PASSWORD_1;
857 case 2: return WRONG_PASSWORD_2;
858 case 3: return WRONG_PASSWORD_3;
859 default: return WRONG_PASSWORD_3;
860 }
861 }
862
Kenny Root655b9582013-04-04 08:37:42 -0700863 AES_KEY* getEncryptionKey() {
864 return &mMasterKeyEncryption;
865 }
866
867 AES_KEY* getDecryptionKey() {
868 return &mMasterKeyDecryption;
869 }
870
Kenny Roota91203b2012-02-15 15:00:46 -0800871 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700872 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800873 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700874 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800875 return false;
876 }
Kenny Root655b9582013-04-04 08:37:42 -0700877
878 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800879 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700880 // We only care about files.
881 if (file->d_type != DT_REG) {
882 continue;
883 }
884
885 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700886 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700887 continue;
888 }
889
890 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800891 }
892 closedir(dir);
893 return true;
894 }
895
Kenny Root655b9582013-04-04 08:37:42 -0700896private:
897 static const int MASTER_KEY_SIZE_BYTES = 16;
898 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
899
900 static const int MAX_RETRY = 4;
901 static const size_t SALT_SIZE = 16;
902
903 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
904 uint8_t* salt) {
905 size_t saltSize;
906 if (salt != NULL) {
907 saltSize = SALT_SIZE;
908 } else {
909 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
910 salt = (uint8_t*) "keystore";
911 // sizeof = 9, not strlen = 8
912 saltSize = sizeof("keystore");
913 }
914
915 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
916 saltSize, 8192, keySize, key);
917 }
918
919 bool generateSalt(Entropy* entropy) {
920 return entropy->generate_random_data(mSalt, sizeof(mSalt));
921 }
922
923 bool generateMasterKey(Entropy* entropy) {
924 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
925 return false;
926 }
927 if (!generateSalt(entropy)) {
928 return false;
929 }
930 return true;
931 }
932
933 void setupMasterKeys() {
934 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
935 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
936 setState(STATE_NO_ERROR);
937 }
938
939 uid_t mUserId;
940
941 char* mUserDir;
942 char* mMasterKeyFile;
943
944 State mState;
945 int8_t mRetry;
946
947 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
948 uint8_t mSalt[SALT_SIZE];
949
950 AES_KEY mMasterKeyEncryption;
951 AES_KEY mMasterKeyDecryption;
952};
953
954typedef struct {
955 uint32_t uid;
956 const uint8_t* filename;
957} grant_t;
958
959class KeyStore {
960public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800961 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700962 : mEntropy(entropy)
963 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800964 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700965 {
966 memset(&mMetaData, '\0', sizeof(mMetaData));
967 }
968
969 ~KeyStore() {
970 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
971 it != mGrants.end(); it++) {
972 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700973 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800974 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700975
976 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
977 it != mMasterKeys.end(); it++) {
978 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700979 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800980 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700981 }
982
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800983 /**
984 * Depending on the hardware keymaster version is this may return a
985 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
986 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
987 * be guarded by a check on the device's version.
988 */
989 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700990 return mDevice;
991 }
992
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800993 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800994 return mFallbackDevice;
995 }
996
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800997 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800998 return blob.isFallback() ? mFallbackDevice: mDevice;
999 }
1000
Kenny Root655b9582013-04-04 08:37:42 -07001001 ResponseCode initialize() {
1002 readMetaData();
1003 if (upgradeKeystore()) {
1004 writeMetaData();
1005 }
1006
1007 return ::NO_ERROR;
1008 }
1009
1010 State getState(uid_t uid) {
1011 return getUserState(uid)->getState();
1012 }
1013
1014 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1015 UserState* userState = getUserState(uid);
1016 return userState->initialize(pw, mEntropy);
1017 }
1018
Robin Lee4e865752014-08-19 17:37:55 +01001019 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1020 UserState *userState = getUserState(uid);
1021 UserState *initState = getUserState(src);
1022 return userState->copyMasterKey(initState);
1023 }
1024
Kenny Root655b9582013-04-04 08:37:42 -07001025 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001026 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001027 return userState->writeMasterKey(pw, mEntropy);
1028 }
1029
1030 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001031 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001032 return userState->readMasterKey(pw, mEntropy);
1033 }
1034
1035 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001036 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001037 encode_key(encoded, keyName);
1038 return android::String8(encoded);
1039 }
1040
1041 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001042 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001043 encode_key(encoded, keyName);
1044 return android::String8::format("%u_%s", uid, encoded);
1045 }
1046
1047 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001048 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001049 encode_key(encoded, keyName);
1050 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1051 encoded);
1052 }
1053
1054 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001055 android::String8 prefix("");
1056 android::Vector<android::String16> aliases;
1057 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1058 return ::SYSTEM_ERROR;
1059 }
1060
Kenny Root655b9582013-04-04 08:37:42 -07001061 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001062 for (uint32_t i = 0; i < aliases.size(); i++) {
1063 android::String8 filename(aliases[i]);
1064 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1065 getKeyName(filename).string());
1066 del(filename, ::TYPE_ANY, uid);
1067 }
1068
Kenny Root655b9582013-04-04 08:37:42 -07001069 userState->zeroizeMasterKeysInMemory();
1070 userState->setState(STATE_UNINITIALIZED);
1071 return userState->reset();
1072 }
1073
1074 bool isEmpty(uid_t uid) const {
1075 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001076 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001077 return true;
1078 }
1079
1080 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001081 if (!dir) {
1082 return true;
1083 }
Kenny Root31e27462014-09-10 11:28:03 -07001084
Kenny Roota91203b2012-02-15 15:00:46 -08001085 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001086 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001087 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001088 // We only care about files.
1089 if (file->d_type != DT_REG) {
1090 continue;
1091 }
1092
1093 // Skip anything that starts with a "."
1094 if (file->d_name[0] == '.') {
1095 continue;
1096 }
1097
Kenny Root31e27462014-09-10 11:28:03 -07001098 result = false;
1099 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001100 }
1101 closedir(dir);
1102 return result;
1103 }
1104
Kenny Root655b9582013-04-04 08:37:42 -07001105 void lock(uid_t uid) {
1106 UserState* userState = getUserState(uid);
1107 userState->zeroizeMasterKeysInMemory();
1108 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001109 }
1110
Kenny Root655b9582013-04-04 08:37:42 -07001111 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1112 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001113 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1114 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001115 if (rc != NO_ERROR) {
1116 return rc;
1117 }
1118
1119 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001120 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001121 /* If we upgrade the key, we need to write it to disk again. Then
1122 * it must be read it again since the blob is encrypted each time
1123 * it's written.
1124 */
Kenny Root655b9582013-04-04 08:37:42 -07001125 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1126 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001127 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1128 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001129 return rc;
1130 }
1131 }
Kenny Root822c3a92012-03-23 16:34:39 -07001132 }
1133
Kenny Root17208e02013-09-04 13:56:03 -07001134 /*
1135 * This will upgrade software-backed keys to hardware-backed keys when
1136 * the HAL for the device supports the newer key types.
1137 */
1138 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1139 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1140 && keyBlob->isFallback()) {
1141 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1142 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1143
1144 // The HAL allowed the import, reget the key to have the "fresh"
1145 // version.
1146 if (imported == NO_ERROR) {
1147 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1148 }
1149 }
1150
Kenny Rootd53bc922013-03-21 14:10:15 -07001151 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001152 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1153 return KEY_NOT_FOUND;
1154 }
1155
1156 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001157 }
1158
Kenny Root655b9582013-04-04 08:37:42 -07001159 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1160 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001161 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1162 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001163 }
1164
Robin Lee4b84fdc2014-09-24 11:56:57 +01001165 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1166 Blob keyBlob;
1167 ResponseCode rc = get(filename, &keyBlob, type, uid);
1168 if (rc != ::NO_ERROR) {
1169 return rc;
1170 }
1171
1172 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1173 // A device doesn't have to implement delete_keypair.
1174 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1175 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1176 rc = ::SYSTEM_ERROR;
1177 }
1178 }
1179 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001180 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1181 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1182 if (dev->delete_key) {
1183 keymaster_key_blob_t blob;
1184 blob.key_material = keyBlob.getValue();
1185 blob.key_material_size = keyBlob.getLength();
1186 dev->delete_key(dev, &blob);
1187 }
1188 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001189 if (rc != ::NO_ERROR) {
1190 return rc;
1191 }
1192
1193 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1194 }
1195
1196 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1197 uid_t uid) {
1198
1199 UserState* userState = getUserState(uid);
1200 size_t n = prefix.length();
1201
1202 DIR* dir = opendir(userState->getUserDirName());
1203 if (!dir) {
1204 ALOGW("can't open directory for user: %s", strerror(errno));
1205 return ::SYSTEM_ERROR;
1206 }
1207
1208 struct dirent* file;
1209 while ((file = readdir(dir)) != NULL) {
1210 // We only care about files.
1211 if (file->d_type != DT_REG) {
1212 continue;
1213 }
1214
1215 // Skip anything that starts with a "."
1216 if (file->d_name[0] == '.') {
1217 continue;
1218 }
1219
1220 if (!strncmp(prefix.string(), file->d_name, n)) {
1221 const char* p = &file->d_name[n];
1222 size_t plen = strlen(p);
1223
1224 size_t extra = decode_key_length(p, plen);
1225 char *match = (char*) malloc(extra + 1);
1226 if (match != NULL) {
1227 decode_key(match, p, plen);
1228 matches->push(android::String16(match, extra));
1229 free(match);
1230 } else {
1231 ALOGW("could not allocate match of size %zd", extra);
1232 }
1233 }
1234 }
1235 closedir(dir);
1236 return ::NO_ERROR;
1237 }
1238
Kenny Root07438c82012-11-02 15:41:02 -07001239 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001240 const grant_t* existing = getGrant(filename, granteeUid);
1241 if (existing == NULL) {
1242 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001243 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001244 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001245 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001246 }
1247 }
1248
Kenny Root07438c82012-11-02 15:41:02 -07001249 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001250 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1251 it != mGrants.end(); it++) {
1252 grant_t* grant = *it;
1253 if (grant->uid == granteeUid
1254 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1255 mGrants.erase(it);
1256 return true;
1257 }
Kenny Root70e3a862012-02-15 17:20:23 -08001258 }
Kenny Root70e3a862012-02-15 17:20:23 -08001259 return false;
1260 }
1261
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001262 bool hasGrant(const char* filename, const uid_t uid) const {
1263 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001264 }
1265
Kenny Rootf9119d62013-04-03 09:22:15 -07001266 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1267 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001268 uint8_t* data;
1269 size_t dataLength;
1270 int rc;
1271
1272 if (mDevice->import_keypair == NULL) {
1273 ALOGE("Keymaster doesn't support import!");
1274 return SYSTEM_ERROR;
1275 }
1276
Kenny Root17208e02013-09-04 13:56:03 -07001277 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001278 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001279 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001280 /*
1281 * Maybe the device doesn't support this type of key. Try to use the
1282 * software fallback keymaster implementation. This is a little bit
1283 * lazier than checking the PKCS#8 key type, but the software
1284 * implementation will do that anyway.
1285 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001286 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001287 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001288
1289 if (rc) {
1290 ALOGE("Error while importing keypair: %d", rc);
1291 return SYSTEM_ERROR;
1292 }
Kenny Root822c3a92012-03-23 16:34:39 -07001293 }
1294
1295 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1296 free(data);
1297
Kenny Rootf9119d62013-04-03 09:22:15 -07001298 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001299 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001300
Kenny Root655b9582013-04-04 08:37:42 -07001301 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001302 }
1303
Kenny Root1b0e3932013-09-05 13:06:32 -07001304 bool isHardwareBacked(const android::String16& keyType) const {
1305 if (mDevice == NULL) {
1306 ALOGW("can't get keymaster device");
1307 return false;
1308 }
1309
1310 if (sRSAKeyType == keyType) {
1311 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1312 } else {
1313 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1314 && (mDevice->common.module->module_api_version
1315 >= KEYMASTER_MODULE_API_VERSION_0_2);
1316 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001317 }
1318
Kenny Root655b9582013-04-04 08:37:42 -07001319 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1320 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001321 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001322
1323 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1324 if (responseCode == NO_ERROR) {
1325 return responseCode;
1326 }
1327
1328 // If this is one of the legacy UID->UID mappings, use it.
1329 uid_t euid = get_keystore_euid(uid);
1330 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001331 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001332 responseCode = get(filepath8.string(), keyBlob, type, uid);
1333 if (responseCode == NO_ERROR) {
1334 return responseCode;
1335 }
1336 }
1337
1338 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001339 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001340 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001341 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001342 if (end[0] != '_' || end[1] == 0) {
1343 return KEY_NOT_FOUND;
1344 }
Kenny Root86b16e82013-09-09 11:15:54 -07001345 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1346 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001347 if (!hasGrant(filepath8.string(), uid)) {
1348 return responseCode;
1349 }
1350
1351 // It is a granted key. Try to load it.
1352 return get(filepath8.string(), keyBlob, type, uid);
1353 }
1354
1355 /**
1356 * Returns any existing UserState or creates it if it doesn't exist.
1357 */
1358 UserState* getUserState(uid_t uid) {
1359 uid_t userId = get_user_id(uid);
1360
1361 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1362 it != mMasterKeys.end(); it++) {
1363 UserState* state = *it;
1364 if (state->getUserId() == userId) {
1365 return state;
1366 }
1367 }
1368
1369 UserState* userState = new UserState(userId);
1370 if (!userState->initialize()) {
1371 /* There's not much we can do if initialization fails. Trying to
1372 * unlock the keystore for that user will fail as well, so any
1373 * subsequent request for this user will just return SYSTEM_ERROR.
1374 */
1375 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1376 }
1377 mMasterKeys.add(userState);
1378 return userState;
1379 }
1380
1381 /**
1382 * Returns NULL if the UserState doesn't already exist.
1383 */
1384 const UserState* getUserState(uid_t uid) const {
1385 uid_t userId = get_user_id(uid);
1386
1387 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1388 it != mMasterKeys.end(); it++) {
1389 UserState* state = *it;
1390 if (state->getUserId() == userId) {
1391 return state;
1392 }
1393 }
1394
1395 return NULL;
1396 }
1397
Kenny Roota91203b2012-02-15 15:00:46 -08001398private:
Kenny Root655b9582013-04-04 08:37:42 -07001399 static const char* sOldMasterKey;
1400 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001401 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001402 Entropy* mEntropy;
1403
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001404 keymaster1_device_t* mDevice;
1405 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001406
Kenny Root655b9582013-04-04 08:37:42 -07001407 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001408
Kenny Root655b9582013-04-04 08:37:42 -07001409 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001410
Kenny Root655b9582013-04-04 08:37:42 -07001411 typedef struct {
1412 uint32_t version;
1413 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001414
Kenny Root655b9582013-04-04 08:37:42 -07001415 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001416
Kenny Root655b9582013-04-04 08:37:42 -07001417 const grant_t* getGrant(const char* filename, uid_t uid) const {
1418 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1419 it != mGrants.end(); it++) {
1420 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001421 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001422 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001423 return grant;
1424 }
1425 }
Kenny Root70e3a862012-02-15 17:20:23 -08001426 return NULL;
1427 }
1428
Kenny Root822c3a92012-03-23 16:34:39 -07001429 /**
1430 * Upgrade code. This will upgrade the key from the current version
1431 * to whatever is newest.
1432 */
Kenny Root655b9582013-04-04 08:37:42 -07001433 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1434 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001435 bool updated = false;
1436 uint8_t version = oldVersion;
1437
1438 /* From V0 -> V1: All old types were unknown */
1439 if (version == 0) {
1440 ALOGV("upgrading to version 1 and setting type %d", type);
1441
1442 blob->setType(type);
1443 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001444 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001445 }
1446 version = 1;
1447 updated = true;
1448 }
1449
Kenny Rootf9119d62013-04-03 09:22:15 -07001450 /* From V1 -> V2: All old keys were encrypted */
1451 if (version == 1) {
1452 ALOGV("upgrading to version 2");
1453
1454 blob->setEncrypted(true);
1455 version = 2;
1456 updated = true;
1457 }
1458
Kenny Root822c3a92012-03-23 16:34:39 -07001459 /*
1460 * If we've updated, set the key blob to the right version
1461 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001462 */
Kenny Root822c3a92012-03-23 16:34:39 -07001463 if (updated) {
1464 ALOGV("updated and writing file %s", filename);
1465 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001466 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001467
1468 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001469 }
1470
1471 /**
1472 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1473 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1474 * Then it overwrites the original blob with the new blob
1475 * format that is returned from the keymaster.
1476 */
Kenny Root655b9582013-04-04 08:37:42 -07001477 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001478 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1479 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1480 if (b.get() == NULL) {
1481 ALOGE("Problem instantiating BIO");
1482 return SYSTEM_ERROR;
1483 }
1484
1485 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1486 if (pkey.get() == NULL) {
1487 ALOGE("Couldn't read old PEM file");
1488 return SYSTEM_ERROR;
1489 }
1490
1491 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1492 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1493 if (len < 0) {
1494 ALOGE("Couldn't measure PKCS#8 length");
1495 return SYSTEM_ERROR;
1496 }
1497
Kenny Root70c98892013-02-07 09:10:36 -08001498 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1499 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001500 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1501 ALOGE("Couldn't convert to PKCS#8");
1502 return SYSTEM_ERROR;
1503 }
1504
Kenny Rootf9119d62013-04-03 09:22:15 -07001505 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1506 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001507 if (rc != NO_ERROR) {
1508 return rc;
1509 }
1510
Kenny Root655b9582013-04-04 08:37:42 -07001511 return get(filename, blob, TYPE_KEY_PAIR, uid);
1512 }
1513
1514 void readMetaData() {
1515 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1516 if (in < 0) {
1517 return;
1518 }
1519 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1520 if (fileLength != sizeof(mMetaData)) {
1521 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1522 sizeof(mMetaData));
1523 }
1524 close(in);
1525 }
1526
1527 void writeMetaData() {
1528 const char* tmpFileName = ".metadata.tmp";
1529 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1530 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1531 if (out < 0) {
1532 ALOGE("couldn't write metadata file: %s", strerror(errno));
1533 return;
1534 }
1535 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1536 if (fileLength != sizeof(mMetaData)) {
1537 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1538 sizeof(mMetaData));
1539 }
1540 close(out);
1541 rename(tmpFileName, sMetaDataFile);
1542 }
1543
1544 bool upgradeKeystore() {
1545 bool upgraded = false;
1546
1547 if (mMetaData.version == 0) {
1548 UserState* userState = getUserState(0);
1549
1550 // Initialize first so the directory is made.
1551 userState->initialize();
1552
1553 // Migrate the old .masterkey file to user 0.
1554 if (access(sOldMasterKey, R_OK) == 0) {
1555 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1556 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1557 return false;
1558 }
1559 }
1560
1561 // Initialize again in case we had a key.
1562 userState->initialize();
1563
1564 // Try to migrate existing keys.
1565 DIR* dir = opendir(".");
1566 if (!dir) {
1567 // Give up now; maybe we can upgrade later.
1568 ALOGE("couldn't open keystore's directory; something is wrong");
1569 return false;
1570 }
1571
1572 struct dirent* file;
1573 while ((file = readdir(dir)) != NULL) {
1574 // We only care about files.
1575 if (file->d_type != DT_REG) {
1576 continue;
1577 }
1578
1579 // Skip anything that starts with a "."
1580 if (file->d_name[0] == '.') {
1581 continue;
1582 }
1583
1584 // Find the current file's user.
1585 char* end;
1586 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1587 if (end[0] != '_' || end[1] == 0) {
1588 continue;
1589 }
1590 UserState* otherUser = getUserState(thisUid);
1591 if (otherUser->getUserId() != 0) {
1592 unlinkat(dirfd(dir), file->d_name, 0);
1593 }
1594
1595 // Rename the file into user directory.
1596 DIR* otherdir = opendir(otherUser->getUserDirName());
1597 if (otherdir == NULL) {
1598 ALOGW("couldn't open user directory for rename");
1599 continue;
1600 }
1601 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1602 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1603 }
1604 closedir(otherdir);
1605 }
1606 closedir(dir);
1607
1608 mMetaData.version = 1;
1609 upgraded = true;
1610 }
1611
1612 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001613 }
Kenny Roota91203b2012-02-15 15:00:46 -08001614};
1615
Kenny Root655b9582013-04-04 08:37:42 -07001616const char* KeyStore::sOldMasterKey = ".masterkey";
1617const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001618
Kenny Root1b0e3932013-09-05 13:06:32 -07001619const android::String16 KeyStore::sRSAKeyType("RSA");
1620
Kenny Root07438c82012-11-02 15:41:02 -07001621namespace android {
1622class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1623public:
1624 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001625 : mKeyStore(keyStore),
1626 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001627 {
Kenny Roota91203b2012-02-15 15:00:46 -08001628 }
Kenny Roota91203b2012-02-15 15:00:46 -08001629
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001630 void binderDied(const wp<IBinder>& who) {
1631 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1632 for (auto token: operations) {
1633 abort(token);
1634 }
Kenny Root822c3a92012-03-23 16:34:39 -07001635 }
Kenny Roota91203b2012-02-15 15:00:46 -08001636
Kenny Root07438c82012-11-02 15:41:02 -07001637 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001638 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001639 pid_t spid = IPCThreadState::self()->getCallingPid();
1640 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001641 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001642 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001643 }
Kenny Roota91203b2012-02-15 15:00:46 -08001644
Kenny Root655b9582013-04-04 08:37:42 -07001645 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001646 }
1647
Kenny Root07438c82012-11-02 15:41:02 -07001648 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001649 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001650 pid_t spid = IPCThreadState::self()->getCallingPid();
1651 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001652 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001653 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001654 }
Kenny Root07438c82012-11-02 15:41:02 -07001655
Kenny Root07438c82012-11-02 15:41:02 -07001656 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001657 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001658
Kenny Root655b9582013-04-04 08:37:42 -07001659 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001660 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001661 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001662 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001663 *item = NULL;
1664 *itemLength = 0;
1665 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001666 }
Kenny Roota91203b2012-02-15 15:00:46 -08001667
Kenny Root07438c82012-11-02 15:41:02 -07001668 *item = (uint8_t*) malloc(keyBlob.getLength());
1669 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1670 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001671
Kenny Root07438c82012-11-02 15:41:02 -07001672 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001673 }
1674
Kenny Rootf9119d62013-04-03 09:22:15 -07001675 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1676 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001677 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001678 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001679 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001680 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001681 return ::PERMISSION_DENIED;
1682 }
Kenny Root07438c82012-11-02 15:41:02 -07001683
Kenny Rootf9119d62013-04-03 09:22:15 -07001684 State state = mKeyStore->getState(callingUid);
1685 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1686 ALOGD("calling get in state: %d", state);
1687 return state;
1688 }
1689
Kenny Root49468902013-03-19 13:41:33 -07001690 if (targetUid == -1) {
1691 targetUid = callingUid;
1692 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001693 return ::PERMISSION_DENIED;
1694 }
1695
Kenny Root07438c82012-11-02 15:41:02 -07001696 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001697 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001698
1699 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001700 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1701
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001702 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001703 }
1704
Kenny Root49468902013-03-19 13:41:33 -07001705 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001706 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001707 pid_t spid = IPCThreadState::self()->getCallingPid();
1708 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001709 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001710 return ::PERMISSION_DENIED;
1711 }
Kenny Root70e3a862012-02-15 17:20:23 -08001712
Kenny Root49468902013-03-19 13:41:33 -07001713 if (targetUid == -1) {
1714 targetUid = callingUid;
1715 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001716 return ::PERMISSION_DENIED;
1717 }
1718
Kenny Root07438c82012-11-02 15:41:02 -07001719 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001720 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001721 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001722 }
1723
Kenny Root49468902013-03-19 13:41:33 -07001724 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001725 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001726 pid_t spid = IPCThreadState::self()->getCallingPid();
1727 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001728 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001729 return ::PERMISSION_DENIED;
1730 }
Kenny Root70e3a862012-02-15 17:20:23 -08001731
Kenny Root49468902013-03-19 13:41:33 -07001732 if (targetUid == -1) {
1733 targetUid = callingUid;
1734 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001735 return ::PERMISSION_DENIED;
1736 }
1737
Kenny Root07438c82012-11-02 15:41:02 -07001738 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001739 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001740
Kenny Root655b9582013-04-04 08:37:42 -07001741 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001742 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1743 }
1744 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001745 }
1746
Kenny Root49468902013-03-19 13:41:33 -07001747 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001748 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001749 pid_t spid = IPCThreadState::self()->getCallingPid();
1750 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001751 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001752 return ::PERMISSION_DENIED;
1753 }
Kenny Root70e3a862012-02-15 17:20:23 -08001754
Kenny Root49468902013-03-19 13:41:33 -07001755 if (targetUid == -1) {
1756 targetUid = callingUid;
1757 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001758 return ::PERMISSION_DENIED;
1759 }
1760
Kenny Root07438c82012-11-02 15:41:02 -07001761 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001762 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001763
Robin Lee4b84fdc2014-09-24 11:56:57 +01001764 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1765 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001766 }
Kenny Root07438c82012-11-02 15:41:02 -07001767 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001768 }
1769
Kenny Root07438c82012-11-02 15:41:02 -07001770 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001771 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001772 pid_t spid = IPCThreadState::self()->getCallingPid();
1773 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001774 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001775 return ::PERMISSION_DENIED;
1776 }
1777
Robin Lee4b84fdc2014-09-24 11:56:57 +01001778 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001779 }
1780
Kenny Root07438c82012-11-02 15:41:02 -07001781 /*
1782 * Here is the history. To improve the security, the parameters to generate the
1783 * master key has been changed. To make a seamless transition, we update the
1784 * file using the same password when the user unlock it for the first time. If
1785 * any thing goes wrong during the transition, the new file will not overwrite
1786 * the old one. This avoids permanent damages of the existing data.
1787 */
1788 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001789 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001790 pid_t spid = IPCThreadState::self()->getCallingPid();
1791 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001792 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001793 return ::PERMISSION_DENIED;
1794 }
Kenny Root70e3a862012-02-15 17:20:23 -08001795
Kenny Root07438c82012-11-02 15:41:02 -07001796 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001797
Kenny Root655b9582013-04-04 08:37:42 -07001798 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001799 case ::STATE_UNINITIALIZED: {
1800 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001801 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001802 }
1803 case ::STATE_NO_ERROR: {
1804 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001805 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001806 }
1807 case ::STATE_LOCKED: {
1808 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001809 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001810 }
1811 }
1812 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001813 }
1814
Kenny Root07438c82012-11-02 15:41:02 -07001815 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001816 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001817 pid_t spid = IPCThreadState::self()->getCallingPid();
1818 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001819 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001820 return ::PERMISSION_DENIED;
1821 }
Kenny Root70e3a862012-02-15 17:20:23 -08001822
Kenny Root655b9582013-04-04 08:37:42 -07001823 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001824 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001825 ALOGD("calling lock in state: %d", state);
1826 return state;
1827 }
1828
Kenny Root655b9582013-04-04 08:37:42 -07001829 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001830 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001831 }
1832
Kenny Root07438c82012-11-02 15:41:02 -07001833 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001834 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001835 pid_t spid = IPCThreadState::self()->getCallingPid();
1836 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001837 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001838 return ::PERMISSION_DENIED;
1839 }
1840
Kenny Root655b9582013-04-04 08:37:42 -07001841 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001842 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001843 ALOGD("calling unlock when not locked");
1844 return state;
1845 }
1846
1847 const String8 password8(pw);
1848 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001849 }
1850
Kenny Root07438c82012-11-02 15:41:02 -07001851 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001852 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001853 pid_t spid = IPCThreadState::self()->getCallingPid();
1854 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001855 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001856 return -1;
1857 }
Kenny Root70e3a862012-02-15 17:20:23 -08001858
Kenny Root655b9582013-04-04 08:37:42 -07001859 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001860 }
1861
Kenny Root96427ba2013-08-16 14:02:41 -07001862 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1863 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001864 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001865 pid_t spid = IPCThreadState::self()->getCallingPid();
1866 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001867 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001868 return ::PERMISSION_DENIED;
1869 }
Kenny Root70e3a862012-02-15 17:20:23 -08001870
Kenny Root49468902013-03-19 13:41:33 -07001871 if (targetUid == -1) {
1872 targetUid = callingUid;
1873 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001874 return ::PERMISSION_DENIED;
1875 }
1876
Kenny Root655b9582013-04-04 08:37:42 -07001877 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001878 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1879 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001880 return state;
1881 }
Kenny Root70e3a862012-02-15 17:20:23 -08001882
Kenny Root07438c82012-11-02 15:41:02 -07001883 uint8_t* data;
1884 size_t dataLength;
1885 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001886 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001887
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001888 const keymaster1_device_t* device = mKeyStore->getDevice();
1889 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001890 if (device == NULL) {
1891 return ::SYSTEM_ERROR;
1892 }
1893
1894 if (device->generate_keypair == NULL) {
1895 return ::SYSTEM_ERROR;
1896 }
1897
Kenny Root17208e02013-09-04 13:56:03 -07001898 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001899 keymaster_dsa_keygen_params_t dsa_params;
1900 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001901
Kenny Root96427ba2013-08-16 14:02:41 -07001902 if (keySize == -1) {
1903 keySize = DSA_DEFAULT_KEY_SIZE;
1904 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1905 || keySize > DSA_MAX_KEY_SIZE) {
1906 ALOGI("invalid key size %d", keySize);
1907 return ::SYSTEM_ERROR;
1908 }
1909 dsa_params.key_size = keySize;
1910
1911 if (args->size() == 3) {
1912 sp<KeystoreArg> gArg = args->itemAt(0);
1913 sp<KeystoreArg> pArg = args->itemAt(1);
1914 sp<KeystoreArg> qArg = args->itemAt(2);
1915
1916 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1917 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1918 dsa_params.generator_len = gArg->size();
1919
1920 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1921 dsa_params.prime_p_len = pArg->size();
1922
1923 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1924 dsa_params.prime_q_len = qArg->size();
1925 } else {
1926 ALOGI("not all DSA parameters were read");
1927 return ::SYSTEM_ERROR;
1928 }
1929 } else if (args->size() != 0) {
1930 ALOGI("DSA args must be 3");
1931 return ::SYSTEM_ERROR;
1932 }
1933
Kenny Root1d448c02013-11-21 10:36:53 -08001934 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001935 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1936 } else {
1937 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001938 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1939 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001940 }
1941 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001942 keymaster_ec_keygen_params_t ec_params;
1943 memset(&ec_params, '\0', sizeof(ec_params));
1944
1945 if (keySize == -1) {
1946 keySize = EC_DEFAULT_KEY_SIZE;
1947 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1948 ALOGI("invalid key size %d", keySize);
1949 return ::SYSTEM_ERROR;
1950 }
1951 ec_params.field_size = keySize;
1952
Kenny Root1d448c02013-11-21 10:36:53 -08001953 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001954 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1955 } else {
1956 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001957 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001958 }
Kenny Root96427ba2013-08-16 14:02:41 -07001959 } else if (keyType == EVP_PKEY_RSA) {
1960 keymaster_rsa_keygen_params_t rsa_params;
1961 memset(&rsa_params, '\0', sizeof(rsa_params));
1962 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1963
1964 if (keySize == -1) {
1965 keySize = RSA_DEFAULT_KEY_SIZE;
1966 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1967 ALOGI("invalid key size %d", keySize);
1968 return ::SYSTEM_ERROR;
1969 }
1970 rsa_params.modulus_size = keySize;
1971
1972 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001973 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001974 return ::SYSTEM_ERROR;
1975 } else if (args->size() == 1) {
1976 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1977 if (pubExpBlob != NULL) {
1978 Unique_BIGNUM pubExpBn(
1979 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1980 pubExpBlob->size(), NULL));
1981 if (pubExpBn.get() == NULL) {
1982 ALOGI("Could not convert public exponent to BN");
1983 return ::SYSTEM_ERROR;
1984 }
1985 unsigned long pubExp = BN_get_word(pubExpBn.get());
1986 if (pubExp == 0xFFFFFFFFL) {
1987 ALOGI("cannot represent public exponent as a long value");
1988 return ::SYSTEM_ERROR;
1989 }
1990 rsa_params.public_exponent = pubExp;
1991 }
1992 }
1993
1994 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1995 } else {
1996 ALOGW("Unsupported key type %d", keyType);
1997 rc = -1;
1998 }
1999
Kenny Root07438c82012-11-02 15:41:02 -07002000 if (rc) {
2001 return ::SYSTEM_ERROR;
2002 }
2003
Kenny Root655b9582013-04-04 08:37:42 -07002004 String8 name8(name);
2005 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002006
2007 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2008 free(data);
2009
Kenny Rootee8068b2013-10-07 09:49:15 -07002010 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002011 keyBlob.setFallback(isFallback);
2012
Kenny Root655b9582013-04-04 08:37:42 -07002013 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08002014 }
2015
Kenny Rootf9119d62013-04-03 09:22:15 -07002016 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2017 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002018 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002019 pid_t spid = IPCThreadState::self()->getCallingPid();
2020 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002021 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002022 return ::PERMISSION_DENIED;
2023 }
Kenny Root07438c82012-11-02 15:41:02 -07002024
Kenny Root49468902013-03-19 13:41:33 -07002025 if (targetUid == -1) {
2026 targetUid = callingUid;
2027 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002028 return ::PERMISSION_DENIED;
2029 }
2030
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002031 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002032 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002033 ALOGD("calling import in state: %d", state);
2034 return state;
2035 }
2036
2037 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002038 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002039
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002040 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002041 }
2042
Kenny Root07438c82012-11-02 15:41:02 -07002043 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2044 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002045 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002046 pid_t spid = IPCThreadState::self()->getCallingPid();
2047 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002048 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002049 return ::PERMISSION_DENIED;
2050 }
Kenny Root07438c82012-11-02 15:41:02 -07002051
Kenny Root07438c82012-11-02 15:41:02 -07002052 Blob keyBlob;
2053 String8 name8(name);
2054
Kenny Rootd38a0b02013-02-13 12:59:14 -08002055 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002056 int rc;
2057
Kenny Root655b9582013-04-04 08:37:42 -07002058 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002059 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002060 if (responseCode != ::NO_ERROR) {
2061 return responseCode;
2062 }
2063
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002064 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002065 if (device == NULL) {
2066 ALOGE("no keymaster device; cannot sign");
2067 return ::SYSTEM_ERROR;
2068 }
2069
2070 if (device->sign_data == NULL) {
2071 ALOGE("device doesn't implement signing");
2072 return ::SYSTEM_ERROR;
2073 }
2074
2075 keymaster_rsa_sign_params_t params;
2076 params.digest_type = DIGEST_NONE;
2077 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002078 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2079 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002080 if (rc) {
2081 ALOGW("device couldn't sign data");
2082 return ::SYSTEM_ERROR;
2083 }
2084
2085 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002086 }
2087
Kenny Root07438c82012-11-02 15:41:02 -07002088 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2089 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002090 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002091 pid_t spid = IPCThreadState::self()->getCallingPid();
2092 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002093 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002094 return ::PERMISSION_DENIED;
2095 }
Kenny Root70e3a862012-02-15 17:20:23 -08002096
Kenny Root655b9582013-04-04 08:37:42 -07002097 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002098 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002099 ALOGD("calling verify in state: %d", state);
2100 return state;
2101 }
Kenny Root70e3a862012-02-15 17:20:23 -08002102
Kenny Root07438c82012-11-02 15:41:02 -07002103 Blob keyBlob;
2104 String8 name8(name);
2105 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002106
Kenny Root655b9582013-04-04 08:37:42 -07002107 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002108 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002109 if (responseCode != ::NO_ERROR) {
2110 return responseCode;
2111 }
Kenny Root70e3a862012-02-15 17:20:23 -08002112
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002113 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002114 if (device == NULL) {
2115 return ::SYSTEM_ERROR;
2116 }
Kenny Root70e3a862012-02-15 17:20:23 -08002117
Kenny Root07438c82012-11-02 15:41:02 -07002118 if (device->verify_data == NULL) {
2119 return ::SYSTEM_ERROR;
2120 }
Kenny Root70e3a862012-02-15 17:20:23 -08002121
Kenny Root07438c82012-11-02 15:41:02 -07002122 keymaster_rsa_sign_params_t params;
2123 params.digest_type = DIGEST_NONE;
2124 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002125
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002126 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2127 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002128 if (rc) {
2129 return ::SYSTEM_ERROR;
2130 } else {
2131 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002132 }
2133 }
Kenny Root07438c82012-11-02 15:41:02 -07002134
2135 /*
2136 * TODO: The abstraction between things stored in hardware and regular blobs
2137 * of data stored on the filesystem should be moved down to keystore itself.
2138 * Unfortunately the Java code that calls this has naming conventions that it
2139 * knows about. Ideally keystore shouldn't be used to store random blobs of
2140 * data.
2141 *
2142 * Until that happens, it's necessary to have a separate "get_pubkey" and
2143 * "del_key" since the Java code doesn't really communicate what it's
2144 * intentions are.
2145 */
2146 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002147 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002148 pid_t spid = IPCThreadState::self()->getCallingPid();
2149 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002150 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002151 return ::PERMISSION_DENIED;
2152 }
Kenny Root07438c82012-11-02 15:41:02 -07002153
Kenny Root07438c82012-11-02 15:41:02 -07002154 Blob keyBlob;
2155 String8 name8(name);
2156
Kenny Rootd38a0b02013-02-13 12:59:14 -08002157 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002158
Kenny Root655b9582013-04-04 08:37:42 -07002159 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002160 TYPE_KEY_PAIR);
2161 if (responseCode != ::NO_ERROR) {
2162 return responseCode;
2163 }
2164
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002165 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002166 if (device == NULL) {
2167 return ::SYSTEM_ERROR;
2168 }
2169
2170 if (device->get_keypair_public == NULL) {
2171 ALOGE("device has no get_keypair_public implementation!");
2172 return ::SYSTEM_ERROR;
2173 }
2174
Kenny Root17208e02013-09-04 13:56:03 -07002175 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002176 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2177 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002178 if (rc) {
2179 return ::SYSTEM_ERROR;
2180 }
2181
2182 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002183 }
Kenny Root07438c82012-11-02 15:41:02 -07002184
Kenny Root49468902013-03-19 13:41:33 -07002185 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002186 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002187 pid_t spid = IPCThreadState::self()->getCallingPid();
2188 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002189 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002190 return ::PERMISSION_DENIED;
2191 }
Kenny Root07438c82012-11-02 15:41:02 -07002192
Kenny Root49468902013-03-19 13:41:33 -07002193 if (targetUid == -1) {
2194 targetUid = callingUid;
2195 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002196 return ::PERMISSION_DENIED;
2197 }
2198
Kenny Root07438c82012-11-02 15:41:02 -07002199 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002200 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002201 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002202 }
2203
2204 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002205 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002206 pid_t spid = IPCThreadState::self()->getCallingPid();
2207 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002208 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002209 return ::PERMISSION_DENIED;
2210 }
Kenny Root07438c82012-11-02 15:41:02 -07002211
Kenny Root655b9582013-04-04 08:37:42 -07002212 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002213 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002214 ALOGD("calling grant in state: %d", state);
2215 return state;
2216 }
2217
2218 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002219 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002220
Kenny Root655b9582013-04-04 08:37:42 -07002221 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002222 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2223 }
2224
Kenny Root655b9582013-04-04 08:37:42 -07002225 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002226 return ::NO_ERROR;
2227 }
2228
2229 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002230 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002231 pid_t spid = IPCThreadState::self()->getCallingPid();
2232 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002233 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002234 return ::PERMISSION_DENIED;
2235 }
Kenny Root07438c82012-11-02 15:41:02 -07002236
Kenny Root655b9582013-04-04 08:37:42 -07002237 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002238 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002239 ALOGD("calling ungrant in state: %d", state);
2240 return state;
2241 }
2242
2243 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002244 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002245
Kenny Root655b9582013-04-04 08:37:42 -07002246 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002247 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2248 }
2249
Kenny Root655b9582013-04-04 08:37:42 -07002250 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002251 }
2252
2253 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002254 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002255 pid_t spid = IPCThreadState::self()->getCallingPid();
2256 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002257 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002258 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002259 }
Kenny Root07438c82012-11-02 15:41:02 -07002260
2261 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002262 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002263
Kenny Root655b9582013-04-04 08:37:42 -07002264 if (access(filename.string(), R_OK) == -1) {
2265 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002266 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002267 }
2268
Kenny Root655b9582013-04-04 08:37:42 -07002269 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002270 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002271 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002272 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002273 }
2274
2275 struct stat s;
2276 int ret = fstat(fd, &s);
2277 close(fd);
2278 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002279 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002280 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002281 }
2282
Kenny Root36a9e232013-02-04 14:24:15 -08002283 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002284 }
2285
Kenny Rootd53bc922013-03-21 14:10:15 -07002286 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2287 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002288 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002289 pid_t spid = IPCThreadState::self()->getCallingPid();
2290 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002291 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002292 return -1L;
2293 }
2294
Kenny Root655b9582013-04-04 08:37:42 -07002295 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002296 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002297 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002298 return state;
2299 }
2300
Kenny Rootd53bc922013-03-21 14:10:15 -07002301 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2302 srcUid = callingUid;
2303 } else if (!is_granted_to(callingUid, srcUid)) {
2304 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002305 return ::PERMISSION_DENIED;
2306 }
2307
Kenny Rootd53bc922013-03-21 14:10:15 -07002308 if (destUid == -1) {
2309 destUid = callingUid;
2310 }
2311
2312 if (srcUid != destUid) {
2313 if (static_cast<uid_t>(srcUid) != callingUid) {
2314 ALOGD("can only duplicate from caller to other or to same uid: "
2315 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2316 return ::PERMISSION_DENIED;
2317 }
2318
2319 if (!is_granted_to(callingUid, destUid)) {
2320 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2321 return ::PERMISSION_DENIED;
2322 }
2323 }
2324
2325 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002326 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002327
Kenny Rootd53bc922013-03-21 14:10:15 -07002328 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002329 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002330
Kenny Root655b9582013-04-04 08:37:42 -07002331 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2332 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002333 return ::SYSTEM_ERROR;
2334 }
2335
Kenny Rootd53bc922013-03-21 14:10:15 -07002336 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002337 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002338 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002339 if (responseCode != ::NO_ERROR) {
2340 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002341 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002342
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002343 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002344 }
2345
Kenny Root1b0e3932013-09-05 13:06:32 -07002346 int32_t is_hardware_backed(const String16& keyType) {
2347 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002348 }
2349
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002350 int32_t clear_uid(int64_t targetUid64) {
2351 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002352 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002353 pid_t spid = IPCThreadState::self()->getCallingPid();
2354 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002355 ALOGW("permission denied for %d: clear_uid", callingUid);
2356 return ::PERMISSION_DENIED;
2357 }
2358
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002359 if (targetUid64 == -1) {
2360 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002361 } else if (!is_self_or_system(callingUid, targetUid)) {
2362 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002363 return ::PERMISSION_DENIED;
2364 }
2365
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002366 const keymaster1_device_t* device = mKeyStore->getDevice();
Kenny Roota9bb5492013-04-01 16:29:11 -07002367 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002368 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002369 return ::SYSTEM_ERROR;
2370 }
2371
Robin Lee4b84fdc2014-09-24 11:56:57 +01002372 String8 prefix = String8::format("%u_", targetUid);
2373 Vector<String16> aliases;
2374 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002375 return ::SYSTEM_ERROR;
2376 }
2377
Robin Lee4b84fdc2014-09-24 11:56:57 +01002378 for (uint32_t i = 0; i < aliases.size(); i++) {
2379 String8 name8(aliases[i]);
2380 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2381 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002382 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002383 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002384 }
2385
Robin Lee4b84fdc2014-09-24 11:56:57 +01002386 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002387 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2388 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002389
Robin Lee4e865752014-08-19 17:37:55 +01002390 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002391 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002392 return ::PERMISSION_DENIED;
2393 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002394 if (!is_self_or_system(callingUid, targetUid)) {
2395 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002396 return ::PERMISSION_DENIED;
2397 }
2398
Robin Lee4b84fdc2014-09-24 11:56:57 +01002399 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002400 }
2401
2402 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2403 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2404 pid_t spid = IPCThreadState::self()->getCallingPid();
2405 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2406 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2407 return ::PERMISSION_DENIED;
2408 }
2409 if (callingUid != AID_SYSTEM) {
2410 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2411 return ::PERMISSION_DENIED;
2412 }
2413 if (sourceUid == targetUid) {
2414 return ::SYSTEM_ERROR;
2415 }
2416
2417 // Initialise user keystore with existing master key held in-memory
2418 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2419 }
2420
2421 int32_t password_uid(const String16& pw, int32_t targetUid) {
2422 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2423 pid_t spid = IPCThreadState::self()->getCallingPid();
2424 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2425 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2426 return ::PERMISSION_DENIED;
2427 }
2428 if (callingUid != AID_SYSTEM) {
2429 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2430 return ::PERMISSION_DENIED;
2431 }
2432
2433 const String8 password8(pw);
2434
2435 switch (mKeyStore->getState(targetUid)) {
2436 case ::STATE_UNINITIALIZED: {
2437 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2438 return mKeyStore->initializeUser(password8, targetUid);
2439 }
2440 case ::STATE_NO_ERROR: {
2441 // rewrite master key with new password.
2442 return mKeyStore->writeMasterKey(password8, targetUid);
2443 }
2444 case ::STATE_LOCKED: {
2445 // read master key, decrypt with password, initialize mMasterKey*.
2446 return mKeyStore->readMasterKey(password8, targetUid);
2447 }
2448 }
2449 return ::SYSTEM_ERROR;
2450 }
2451
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002452 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2453 const keymaster1_device_t* device = mKeyStore->getDevice();
2454 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2455 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2456 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2457 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2458 device->add_rng_entropy != NULL) {
2459 devResult = device->add_rng_entropy(device, data, dataLength);
2460 }
2461 if (fallback->add_rng_entropy) {
2462 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2463 }
2464 if (devResult) {
2465 return devResult;
2466 }
2467 if (fallbackResult) {
2468 return fallbackResult;
2469 }
2470 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002471 }
2472
Chad Brubaker17d68b92015-02-05 22:04:16 -08002473 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002474 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2475 KeyCharacteristics* outCharacteristics) {
Chad Brubaker17d68b92015-02-05 22:04:16 -08002476 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2477 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2478 if (!has_permission(callingUid, P_INSERT, callingPid)) {
2479 ALOGW("permission denied for %d: generateKey", callingUid);
2480 return ::PERMISSION_DENIED;
2481 }
2482
2483 State state = mKeyStore->getState(callingUid);
2484 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2485 ALOGW("calling generate in state: %d", state);
2486 return state;
2487 }
2488
2489 if (uid == -1) {
2490 uid = callingUid;
2491 } else if (!is_granted_to(callingUid, uid)) {
2492 return ::PERMISSION_DENIED;
2493 }
2494
Chad Brubaker17d68b92015-02-05 22:04:16 -08002495 int rc = KM_ERROR_UNIMPLEMENTED;
2496 bool isFallback = false;
2497 keymaster_key_blob_t blob;
2498 keymaster_key_characteristics_t *out = NULL;
2499
2500 const keymaster1_device_t* device = mKeyStore->getDevice();
2501 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2502 if (device == NULL) {
2503 return ::SYSTEM_ERROR;
2504 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002505 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002506 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2507 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002508 if (!entropy) {
2509 rc = KM_ERROR_OK;
2510 } else if (device->add_rng_entropy) {
2511 rc = device->add_rng_entropy(device, entropy, entropyLength);
2512 } else {
2513 rc = KM_ERROR_UNIMPLEMENTED;
2514 }
2515 if (rc == KM_ERROR_OK) {
2516 rc = device->generate_key(device, params.params.data(), params.params.size(),
2517 &blob, &out);
2518 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002519 }
2520 // If the HW device didn't support generate_key or generate_key failed
2521 // fall back to the software implementation.
2522 if (rc && fallback->generate_key != NULL) {
2523 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002524 if (!entropy) {
2525 rc = KM_ERROR_OK;
2526 } else if (fallback->add_rng_entropy) {
2527 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2528 } else {
2529 rc = KM_ERROR_UNIMPLEMENTED;
2530 }
2531 if (rc == KM_ERROR_OK) {
2532 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2533 &blob,
2534 &out);
2535 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002536 }
2537
2538 if (out) {
2539 if (outCharacteristics) {
2540 outCharacteristics->characteristics = *out;
2541 } else {
2542 keymaster_free_characteristics(out);
2543 }
2544 free(out);
2545 }
2546
2547 if (rc) {
2548 return rc;
2549 }
2550
2551 String8 name8(name);
2552 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2553
2554 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2555 keyBlob.setFallback(isFallback);
2556 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2557
2558 free(const_cast<uint8_t*>(blob.key_material));
2559
2560 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002561 }
2562
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002563 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002564 const keymaster_blob_t* clientId,
2565 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002566 KeyCharacteristics* outCharacteristics) {
2567
2568 if (!outCharacteristics) {
2569 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2570 }
2571
2572 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2573
2574 Blob keyBlob;
2575 String8 name8(name);
2576 int rc;
2577
2578 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2579 TYPE_KEYMASTER_10);
2580 if (responseCode != ::NO_ERROR) {
2581 return responseCode;
2582 }
2583 keymaster_key_blob_t key;
2584 key.key_material_size = keyBlob.getLength();
2585 key.key_material = keyBlob.getValue();
2586 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2587 keymaster_key_characteristics_t *out = NULL;
2588 if (!dev->get_key_characteristics) {
2589 ALOGW("device does not implement get_key_characteristics");
2590 return KM_ERROR_UNIMPLEMENTED;
2591 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002592 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002593 if (out) {
2594 outCharacteristics->characteristics = *out;
2595 free(out);
2596 }
2597 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002598 }
2599
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002600 int32_t importKey(const String16& name, const KeymasterArguments& params,
2601 keymaster_key_format_t format, const uint8_t *keyData,
2602 size_t keyLength, int uid, int flags,
2603 KeyCharacteristics* outCharacteristics) {
2604 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2605 pid_t spid = IPCThreadState::self()->getCallingPid();
2606 if (!has_permission(callingUid, P_INSERT, spid)) {
2607 ALOGW("permission denied for %d: importKey", callingUid);
2608 return ::PERMISSION_DENIED;
2609 }
2610
2611 State state = mKeyStore->getState(callingUid);
2612 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2613 ALOGW("calling importKey in state: %d", state);
2614 return state;
2615 }
2616
2617 if (uid == -1) {
2618 uid = callingUid;
2619 } else if (!is_granted_to(callingUid, uid)) {
2620 ALOGW("not granted to %d %d", callingUid, uid);
2621 return ::PERMISSION_DENIED;
2622 }
2623
2624 int rc = KM_ERROR_UNIMPLEMENTED;
2625 bool isFallback = false;
2626 keymaster_key_blob_t blob;
2627 keymaster_key_characteristics_t *out = NULL;
2628
2629 const keymaster1_device_t* device = mKeyStore->getDevice();
2630 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2631 if (device == NULL) {
2632 return ::SYSTEM_ERROR;
2633 }
2634 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2635 device->import_key != NULL) {
2636 rc = device->import_key(device, params.params.data(), params.params.size(),
2637 format, keyData, keyLength, &blob, &out);
2638 }
2639 if (rc && fallback->import_key != NULL) {
2640 isFallback = true;
2641 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2642 format, keyData, keyLength, &blob, &out);
2643 }
2644 if (out) {
2645 if (outCharacteristics) {
2646 outCharacteristics->characteristics = *out;
2647 } else {
2648 keymaster_free_characteristics(out);
2649 }
2650 free(out);
2651 }
2652 if (rc) {
2653 return rc;
2654 }
2655
2656 String8 name8(name);
2657 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2658
2659 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2660 keyBlob.setFallback(isFallback);
2661 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2662
2663 free((void*) blob.key_material);
2664
2665 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002666 }
2667
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002668 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002669 const keymaster_blob_t* clientId,
2670 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002671
2672 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2673
2674 Blob keyBlob;
2675 String8 name8(name);
2676 int rc;
2677
2678 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2679 TYPE_KEYMASTER_10);
2680 if (responseCode != ::NO_ERROR) {
2681 result->resultCode = responseCode;
2682 return;
2683 }
2684 keymaster_key_blob_t key;
2685 key.key_material_size = keyBlob.getLength();
2686 key.key_material = keyBlob.getValue();
2687 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2688 if (!dev->export_key) {
2689 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2690 return;
2691 }
2692 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002693 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002694 &ptr, &result->dataLength);
2695 result->exportData.reset(ptr);
2696 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002697 }
2698
Chad Brubaker06801e02015-03-31 15:13:13 -07002699 /**
2700 * Check that all keymaster_key_param_t's provided by the application are
2701 * allowed. Any parameter that keystore adds itself should be disallowed here.
2702 */
2703 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2704 for (auto param: params) {
2705 switch (param.tag) {
2706 case KM_TAG_AUTH_TOKEN:
2707 return false;
2708 default:
2709 break;
2710 }
2711 }
2712 return true;
2713 }
2714
Chad Brubakerad6514a2015-04-09 14:00:26 -07002715 int authorizeOperation(const keymaster_key_characteristics_t& characteristics,
Chad Brubaker06801e02015-03-31 15:13:13 -07002716 keymaster_operation_handle_t handle,
2717 std::vector<keymaster_key_param_t>* params,
2718 bool failOnTokenMissing=true) {
2719 if (!checkAllowedOperationParams(*params)) {
2720 return KM_ERROR_INVALID_ARGUMENT;
2721 }
Chad Brubakerad6514a2015-04-09 14:00:26 -07002722 std::vector<keymaster_key_param_t> allCharacteristics;
2723 for (size_t i = 0; i < characteristics.sw_enforced.length; i++) {
2724 allCharacteristics.push_back(characteristics.sw_enforced.params[i]);
2725 }
2726 for (size_t i = 0; i < characteristics.hw_enforced.length; i++) {
2727 allCharacteristics.push_back(characteristics.hw_enforced.params[i]);
2728 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002729 // Check for auth token and add it to the param list if present.
2730 const hw_auth_token_t* authToken;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002731 switch (mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2732 allCharacteristics.size(), handle, &authToken)) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002733 case keymaster::AuthTokenTable::OK:
2734 // Auth token found.
2735 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2736 reinterpret_cast<const uint8_t*>(authToken),
2737 sizeof(hw_auth_token_t)));
2738 break;
2739 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2740 return KM_ERROR_OK;
2741 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2742 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2743 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2744 if (failOnTokenMissing) {
2745 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2746 }
2747 break;
2748 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2749 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2750 default:
2751 return KM_ERROR_INVALID_ARGUMENT;
2752 }
2753 // TODO: Enforce the rest of authorization
2754 return KM_ERROR_OK;
2755 }
2756
Chad Brubakerad6514a2015-04-09 14:00:26 -07002757 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2758 const keymaster1_device_t* dev,
2759 const std::vector<keymaster_key_param_t>& params,
2760 keymaster_key_characteristics_t* out) {
2761 UniquePtr<keymaster_blob_t> appId;
2762 UniquePtr<keymaster_blob_t> appData;
2763 for (auto param : params) {
2764 if (param.tag == KM_TAG_APPLICATION_ID) {
2765 appId.reset(new keymaster_blob_t);
2766 appId->data = param.blob.data;
2767 appId->data_length = param.blob.data_length;
2768 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2769 appData.reset(new keymaster_blob_t);
2770 appData->data = param.blob.data;
2771 appData->data_length = param.blob.data_length;
2772 }
2773 }
2774 keymaster_key_characteristics_t* result = NULL;
2775 if (!dev->get_key_characteristics) {
2776 return KM_ERROR_UNIMPLEMENTED;
2777 }
2778 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2779 appData.get(), &result);
2780 if (result) {
2781 *out = *result;
2782 free(result);
2783 }
2784 return error;
2785 }
2786
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002787 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002788 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2789 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002790 if (!result || !outParams) {
2791 ALOGE("Unexpected null arguments to begin()");
2792 return;
2793 }
2794 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2795 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2796 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2797 result->resultCode = ::PERMISSION_DENIED;
2798 return;
2799 }
2800 Blob keyBlob;
2801 String8 name8(name);
2802 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2803 TYPE_KEYMASTER_10);
2804 if (responseCode != ::NO_ERROR) {
2805 result->resultCode = responseCode;
2806 return;
2807 }
2808 keymaster_key_blob_t key;
2809 key.key_material_size = keyBlob.getLength();
2810 key.key_material = keyBlob.getValue();
2811 keymaster_key_param_t* out;
2812 size_t outSize;
2813 keymaster_operation_handle_t handle;
2814 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002815 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002816 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002817 Unique_keymaster_key_characteristics characteristics;
2818 characteristics.reset(new keymaster_key_characteristics_t);
2819 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2820 if (err) {
2821 result->resultCode = err;
2822 return;
2823 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002824 // Don't require an auth token for the call to begin, authentication can
2825 // require an operation handle. Update and finish will require the token
2826 // be present and valid.
Chad Brubakerad6514a2015-04-09 14:00:26 -07002827 int32_t authResult = authorizeOperation(*characteristics, 0, &opParams,
Chad Brubaker06801e02015-03-31 15:13:13 -07002828 /*failOnTokenMissing*/ false);
2829 if (authResult) {
2830 result->resultCode = err;
2831 return;
2832 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002833 // Add entropy to the device first.
2834 if (entropy) {
2835 if (dev->add_rng_entropy) {
2836 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2837 } else {
2838 err = KM_ERROR_UNIMPLEMENTED;
2839 }
2840 if (err) {
2841 result->resultCode = err;
2842 return;
2843 }
2844 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002845 // Don't do an auth check here, we need begin to succeed for
2846 // per-operation auth. update/finish will be doing the auth checks.
2847 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2848 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002849
2850 // If there are too many operations abort the oldest operation that was
2851 // started as pruneable and try again.
2852 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2853 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2854 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2855 if (abort(oldest) != ::NO_ERROR) {
2856 break;
2857 }
2858 err = dev->begin(dev, purpose, &key, params.params.data(),
2859 params.params.size(), &out, &outSize,
2860 &handle);
2861 }
2862 if (err) {
2863 result->resultCode = err;
2864 return;
2865 }
2866 if (out) {
2867 outParams->params.assign(out, out + outSize);
2868 free(out);
2869 }
2870
Chad Brubakerad6514a2015-04-09 14:00:26 -07002871 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2872 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002873 pruneable);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002874 result->resultCode = ::NO_ERROR;
2875 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002876 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002877 }
2878
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002879 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2880 size_t dataLength, OperationResult* result) {
2881 const keymaster1_device_t* dev;
2882 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002883 const keymaster_key_characteristics_t* characteristics;
2884 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002885 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2886 return;
2887 }
2888 uint8_t* output_buf = NULL;
2889 size_t output_length = 0;
2890 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002891 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002892 int32_t authResult = authorizeOperation(*characteristics, handle, &opParams);
Chad Brubaker06801e02015-03-31 15:13:13 -07002893 if (authResult) {
2894 result->resultCode = authResult;
2895 return;
2896 }
2897 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2898 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002899 result->data.reset(output_buf);
2900 result->dataLength = output_length;
2901 result->inputConsumed = consumed;
2902 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002903 }
2904
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002905 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2906 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
2907 const keymaster1_device_t* dev;
2908 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002909 const keymaster_key_characteristics_t* characteristics;
2910 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002911 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2912 return;
2913 }
2914 uint8_t* output_buf = NULL;
2915 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002916 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002917 int32_t authResult = authorizeOperation(*characteristics, handle, &opParams);
Chad Brubaker06801e02015-03-31 15:13:13 -07002918 if (authResult) {
2919 result->resultCode = authResult;
2920 return;
2921 }
2922 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2923 signature, signatureLength, &output_buf,
2924 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002925 // Remove the operation regardless of the result
2926 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002927 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002928 result->data.reset(output_buf);
2929 result->dataLength = output_length;
2930 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002931 }
2932
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002933 int32_t abort(const sp<IBinder>& token) {
2934 const keymaster1_device_t* dev;
2935 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002936 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002937 return KM_ERROR_INVALID_OPERATION_HANDLE;
2938 }
2939 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002940 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002941 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002942 rc = KM_ERROR_UNIMPLEMENTED;
2943 } else {
2944 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002945 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002946 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002947 if (rc) {
2948 return rc;
2949 }
2950 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002951 }
2952
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002953 bool isOperationAuthorized(const sp<IBinder>& token) {
2954 const keymaster1_device_t* dev;
2955 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002956 const keymaster_key_characteristics_t* characteristics;
2957 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002958 return false;
2959 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002960 std::vector<keymaster_key_param_t> ignored;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002961 int32_t authResult = authorizeOperation(*characteristics, handle, &ignored);
Chad Brubaker06801e02015-03-31 15:13:13 -07002962 return authResult == KM_ERROR_OK;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002963 }
2964
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002965 int32_t addAuthToken(const uint8_t* token, size_t length) {
2966 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2967 pid_t spid = IPCThreadState::self()->getCallingPid();
2968 if (!has_permission(callingUid, P_ADD_AUTH, spid)) {
2969 ALOGW("permission denied for %d: addAuthToken", callingUid);
2970 return ::PERMISSION_DENIED;
2971 }
2972 if (length != sizeof(hw_auth_token_t)) {
2973 return KM_ERROR_INVALID_ARGUMENT;
2974 }
2975 hw_auth_token_t* authToken = new hw_auth_token_t;
2976 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2977 // The table takes ownership of authToken.
2978 mAuthTokenTable.AddAuthenticationToken(authToken);
2979 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002980 }
2981
Kenny Root07438c82012-11-02 15:41:02 -07002982private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002983 inline bool isKeystoreUnlocked(State state) {
2984 switch (state) {
2985 case ::STATE_NO_ERROR:
2986 return true;
2987 case ::STATE_UNINITIALIZED:
2988 case ::STATE_LOCKED:
2989 return false;
2990 }
2991 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002992 }
2993
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002994 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002995 const int32_t device_api = device->common.module->module_api_version;
2996 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2997 switch (keyType) {
2998 case TYPE_RSA:
2999 case TYPE_DSA:
3000 case TYPE_EC:
3001 return true;
3002 default:
3003 return false;
3004 }
3005 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
3006 switch (keyType) {
3007 case TYPE_RSA:
3008 return true;
3009 case TYPE_DSA:
3010 return device->flags & KEYMASTER_SUPPORTS_DSA;
3011 case TYPE_EC:
3012 return device->flags & KEYMASTER_SUPPORTS_EC;
3013 default:
3014 return false;
3015 }
3016 } else {
3017 return keyType == TYPE_RSA;
3018 }
3019 }
3020
Kenny Root07438c82012-11-02 15:41:02 -07003021 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003022 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003023 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003024};
3025
3026}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003027
3028int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003029 if (argc < 2) {
3030 ALOGE("A directory must be specified!");
3031 return 1;
3032 }
3033 if (chdir(argv[1]) == -1) {
3034 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3035 return 1;
3036 }
3037
3038 Entropy entropy;
3039 if (!entropy.open()) {
3040 return 1;
3041 }
Kenny Root70e3a862012-02-15 17:20:23 -08003042
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07003043 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003044 if (keymaster_device_initialize(&dev)) {
3045 ALOGE("keystore keymaster could not be initialized; exiting");
3046 return 1;
3047 }
3048
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003049 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003050 if (fallback_keymaster_device_initialize(&fallback)) {
3051 ALOGE("software keymaster could not be initialized; exiting");
3052 return 1;
3053 }
3054
Riley Spahneaabae92014-06-30 12:39:52 -07003055 ks_is_selinux_enabled = is_selinux_enabled();
3056 if (ks_is_selinux_enabled) {
3057 union selinux_callback cb;
3058 cb.func_log = selinux_log_callback;
3059 selinux_set_callback(SELINUX_CB_LOG, cb);
3060 if (getcon(&tctx) != 0) {
3061 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3062 return -1;
3063 }
3064 } else {
3065 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3066 }
3067
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003068 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003069 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003070 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3071 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3072 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3073 if (ret != android::OK) {
3074 ALOGE("Couldn't register binder service!");
3075 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003076 }
Kenny Root07438c82012-11-02 15:41:02 -07003077
3078 /*
3079 * We're the only thread in existence, so we're just going to process
3080 * Binder transaction as a single-threaded program.
3081 */
3082 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003083
3084 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003085 return 1;
3086}