blob: c3896b55fa8b4a3f1782c03b4fe7c342813dc453 [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) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700310 if (callingUid == targetUid) {
311 return true;
312 }
Kenny Root49468902013-03-19 13:41:33 -0700313 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
314 struct user_euid user = user_euids[i];
315 if (user.euid == callingUid && user.uid == targetUid) {
316 return true;
317 }
318 }
319
320 return false;
321}
322
Kenny Roota91203b2012-02-15 15:00:46 -0800323/* Here is the encoding of keys. This is necessary in order to allow arbitrary
324 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
325 * into two bytes. The first byte is one of [+-.] which represents the first
326 * two bits of the character. The second byte encodes the rest of the bits into
327 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
328 * that Base64 cannot be used here due to the need of prefix match on keys. */
329
Kenny Root655b9582013-04-04 08:37:42 -0700330static size_t encode_key_length(const android::String8& keyName) {
331 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
332 size_t length = keyName.length();
333 for (int i = length; i > 0; --i, ++in) {
334 if (*in < '0' || *in > '~') {
335 ++length;
336 }
337 }
338 return length;
339}
340
Kenny Root07438c82012-11-02 15:41:02 -0700341static int encode_key(char* out, const android::String8& keyName) {
342 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
343 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800344 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700345 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800346 *out = '+' + (*in >> 6);
347 *++out = '0' + (*in & 0x3F);
348 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700349 } else {
350 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800351 }
352 }
353 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800354 return length;
355}
356
Kenny Root07438c82012-11-02 15:41:02 -0700357/*
358 * Converts from the "escaped" format on disk to actual name.
359 * This will be smaller than the input string.
360 *
361 * Characters that should combine with the next at the end will be truncated.
362 */
363static size_t decode_key_length(const char* in, size_t length) {
364 size_t outLength = 0;
365
366 for (const char* end = in + length; in < end; in++) {
367 /* This combines with the next character. */
368 if (*in < '0' || *in > '~') {
369 continue;
370 }
371
372 outLength++;
373 }
374 return outLength;
375}
376
377static void decode_key(char* out, const char* in, size_t length) {
378 for (const char* end = in + length; in < end; in++) {
379 if (*in < '0' || *in > '~') {
380 /* Truncate combining characters at the end. */
381 if (in + 1 >= end) {
382 break;
383 }
384
385 *out = (*in++ - '+') << 6;
386 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800387 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700388 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800389 }
390 }
391 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800392}
393
394static size_t readFully(int fd, uint8_t* data, size_t size) {
395 size_t remaining = size;
396 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800397 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800398 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800399 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800400 }
401 data += n;
402 remaining -= n;
403 }
404 return size;
405}
406
407static size_t writeFully(int fd, uint8_t* data, size_t size) {
408 size_t remaining = size;
409 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800410 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
411 if (n < 0) {
412 ALOGW("write failed: %s", strerror(errno));
413 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800414 }
415 data += n;
416 remaining -= n;
417 }
418 return size;
419}
420
421class Entropy {
422public:
423 Entropy() : mRandom(-1) {}
424 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800425 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800426 close(mRandom);
427 }
428 }
429
430 bool open() {
431 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800432 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
433 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800434 ALOGE("open: %s: %s", randomDevice, strerror(errno));
435 return false;
436 }
437 return true;
438 }
439
Kenny Root51878182012-03-13 12:53:19 -0700440 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800441 return (readFully(mRandom, data, size) == size);
442 }
443
444private:
445 int mRandom;
446};
447
448/* Here is the file format. There are two parts in blob.value, the secret and
449 * the description. The secret is stored in ciphertext, and its original size
450 * can be found in blob.length. The description is stored after the secret in
451 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700452 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700453 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800454 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
455 * and decryptBlob(). Thus they should not be accessed from outside. */
456
Kenny Root822c3a92012-03-23 16:34:39 -0700457/* ** Note to future implementors of encryption: **
458 * Currently this is the construction:
459 * metadata || Enc(MD5(data) || data)
460 *
461 * This should be the construction used for encrypting if re-implementing:
462 *
463 * Derive independent keys for encryption and MAC:
464 * Kenc = AES_encrypt(masterKey, "Encrypt")
465 * Kmac = AES_encrypt(masterKey, "MAC")
466 *
467 * Store this:
468 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
469 * HMAC(Kmac, metadata || Enc(data))
470 */
Kenny Roota91203b2012-02-15 15:00:46 -0800471struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700472 uint8_t version;
473 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700474 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800475 uint8_t info;
476 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700477 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800478 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700479 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800480 int32_t length; // in network byte order when encrypted
481 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
482};
483
Kenny Root822c3a92012-03-23 16:34:39 -0700484typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700485 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700486 TYPE_GENERIC = 1,
487 TYPE_MASTER_KEY = 2,
488 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800489 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700490} BlobType;
491
Kenny Rootf9119d62013-04-03 09:22:15 -0700492static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700493
Kenny Roota91203b2012-02-15 15:00:46 -0800494class Blob {
495public:
Kenny Root07438c82012-11-02 15:41:02 -0700496 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
497 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800498 mBlob.length = valueLength;
499 memcpy(mBlob.value, value, valueLength);
500
501 mBlob.info = infoLength;
502 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700503
Kenny Root07438c82012-11-02 15:41:02 -0700504 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700505 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700506
Kenny Rootee8068b2013-10-07 09:49:15 -0700507 if (type == TYPE_MASTER_KEY) {
508 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
509 } else {
510 mBlob.flags = KEYSTORE_FLAG_NONE;
511 }
Kenny Roota91203b2012-02-15 15:00:46 -0800512 }
513
514 Blob(blob b) {
515 mBlob = b;
516 }
517
518 Blob() {}
519
Kenny Root51878182012-03-13 12:53:19 -0700520 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800521 return mBlob.value;
522 }
523
Kenny Root51878182012-03-13 12:53:19 -0700524 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800525 return mBlob.length;
526 }
527
Kenny Root51878182012-03-13 12:53:19 -0700528 const uint8_t* getInfo() const {
529 return mBlob.value + mBlob.length;
530 }
531
532 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.info;
534 }
535
Kenny Root822c3a92012-03-23 16:34:39 -0700536 uint8_t getVersion() const {
537 return mBlob.version;
538 }
539
Kenny Rootf9119d62013-04-03 09:22:15 -0700540 bool isEncrypted() const {
541 if (mBlob.version < 2) {
542 return true;
543 }
544
545 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
546 }
547
548 void setEncrypted(bool encrypted) {
549 if (encrypted) {
550 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
551 } else {
552 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
553 }
554 }
555
Kenny Root17208e02013-09-04 13:56:03 -0700556 bool isFallback() const {
557 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
558 }
559
560 void setFallback(bool fallback) {
561 if (fallback) {
562 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
563 } else {
564 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
565 }
566 }
567
Kenny Root822c3a92012-03-23 16:34:39 -0700568 void setVersion(uint8_t version) {
569 mBlob.version = version;
570 }
571
572 BlobType getType() const {
573 return BlobType(mBlob.type);
574 }
575
576 void setType(BlobType type) {
577 mBlob.type = uint8_t(type);
578 }
579
Kenny Rootf9119d62013-04-03 09:22:15 -0700580 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
581 ALOGV("writing blob %s", filename);
582 if (isEncrypted()) {
583 if (state != STATE_NO_ERROR) {
584 ALOGD("couldn't insert encrypted blob while not unlocked");
585 return LOCKED;
586 }
587
588 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
589 ALOGW("Could not read random data for: %s", filename);
590 return SYSTEM_ERROR;
591 }
Kenny Roota91203b2012-02-15 15:00:46 -0800592 }
593
594 // data includes the value and the value's length
595 size_t dataLength = mBlob.length + sizeof(mBlob.length);
596 // pad data to the AES_BLOCK_SIZE
597 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
598 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
599 // encrypted data includes the digest value
600 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
601 // move info after space for padding
602 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
603 // zero padding area
604 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
605
606 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800607
Kenny Rootf9119d62013-04-03 09:22:15 -0700608 if (isEncrypted()) {
609 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800610
Kenny Rootf9119d62013-04-03 09:22:15 -0700611 uint8_t vector[AES_BLOCK_SIZE];
612 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
613 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
614 aes_key, vector, AES_ENCRYPT);
615 }
616
Kenny Roota91203b2012-02-15 15:00:46 -0800617 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
618 size_t fileLength = encryptedLength + headerLength + mBlob.info;
619
620 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800621 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
622 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
623 if (out < 0) {
624 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800625 return SYSTEM_ERROR;
626 }
627 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
628 if (close(out) != 0) {
629 return SYSTEM_ERROR;
630 }
631 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800632 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800633 unlink(tmpFileName);
634 return SYSTEM_ERROR;
635 }
Kenny Root150ca932012-11-14 14:29:02 -0800636 if (rename(tmpFileName, filename) == -1) {
637 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
638 return SYSTEM_ERROR;
639 }
640 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800641 }
642
Kenny Rootf9119d62013-04-03 09:22:15 -0700643 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
644 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800645 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
646 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800647 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
648 }
649 // fileLength may be less than sizeof(mBlob) since the in
650 // memory version has extra padding to tolerate rounding up to
651 // the AES_BLOCK_SIZE
652 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
653 if (close(in) != 0) {
654 return SYSTEM_ERROR;
655 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700656
657 if (isEncrypted() && (state != STATE_NO_ERROR)) {
658 return LOCKED;
659 }
660
Kenny Roota91203b2012-02-15 15:00:46 -0800661 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
662 if (fileLength < headerLength) {
663 return VALUE_CORRUPTED;
664 }
665
666 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700667 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800668 return VALUE_CORRUPTED;
669 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700670
671 ssize_t digestedLength;
672 if (isEncrypted()) {
673 if (encryptedLength % AES_BLOCK_SIZE != 0) {
674 return VALUE_CORRUPTED;
675 }
676
677 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
678 mBlob.vector, AES_DECRYPT);
679 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
680 uint8_t computedDigest[MD5_DIGEST_LENGTH];
681 MD5(mBlob.digested, digestedLength, computedDigest);
682 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
683 return VALUE_CORRUPTED;
684 }
685 } else {
686 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800687 }
688
689 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
690 mBlob.length = ntohl(mBlob.length);
691 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
692 return VALUE_CORRUPTED;
693 }
694 if (mBlob.info != 0) {
695 // move info from after padding to after data
696 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
697 }
Kenny Root07438c82012-11-02 15:41:02 -0700698 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800699 }
700
701private:
702 struct blob mBlob;
703};
704
Kenny Root655b9582013-04-04 08:37:42 -0700705class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800706public:
Kenny Root655b9582013-04-04 08:37:42 -0700707 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
708 asprintf(&mUserDir, "user_%u", mUserId);
709 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
710 }
711
712 ~UserState() {
713 free(mUserDir);
714 free(mMasterKeyFile);
715 }
716
717 bool initialize() {
718 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
719 ALOGE("Could not create directory '%s'", mUserDir);
720 return false;
721 }
722
723 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800724 setState(STATE_LOCKED);
725 } else {
726 setState(STATE_UNINITIALIZED);
727 }
Kenny Root70e3a862012-02-15 17:20:23 -0800728
Kenny Root655b9582013-04-04 08:37:42 -0700729 return true;
730 }
731
732 uid_t getUserId() const {
733 return mUserId;
734 }
735
736 const char* getUserDirName() const {
737 return mUserDir;
738 }
739
740 const char* getMasterKeyFileName() const {
741 return mMasterKeyFile;
742 }
743
744 void setState(State state) {
745 mState = state;
746 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
747 mRetry = MAX_RETRY;
748 }
Kenny Roota91203b2012-02-15 15:00:46 -0800749 }
750
Kenny Root51878182012-03-13 12:53:19 -0700751 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800752 return mState;
753 }
754
Kenny Root51878182012-03-13 12:53:19 -0700755 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800756 return mRetry;
757 }
758
Kenny Root655b9582013-04-04 08:37:42 -0700759 void zeroizeMasterKeysInMemory() {
760 memset(mMasterKey, 0, sizeof(mMasterKey));
761 memset(mSalt, 0, sizeof(mSalt));
762 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
763 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800764 }
765
Kenny Root655b9582013-04-04 08:37:42 -0700766 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
767 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800768 return SYSTEM_ERROR;
769 }
Kenny Root655b9582013-04-04 08:37:42 -0700770 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800771 if (response != NO_ERROR) {
772 return response;
773 }
774 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700775 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800776 }
777
Robin Lee4e865752014-08-19 17:37:55 +0100778 ResponseCode copyMasterKey(UserState* src) {
779 if (mState != STATE_UNINITIALIZED) {
780 return ::SYSTEM_ERROR;
781 }
782 if (src->getState() != STATE_NO_ERROR) {
783 return ::SYSTEM_ERROR;
784 }
785 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
786 setupMasterKeys();
787 return ::NO_ERROR;
788 }
789
Kenny Root655b9582013-04-04 08:37:42 -0700790 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800791 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
792 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
793 AES_KEY passwordAesKey;
794 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700795 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700796 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800797 }
798
Kenny Root655b9582013-04-04 08:37:42 -0700799 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
800 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800801 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800802 return SYSTEM_ERROR;
803 }
804
805 // we read the raw blob to just to get the salt to generate
806 // the AES key, then we create the Blob to use with decryptBlob
807 blob rawBlob;
808 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
809 if (close(in) != 0) {
810 return SYSTEM_ERROR;
811 }
812 // find salt at EOF if present, otherwise we have an old file
813 uint8_t* salt;
814 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
815 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
816 } else {
817 salt = NULL;
818 }
819 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
820 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
821 AES_KEY passwordAesKey;
822 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
823 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700824 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
825 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800826 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700827 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800828 }
829 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
830 // if salt was missing, generate one and write a new master key file with the salt.
831 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700832 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800833 return SYSTEM_ERROR;
834 }
Kenny Root655b9582013-04-04 08:37:42 -0700835 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800836 }
837 if (response == NO_ERROR) {
838 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
839 setupMasterKeys();
840 }
841 return response;
842 }
843 if (mRetry <= 0) {
844 reset();
845 return UNINITIALIZED;
846 }
847 --mRetry;
848 switch (mRetry) {
849 case 0: return WRONG_PASSWORD_0;
850 case 1: return WRONG_PASSWORD_1;
851 case 2: return WRONG_PASSWORD_2;
852 case 3: return WRONG_PASSWORD_3;
853 default: return WRONG_PASSWORD_3;
854 }
855 }
856
Kenny Root655b9582013-04-04 08:37:42 -0700857 AES_KEY* getEncryptionKey() {
858 return &mMasterKeyEncryption;
859 }
860
861 AES_KEY* getDecryptionKey() {
862 return &mMasterKeyDecryption;
863 }
864
Kenny Roota91203b2012-02-15 15:00:46 -0800865 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700866 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800867 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700868 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800869 return false;
870 }
Kenny Root655b9582013-04-04 08:37:42 -0700871
872 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800873 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700874 // We only care about files.
875 if (file->d_type != DT_REG) {
876 continue;
877 }
878
879 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700880 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700881 continue;
882 }
883
884 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800885 }
886 closedir(dir);
887 return true;
888 }
889
Kenny Root655b9582013-04-04 08:37:42 -0700890private:
891 static const int MASTER_KEY_SIZE_BYTES = 16;
892 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
893
894 static const int MAX_RETRY = 4;
895 static const size_t SALT_SIZE = 16;
896
897 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
898 uint8_t* salt) {
899 size_t saltSize;
900 if (salt != NULL) {
901 saltSize = SALT_SIZE;
902 } else {
903 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
904 salt = (uint8_t*) "keystore";
905 // sizeof = 9, not strlen = 8
906 saltSize = sizeof("keystore");
907 }
908
909 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
910 saltSize, 8192, keySize, key);
911 }
912
913 bool generateSalt(Entropy* entropy) {
914 return entropy->generate_random_data(mSalt, sizeof(mSalt));
915 }
916
917 bool generateMasterKey(Entropy* entropy) {
918 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
919 return false;
920 }
921 if (!generateSalt(entropy)) {
922 return false;
923 }
924 return true;
925 }
926
927 void setupMasterKeys() {
928 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
929 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
930 setState(STATE_NO_ERROR);
931 }
932
933 uid_t mUserId;
934
935 char* mUserDir;
936 char* mMasterKeyFile;
937
938 State mState;
939 int8_t mRetry;
940
941 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
942 uint8_t mSalt[SALT_SIZE];
943
944 AES_KEY mMasterKeyEncryption;
945 AES_KEY mMasterKeyDecryption;
946};
947
948typedef struct {
949 uint32_t uid;
950 const uint8_t* filename;
951} grant_t;
952
953class KeyStore {
954public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800955 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700956 : mEntropy(entropy)
957 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800958 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700959 {
960 memset(&mMetaData, '\0', sizeof(mMetaData));
961 }
962
963 ~KeyStore() {
964 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
965 it != mGrants.end(); it++) {
966 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700967 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800968 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700969
970 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
971 it != mMasterKeys.end(); it++) {
972 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700973 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800974 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700975 }
976
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800977 /**
978 * Depending on the hardware keymaster version is this may return a
979 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
980 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
981 * be guarded by a check on the device's version.
982 */
983 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700984 return mDevice;
985 }
986
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800987 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800988 return mFallbackDevice;
989 }
990
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800991 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800992 return blob.isFallback() ? mFallbackDevice: mDevice;
993 }
994
Kenny Root655b9582013-04-04 08:37:42 -0700995 ResponseCode initialize() {
996 readMetaData();
997 if (upgradeKeystore()) {
998 writeMetaData();
999 }
1000
1001 return ::NO_ERROR;
1002 }
1003
1004 State getState(uid_t uid) {
1005 return getUserState(uid)->getState();
1006 }
1007
1008 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1009 UserState* userState = getUserState(uid);
1010 return userState->initialize(pw, mEntropy);
1011 }
1012
Robin Lee4e865752014-08-19 17:37:55 +01001013 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1014 UserState *userState = getUserState(uid);
1015 UserState *initState = getUserState(src);
1016 return userState->copyMasterKey(initState);
1017 }
1018
Kenny Root655b9582013-04-04 08:37:42 -07001019 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001020 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001021 return userState->writeMasterKey(pw, mEntropy);
1022 }
1023
1024 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001025 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001026 return userState->readMasterKey(pw, mEntropy);
1027 }
1028
1029 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001030 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001031 encode_key(encoded, keyName);
1032 return android::String8(encoded);
1033 }
1034
1035 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
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::format("%u_%s", uid, encoded);
1039 }
1040
1041 android::String8 getKeyNameForUidWithDir(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("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1045 encoded);
1046 }
1047
1048 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001049 android::String8 prefix("");
1050 android::Vector<android::String16> aliases;
1051 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1052 return ::SYSTEM_ERROR;
1053 }
1054
Kenny Root655b9582013-04-04 08:37:42 -07001055 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001056 for (uint32_t i = 0; i < aliases.size(); i++) {
1057 android::String8 filename(aliases[i]);
1058 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1059 getKeyName(filename).string());
1060 del(filename, ::TYPE_ANY, uid);
1061 }
1062
Kenny Root655b9582013-04-04 08:37:42 -07001063 userState->zeroizeMasterKeysInMemory();
1064 userState->setState(STATE_UNINITIALIZED);
1065 return userState->reset();
1066 }
1067
1068 bool isEmpty(uid_t uid) const {
1069 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001070 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001071 return true;
1072 }
1073
1074 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001075 if (!dir) {
1076 return true;
1077 }
Kenny Root31e27462014-09-10 11:28:03 -07001078
Kenny Roota91203b2012-02-15 15:00:46 -08001079 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001080 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001081 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001082 // We only care about files.
1083 if (file->d_type != DT_REG) {
1084 continue;
1085 }
1086
1087 // Skip anything that starts with a "."
1088 if (file->d_name[0] == '.') {
1089 continue;
1090 }
1091
Kenny Root31e27462014-09-10 11:28:03 -07001092 result = false;
1093 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001094 }
1095 closedir(dir);
1096 return result;
1097 }
1098
Kenny Root655b9582013-04-04 08:37:42 -07001099 void lock(uid_t uid) {
1100 UserState* userState = getUserState(uid);
1101 userState->zeroizeMasterKeysInMemory();
1102 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001103 }
1104
Kenny Root655b9582013-04-04 08:37:42 -07001105 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1106 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001107 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1108 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001109 if (rc != NO_ERROR) {
1110 return rc;
1111 }
1112
1113 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001114 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001115 /* If we upgrade the key, we need to write it to disk again. Then
1116 * it must be read it again since the blob is encrypted each time
1117 * it's written.
1118 */
Kenny Root655b9582013-04-04 08:37:42 -07001119 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1120 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001121 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1122 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001123 return rc;
1124 }
1125 }
Kenny Root822c3a92012-03-23 16:34:39 -07001126 }
1127
Kenny Root17208e02013-09-04 13:56:03 -07001128 /*
1129 * This will upgrade software-backed keys to hardware-backed keys when
1130 * the HAL for the device supports the newer key types.
1131 */
1132 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1133 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1134 && keyBlob->isFallback()) {
1135 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1136 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1137
1138 // The HAL allowed the import, reget the key to have the "fresh"
1139 // version.
1140 if (imported == NO_ERROR) {
1141 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1142 }
1143 }
1144
Kenny Rootd53bc922013-03-21 14:10:15 -07001145 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001146 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1147 return KEY_NOT_FOUND;
1148 }
1149
1150 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001151 }
1152
Kenny Root655b9582013-04-04 08:37:42 -07001153 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1154 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001155 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1156 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001157 }
1158
Robin Lee4b84fdc2014-09-24 11:56:57 +01001159 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1160 Blob keyBlob;
1161 ResponseCode rc = get(filename, &keyBlob, type, uid);
1162 if (rc != ::NO_ERROR) {
1163 return rc;
1164 }
1165
1166 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1167 // A device doesn't have to implement delete_keypair.
1168 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1169 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1170 rc = ::SYSTEM_ERROR;
1171 }
1172 }
1173 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001174 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1175 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1176 if (dev->delete_key) {
1177 keymaster_key_blob_t blob;
1178 blob.key_material = keyBlob.getValue();
1179 blob.key_material_size = keyBlob.getLength();
1180 dev->delete_key(dev, &blob);
1181 }
1182 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001183 if (rc != ::NO_ERROR) {
1184 return rc;
1185 }
1186
1187 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1188 }
1189
1190 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1191 uid_t uid) {
1192
1193 UserState* userState = getUserState(uid);
1194 size_t n = prefix.length();
1195
1196 DIR* dir = opendir(userState->getUserDirName());
1197 if (!dir) {
1198 ALOGW("can't open directory for user: %s", strerror(errno));
1199 return ::SYSTEM_ERROR;
1200 }
1201
1202 struct dirent* file;
1203 while ((file = readdir(dir)) != NULL) {
1204 // We only care about files.
1205 if (file->d_type != DT_REG) {
1206 continue;
1207 }
1208
1209 // Skip anything that starts with a "."
1210 if (file->d_name[0] == '.') {
1211 continue;
1212 }
1213
1214 if (!strncmp(prefix.string(), file->d_name, n)) {
1215 const char* p = &file->d_name[n];
1216 size_t plen = strlen(p);
1217
1218 size_t extra = decode_key_length(p, plen);
1219 char *match = (char*) malloc(extra + 1);
1220 if (match != NULL) {
1221 decode_key(match, p, plen);
1222 matches->push(android::String16(match, extra));
1223 free(match);
1224 } else {
1225 ALOGW("could not allocate match of size %zd", extra);
1226 }
1227 }
1228 }
1229 closedir(dir);
1230 return ::NO_ERROR;
1231 }
1232
Kenny Root07438c82012-11-02 15:41:02 -07001233 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001234 const grant_t* existing = getGrant(filename, granteeUid);
1235 if (existing == NULL) {
1236 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001237 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001238 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001239 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001240 }
1241 }
1242
Kenny Root07438c82012-11-02 15:41:02 -07001243 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001244 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1245 it != mGrants.end(); it++) {
1246 grant_t* grant = *it;
1247 if (grant->uid == granteeUid
1248 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1249 mGrants.erase(it);
1250 return true;
1251 }
Kenny Root70e3a862012-02-15 17:20:23 -08001252 }
Kenny Root70e3a862012-02-15 17:20:23 -08001253 return false;
1254 }
1255
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001256 bool hasGrant(const char* filename, const uid_t uid) const {
1257 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001258 }
1259
Kenny Rootf9119d62013-04-03 09:22:15 -07001260 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1261 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001262 uint8_t* data;
1263 size_t dataLength;
1264 int rc;
1265
1266 if (mDevice->import_keypair == NULL) {
1267 ALOGE("Keymaster doesn't support import!");
1268 return SYSTEM_ERROR;
1269 }
1270
Kenny Root17208e02013-09-04 13:56:03 -07001271 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001272 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001273 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001274 /*
1275 * Maybe the device doesn't support this type of key. Try to use the
1276 * software fallback keymaster implementation. This is a little bit
1277 * lazier than checking the PKCS#8 key type, but the software
1278 * implementation will do that anyway.
1279 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001280 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001281 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001282
1283 if (rc) {
1284 ALOGE("Error while importing keypair: %d", rc);
1285 return SYSTEM_ERROR;
1286 }
Kenny Root822c3a92012-03-23 16:34:39 -07001287 }
1288
1289 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1290 free(data);
1291
Kenny Rootf9119d62013-04-03 09:22:15 -07001292 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001293 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001294
Kenny Root655b9582013-04-04 08:37:42 -07001295 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001296 }
1297
Kenny Root1b0e3932013-09-05 13:06:32 -07001298 bool isHardwareBacked(const android::String16& keyType) const {
1299 if (mDevice == NULL) {
1300 ALOGW("can't get keymaster device");
1301 return false;
1302 }
1303
1304 if (sRSAKeyType == keyType) {
1305 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1306 } else {
1307 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1308 && (mDevice->common.module->module_api_version
1309 >= KEYMASTER_MODULE_API_VERSION_0_2);
1310 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001311 }
1312
Kenny Root655b9582013-04-04 08:37:42 -07001313 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1314 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001315 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001316
1317 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1318 if (responseCode == NO_ERROR) {
1319 return responseCode;
1320 }
1321
1322 // If this is one of the legacy UID->UID mappings, use it.
1323 uid_t euid = get_keystore_euid(uid);
1324 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001325 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001326 responseCode = get(filepath8.string(), keyBlob, type, uid);
1327 if (responseCode == NO_ERROR) {
1328 return responseCode;
1329 }
1330 }
1331
1332 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001333 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001334 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001335 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001336 if (end[0] != '_' || end[1] == 0) {
1337 return KEY_NOT_FOUND;
1338 }
Kenny Root86b16e82013-09-09 11:15:54 -07001339 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1340 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001341 if (!hasGrant(filepath8.string(), uid)) {
1342 return responseCode;
1343 }
1344
1345 // It is a granted key. Try to load it.
1346 return get(filepath8.string(), keyBlob, type, uid);
1347 }
1348
1349 /**
1350 * Returns any existing UserState or creates it if it doesn't exist.
1351 */
1352 UserState* getUserState(uid_t uid) {
1353 uid_t userId = get_user_id(uid);
1354
1355 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1356 it != mMasterKeys.end(); it++) {
1357 UserState* state = *it;
1358 if (state->getUserId() == userId) {
1359 return state;
1360 }
1361 }
1362
1363 UserState* userState = new UserState(userId);
1364 if (!userState->initialize()) {
1365 /* There's not much we can do if initialization fails. Trying to
1366 * unlock the keystore for that user will fail as well, so any
1367 * subsequent request for this user will just return SYSTEM_ERROR.
1368 */
1369 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1370 }
1371 mMasterKeys.add(userState);
1372 return userState;
1373 }
1374
1375 /**
1376 * Returns NULL if the UserState doesn't already exist.
1377 */
1378 const UserState* getUserState(uid_t uid) const {
1379 uid_t userId = get_user_id(uid);
1380
1381 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1382 it != mMasterKeys.end(); it++) {
1383 UserState* state = *it;
1384 if (state->getUserId() == userId) {
1385 return state;
1386 }
1387 }
1388
1389 return NULL;
1390 }
1391
Kenny Roota91203b2012-02-15 15:00:46 -08001392private:
Kenny Root655b9582013-04-04 08:37:42 -07001393 static const char* sOldMasterKey;
1394 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001395 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001396 Entropy* mEntropy;
1397
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001398 keymaster1_device_t* mDevice;
1399 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001400
Kenny Root655b9582013-04-04 08:37:42 -07001401 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001402
Kenny Root655b9582013-04-04 08:37:42 -07001403 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001404
Kenny Root655b9582013-04-04 08:37:42 -07001405 typedef struct {
1406 uint32_t version;
1407 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001408
Kenny Root655b9582013-04-04 08:37:42 -07001409 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001410
Kenny Root655b9582013-04-04 08:37:42 -07001411 const grant_t* getGrant(const char* filename, uid_t uid) const {
1412 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1413 it != mGrants.end(); it++) {
1414 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001415 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001416 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001417 return grant;
1418 }
1419 }
Kenny Root70e3a862012-02-15 17:20:23 -08001420 return NULL;
1421 }
1422
Kenny Root822c3a92012-03-23 16:34:39 -07001423 /**
1424 * Upgrade code. This will upgrade the key from the current version
1425 * to whatever is newest.
1426 */
Kenny Root655b9582013-04-04 08:37:42 -07001427 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1428 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001429 bool updated = false;
1430 uint8_t version = oldVersion;
1431
1432 /* From V0 -> V1: All old types were unknown */
1433 if (version == 0) {
1434 ALOGV("upgrading to version 1 and setting type %d", type);
1435
1436 blob->setType(type);
1437 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001438 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001439 }
1440 version = 1;
1441 updated = true;
1442 }
1443
Kenny Rootf9119d62013-04-03 09:22:15 -07001444 /* From V1 -> V2: All old keys were encrypted */
1445 if (version == 1) {
1446 ALOGV("upgrading to version 2");
1447
1448 blob->setEncrypted(true);
1449 version = 2;
1450 updated = true;
1451 }
1452
Kenny Root822c3a92012-03-23 16:34:39 -07001453 /*
1454 * If we've updated, set the key blob to the right version
1455 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001456 */
Kenny Root822c3a92012-03-23 16:34:39 -07001457 if (updated) {
1458 ALOGV("updated and writing file %s", filename);
1459 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001460 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001461
1462 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001463 }
1464
1465 /**
1466 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1467 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1468 * Then it overwrites the original blob with the new blob
1469 * format that is returned from the keymaster.
1470 */
Kenny Root655b9582013-04-04 08:37:42 -07001471 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001472 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1473 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1474 if (b.get() == NULL) {
1475 ALOGE("Problem instantiating BIO");
1476 return SYSTEM_ERROR;
1477 }
1478
1479 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1480 if (pkey.get() == NULL) {
1481 ALOGE("Couldn't read old PEM file");
1482 return SYSTEM_ERROR;
1483 }
1484
1485 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1486 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1487 if (len < 0) {
1488 ALOGE("Couldn't measure PKCS#8 length");
1489 return SYSTEM_ERROR;
1490 }
1491
Kenny Root70c98892013-02-07 09:10:36 -08001492 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1493 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001494 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1495 ALOGE("Couldn't convert to PKCS#8");
1496 return SYSTEM_ERROR;
1497 }
1498
Kenny Rootf9119d62013-04-03 09:22:15 -07001499 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1500 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001501 if (rc != NO_ERROR) {
1502 return rc;
1503 }
1504
Kenny Root655b9582013-04-04 08:37:42 -07001505 return get(filename, blob, TYPE_KEY_PAIR, uid);
1506 }
1507
1508 void readMetaData() {
1509 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1510 if (in < 0) {
1511 return;
1512 }
1513 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1514 if (fileLength != sizeof(mMetaData)) {
1515 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1516 sizeof(mMetaData));
1517 }
1518 close(in);
1519 }
1520
1521 void writeMetaData() {
1522 const char* tmpFileName = ".metadata.tmp";
1523 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1524 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1525 if (out < 0) {
1526 ALOGE("couldn't write metadata file: %s", strerror(errno));
1527 return;
1528 }
1529 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1530 if (fileLength != sizeof(mMetaData)) {
1531 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1532 sizeof(mMetaData));
1533 }
1534 close(out);
1535 rename(tmpFileName, sMetaDataFile);
1536 }
1537
1538 bool upgradeKeystore() {
1539 bool upgraded = false;
1540
1541 if (mMetaData.version == 0) {
1542 UserState* userState = getUserState(0);
1543
1544 // Initialize first so the directory is made.
1545 userState->initialize();
1546
1547 // Migrate the old .masterkey file to user 0.
1548 if (access(sOldMasterKey, R_OK) == 0) {
1549 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1550 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1551 return false;
1552 }
1553 }
1554
1555 // Initialize again in case we had a key.
1556 userState->initialize();
1557
1558 // Try to migrate existing keys.
1559 DIR* dir = opendir(".");
1560 if (!dir) {
1561 // Give up now; maybe we can upgrade later.
1562 ALOGE("couldn't open keystore's directory; something is wrong");
1563 return false;
1564 }
1565
1566 struct dirent* file;
1567 while ((file = readdir(dir)) != NULL) {
1568 // We only care about files.
1569 if (file->d_type != DT_REG) {
1570 continue;
1571 }
1572
1573 // Skip anything that starts with a "."
1574 if (file->d_name[0] == '.') {
1575 continue;
1576 }
1577
1578 // Find the current file's user.
1579 char* end;
1580 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1581 if (end[0] != '_' || end[1] == 0) {
1582 continue;
1583 }
1584 UserState* otherUser = getUserState(thisUid);
1585 if (otherUser->getUserId() != 0) {
1586 unlinkat(dirfd(dir), file->d_name, 0);
1587 }
1588
1589 // Rename the file into user directory.
1590 DIR* otherdir = opendir(otherUser->getUserDirName());
1591 if (otherdir == NULL) {
1592 ALOGW("couldn't open user directory for rename");
1593 continue;
1594 }
1595 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1596 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1597 }
1598 closedir(otherdir);
1599 }
1600 closedir(dir);
1601
1602 mMetaData.version = 1;
1603 upgraded = true;
1604 }
1605
1606 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001607 }
Kenny Roota91203b2012-02-15 15:00:46 -08001608};
1609
Kenny Root655b9582013-04-04 08:37:42 -07001610const char* KeyStore::sOldMasterKey = ".masterkey";
1611const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001612
Kenny Root1b0e3932013-09-05 13:06:32 -07001613const android::String16 KeyStore::sRSAKeyType("RSA");
1614
Kenny Root07438c82012-11-02 15:41:02 -07001615namespace android {
1616class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1617public:
1618 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001619 : mKeyStore(keyStore),
1620 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001621 {
Kenny Roota91203b2012-02-15 15:00:46 -08001622 }
Kenny Roota91203b2012-02-15 15:00:46 -08001623
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001624 void binderDied(const wp<IBinder>& who) {
1625 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1626 for (auto token: operations) {
1627 abort(token);
1628 }
Kenny Root822c3a92012-03-23 16:34:39 -07001629 }
Kenny Roota91203b2012-02-15 15:00:46 -08001630
Kenny Root07438c82012-11-02 15:41:02 -07001631 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001632 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001633 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001634 }
Kenny Roota91203b2012-02-15 15:00:46 -08001635
Chad Brubaker9489b792015-04-14 11:01:45 -07001636 return mKeyStore->getState(IPCThreadState::self()->getCallingUid());
Kenny Root298e7b12012-03-26 13:54:44 -07001637 }
1638
Kenny Root07438c82012-11-02 15:41:02 -07001639 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001640 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001641 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001642 }
Kenny Root07438c82012-11-02 15:41:02 -07001643
Chad Brubaker9489b792015-04-14 11:01:45 -07001644 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001645 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001646 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001647
Kenny Root655b9582013-04-04 08:37:42 -07001648 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001649 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001650 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001651 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001652 *item = NULL;
1653 *itemLength = 0;
1654 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001655 }
Kenny Roota91203b2012-02-15 15:00:46 -08001656
Kenny Root07438c82012-11-02 15:41:02 -07001657 *item = (uint8_t*) malloc(keyBlob.getLength());
1658 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1659 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001660
Kenny Root07438c82012-11-02 15:41:02 -07001661 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001662 }
1663
Kenny Rootf9119d62013-04-03 09:22:15 -07001664 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1665 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001666 targetUid = getEffectiveUid(targetUid);
1667 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1668 flags & KEYSTORE_FLAG_ENCRYPTED);
1669 if (result != ::NO_ERROR) {
1670 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001671 }
1672
Kenny Root07438c82012-11-02 15:41:02 -07001673 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001674 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001675
1676 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001677 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1678
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001679 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001680 }
1681
Kenny Root49468902013-03-19 13:41:33 -07001682 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001683 targetUid = getEffectiveUid(targetUid);
1684 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001685 return ::PERMISSION_DENIED;
1686 }
Kenny Root07438c82012-11-02 15:41:02 -07001687 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001688 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001689 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001690 }
1691
Kenny Root49468902013-03-19 13:41:33 -07001692 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001693 targetUid = getEffectiveUid(targetUid);
1694 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001695 return ::PERMISSION_DENIED;
1696 }
1697
Kenny Root07438c82012-11-02 15:41:02 -07001698 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001699 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001700
Kenny Root655b9582013-04-04 08:37:42 -07001701 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001702 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1703 }
1704 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001705 }
1706
Kenny Root49468902013-03-19 13:41:33 -07001707 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001708 targetUid = getEffectiveUid(targetUid);
1709 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001710 return ::PERMISSION_DENIED;
1711 }
Kenny Root07438c82012-11-02 15:41:02 -07001712 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001713 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001714
Robin Lee4b84fdc2014-09-24 11:56:57 +01001715 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1716 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001717 }
Kenny Root07438c82012-11-02 15:41:02 -07001718 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001719 }
1720
Kenny Root07438c82012-11-02 15:41:02 -07001721 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001722 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001723 return ::PERMISSION_DENIED;
1724 }
1725
Chad Brubaker9489b792015-04-14 11:01:45 -07001726 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01001727 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001728 }
1729
Kenny Root07438c82012-11-02 15:41:02 -07001730 /*
1731 * Here is the history. To improve the security, the parameters to generate the
1732 * master key has been changed. To make a seamless transition, we update the
1733 * file using the same password when the user unlock it for the first time. If
1734 * any thing goes wrong during the transition, the new file will not overwrite
1735 * the old one. This avoids permanent damages of the existing data.
1736 */
1737 int32_t password(const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001738 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001739 return ::PERMISSION_DENIED;
1740 }
Kenny Root70e3a862012-02-15 17:20:23 -08001741
Kenny Root07438c82012-11-02 15:41:02 -07001742 const String8 password8(password);
Chad Brubaker9489b792015-04-14 11:01:45 -07001743 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root70e3a862012-02-15 17:20:23 -08001744
Kenny Root655b9582013-04-04 08:37:42 -07001745 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001746 case ::STATE_UNINITIALIZED: {
1747 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001748 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001749 }
1750 case ::STATE_NO_ERROR: {
1751 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001752 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001753 }
1754 case ::STATE_LOCKED: {
1755 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001756 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001757 }
1758 }
1759 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001760 }
1761
Kenny Root07438c82012-11-02 15:41:02 -07001762 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001763 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001764 return ::PERMISSION_DENIED;
1765 }
Kenny Root70e3a862012-02-15 17:20:23 -08001766
Chad Brubaker9489b792015-04-14 11:01:45 -07001767 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001768 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001769 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001770 ALOGD("calling lock in state: %d", state);
1771 return state;
1772 }
1773
Kenny Root655b9582013-04-04 08:37:42 -07001774 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001775 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001776 }
1777
Kenny Root07438c82012-11-02 15:41:02 -07001778 int32_t unlock(const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001779 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001780 return ::PERMISSION_DENIED;
1781 }
1782
Chad Brubaker9489b792015-04-14 11:01:45 -07001783 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001784 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001785 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001786 ALOGD("calling unlock when not locked");
1787 return state;
1788 }
1789
1790 const String8 password8(pw);
1791 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001792 }
1793
Kenny Root07438c82012-11-02 15:41:02 -07001794 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001795 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001796 return -1;
1797 }
Kenny Root70e3a862012-02-15 17:20:23 -08001798
Chad Brubaker9489b792015-04-14 11:01:45 -07001799 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001800 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001801 }
1802
Kenny Root96427ba2013-08-16 14:02:41 -07001803 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1804 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001805 targetUid = getEffectiveUid(targetUid);
1806 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1807 flags & KEYSTORE_FLAG_ENCRYPTED);
1808 if (result != ::NO_ERROR) {
1809 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001810 }
Kenny Root07438c82012-11-02 15:41:02 -07001811 uint8_t* data;
1812 size_t dataLength;
1813 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001814 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001815
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001816 const keymaster1_device_t* device = mKeyStore->getDevice();
1817 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001818 if (device == NULL) {
1819 return ::SYSTEM_ERROR;
1820 }
1821
1822 if (device->generate_keypair == NULL) {
1823 return ::SYSTEM_ERROR;
1824 }
1825
Kenny Root17208e02013-09-04 13:56:03 -07001826 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001827 keymaster_dsa_keygen_params_t dsa_params;
1828 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001829
Kenny Root96427ba2013-08-16 14:02:41 -07001830 if (keySize == -1) {
1831 keySize = DSA_DEFAULT_KEY_SIZE;
1832 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1833 || keySize > DSA_MAX_KEY_SIZE) {
1834 ALOGI("invalid key size %d", keySize);
1835 return ::SYSTEM_ERROR;
1836 }
1837 dsa_params.key_size = keySize;
1838
1839 if (args->size() == 3) {
1840 sp<KeystoreArg> gArg = args->itemAt(0);
1841 sp<KeystoreArg> pArg = args->itemAt(1);
1842 sp<KeystoreArg> qArg = args->itemAt(2);
1843
1844 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1845 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1846 dsa_params.generator_len = gArg->size();
1847
1848 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1849 dsa_params.prime_p_len = pArg->size();
1850
1851 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1852 dsa_params.prime_q_len = qArg->size();
1853 } else {
1854 ALOGI("not all DSA parameters were read");
1855 return ::SYSTEM_ERROR;
1856 }
1857 } else if (args->size() != 0) {
1858 ALOGI("DSA args must be 3");
1859 return ::SYSTEM_ERROR;
1860 }
1861
Kenny Root1d448c02013-11-21 10:36:53 -08001862 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001863 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1864 } else {
1865 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001866 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1867 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001868 }
1869 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001870 keymaster_ec_keygen_params_t ec_params;
1871 memset(&ec_params, '\0', sizeof(ec_params));
1872
1873 if (keySize == -1) {
1874 keySize = EC_DEFAULT_KEY_SIZE;
1875 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1876 ALOGI("invalid key size %d", keySize);
1877 return ::SYSTEM_ERROR;
1878 }
1879 ec_params.field_size = keySize;
1880
Kenny Root1d448c02013-11-21 10:36:53 -08001881 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001882 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1883 } else {
1884 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001885 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001886 }
Kenny Root96427ba2013-08-16 14:02:41 -07001887 } else if (keyType == EVP_PKEY_RSA) {
1888 keymaster_rsa_keygen_params_t rsa_params;
1889 memset(&rsa_params, '\0', sizeof(rsa_params));
1890 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1891
1892 if (keySize == -1) {
1893 keySize = RSA_DEFAULT_KEY_SIZE;
1894 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1895 ALOGI("invalid key size %d", keySize);
1896 return ::SYSTEM_ERROR;
1897 }
1898 rsa_params.modulus_size = keySize;
1899
1900 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001901 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001902 return ::SYSTEM_ERROR;
1903 } else if (args->size() == 1) {
1904 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1905 if (pubExpBlob != NULL) {
1906 Unique_BIGNUM pubExpBn(
1907 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1908 pubExpBlob->size(), NULL));
1909 if (pubExpBn.get() == NULL) {
1910 ALOGI("Could not convert public exponent to BN");
1911 return ::SYSTEM_ERROR;
1912 }
1913 unsigned long pubExp = BN_get_word(pubExpBn.get());
1914 if (pubExp == 0xFFFFFFFFL) {
1915 ALOGI("cannot represent public exponent as a long value");
1916 return ::SYSTEM_ERROR;
1917 }
1918 rsa_params.public_exponent = pubExp;
1919 }
1920 }
1921
1922 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1923 } else {
1924 ALOGW("Unsupported key type %d", keyType);
1925 rc = -1;
1926 }
1927
Kenny Root07438c82012-11-02 15:41:02 -07001928 if (rc) {
1929 return ::SYSTEM_ERROR;
1930 }
1931
Kenny Root655b9582013-04-04 08:37:42 -07001932 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07001933 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001934
1935 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1936 free(data);
1937
Kenny Rootee8068b2013-10-07 09:49:15 -07001938 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001939 keyBlob.setFallback(isFallback);
1940
Chad Brubaker9489b792015-04-14 11:01:45 -07001941 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001942 }
1943
Kenny Rootf9119d62013-04-03 09:22:15 -07001944 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1945 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001946 targetUid = getEffectiveUid(targetUid);
1947 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1948 flags & KEYSTORE_FLAG_ENCRYPTED);
1949 if (result != ::NO_ERROR) {
1950 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001951 }
Kenny Root07438c82012-11-02 15:41:02 -07001952 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001953 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001954
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001955 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001956 }
1957
Kenny Root07438c82012-11-02 15:41:02 -07001958 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1959 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001960 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07001961 return ::PERMISSION_DENIED;
1962 }
Kenny Root07438c82012-11-02 15:41:02 -07001963
Chad Brubaker9489b792015-04-14 11:01:45 -07001964 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001965 Blob keyBlob;
1966 String8 name8(name);
1967
Kenny Rootd38a0b02013-02-13 12:59:14 -08001968 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001969
Kenny Root655b9582013-04-04 08:37:42 -07001970 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001971 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001972 if (responseCode != ::NO_ERROR) {
1973 return responseCode;
1974 }
1975
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001976 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07001977 if (device == NULL) {
1978 ALOGE("no keymaster device; cannot sign");
1979 return ::SYSTEM_ERROR;
1980 }
1981
1982 if (device->sign_data == NULL) {
1983 ALOGE("device doesn't implement signing");
1984 return ::SYSTEM_ERROR;
1985 }
1986
1987 keymaster_rsa_sign_params_t params;
1988 params.digest_type = DIGEST_NONE;
1989 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07001990 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001991 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07001992 if (rc) {
1993 ALOGW("device couldn't sign data");
1994 return ::SYSTEM_ERROR;
1995 }
1996
1997 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001998 }
1999
Kenny Root07438c82012-11-02 15:41:02 -07002000 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2001 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002002 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002003 return ::PERMISSION_DENIED;
2004 }
Kenny Root70e3a862012-02-15 17:20:23 -08002005
Chad Brubaker9489b792015-04-14 11:01:45 -07002006 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002007 Blob keyBlob;
2008 String8 name8(name);
2009 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002010
Kenny Root655b9582013-04-04 08:37:42 -07002011 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002012 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002013 if (responseCode != ::NO_ERROR) {
2014 return responseCode;
2015 }
Kenny Root70e3a862012-02-15 17:20:23 -08002016
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002017 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002018 if (device == NULL) {
2019 return ::SYSTEM_ERROR;
2020 }
Kenny Root70e3a862012-02-15 17:20:23 -08002021
Kenny Root07438c82012-11-02 15:41:02 -07002022 if (device->verify_data == NULL) {
2023 return ::SYSTEM_ERROR;
2024 }
Kenny Root70e3a862012-02-15 17:20:23 -08002025
Kenny Root07438c82012-11-02 15:41:02 -07002026 keymaster_rsa_sign_params_t params;
2027 params.digest_type = DIGEST_NONE;
2028 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002029
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002030 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2031 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002032 if (rc) {
2033 return ::SYSTEM_ERROR;
2034 } else {
2035 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002036 }
2037 }
Kenny Root07438c82012-11-02 15:41:02 -07002038
2039 /*
2040 * TODO: The abstraction between things stored in hardware and regular blobs
2041 * of data stored on the filesystem should be moved down to keystore itself.
2042 * Unfortunately the Java code that calls this has naming conventions that it
2043 * knows about. Ideally keystore shouldn't be used to store random blobs of
2044 * data.
2045 *
2046 * Until that happens, it's necessary to have a separate "get_pubkey" and
2047 * "del_key" since the Java code doesn't really communicate what it's
2048 * intentions are.
2049 */
2050 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002051 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002052 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002053 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002054 return ::PERMISSION_DENIED;
2055 }
Kenny Root07438c82012-11-02 15:41:02 -07002056
Kenny Root07438c82012-11-02 15:41:02 -07002057 Blob keyBlob;
2058 String8 name8(name);
2059
Kenny Rootd38a0b02013-02-13 12:59:14 -08002060 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002061
Kenny Root655b9582013-04-04 08:37:42 -07002062 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002063 TYPE_KEY_PAIR);
2064 if (responseCode != ::NO_ERROR) {
2065 return responseCode;
2066 }
2067
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002068 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002069 if (device == NULL) {
2070 return ::SYSTEM_ERROR;
2071 }
2072
2073 if (device->get_keypair_public == NULL) {
2074 ALOGE("device has no get_keypair_public implementation!");
2075 return ::SYSTEM_ERROR;
2076 }
2077
Kenny Root17208e02013-09-04 13:56:03 -07002078 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002079 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2080 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002081 if (rc) {
2082 return ::SYSTEM_ERROR;
2083 }
2084
2085 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002086 }
Kenny Root07438c82012-11-02 15:41:02 -07002087
Kenny Root49468902013-03-19 13:41:33 -07002088 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002089 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002090 }
2091
2092 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002093 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002094 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2095 if (result != ::NO_ERROR) {
2096 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002097 }
2098
2099 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002100 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002101
Kenny Root655b9582013-04-04 08:37:42 -07002102 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002103 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2104 }
2105
Kenny Root655b9582013-04-04 08:37:42 -07002106 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002107 return ::NO_ERROR;
2108 }
2109
2110 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002111 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002112 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2113 if (result != ::NO_ERROR) {
2114 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002115 }
2116
2117 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002118 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002119
Kenny Root655b9582013-04-04 08:37:42 -07002120 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002121 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2122 }
2123
Kenny Root655b9582013-04-04 08:37:42 -07002124 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002125 }
2126
2127 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002128 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002129 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002130 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002131 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002132 }
Kenny Root07438c82012-11-02 15:41:02 -07002133
2134 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002135 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002136
Kenny Root655b9582013-04-04 08:37:42 -07002137 if (access(filename.string(), R_OK) == -1) {
2138 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002139 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002140 }
2141
Kenny Root655b9582013-04-04 08:37:42 -07002142 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002143 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002144 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002145 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002146 }
2147
2148 struct stat s;
2149 int ret = fstat(fd, &s);
2150 close(fd);
2151 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002152 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002153 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002154 }
2155
Kenny Root36a9e232013-02-04 14:24:15 -08002156 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002157 }
2158
Kenny Rootd53bc922013-03-21 14:10:15 -07002159 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2160 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002161 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002162 pid_t spid = IPCThreadState::self()->getCallingPid();
2163 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002164 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002165 return -1L;
2166 }
2167
Kenny Root655b9582013-04-04 08:37:42 -07002168 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002169 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002170 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002171 return state;
2172 }
2173
Kenny Rootd53bc922013-03-21 14:10:15 -07002174 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2175 srcUid = callingUid;
2176 } else if (!is_granted_to(callingUid, srcUid)) {
2177 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002178 return ::PERMISSION_DENIED;
2179 }
2180
Kenny Rootd53bc922013-03-21 14:10:15 -07002181 if (destUid == -1) {
2182 destUid = callingUid;
2183 }
2184
2185 if (srcUid != destUid) {
2186 if (static_cast<uid_t>(srcUid) != callingUid) {
2187 ALOGD("can only duplicate from caller to other or to same uid: "
2188 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2189 return ::PERMISSION_DENIED;
2190 }
2191
2192 if (!is_granted_to(callingUid, destUid)) {
2193 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2194 return ::PERMISSION_DENIED;
2195 }
2196 }
2197
2198 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002199 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002200
Kenny Rootd53bc922013-03-21 14:10:15 -07002201 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002202 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002203
Kenny Root655b9582013-04-04 08:37:42 -07002204 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2205 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002206 return ::SYSTEM_ERROR;
2207 }
2208
Kenny Rootd53bc922013-03-21 14:10:15 -07002209 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002210 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002211 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002212 if (responseCode != ::NO_ERROR) {
2213 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002214 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002215
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002216 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002217 }
2218
Kenny Root1b0e3932013-09-05 13:06:32 -07002219 int32_t is_hardware_backed(const String16& keyType) {
2220 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002221 }
2222
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002223 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002224 uid_t targetUid = getEffectiveUid(targetUid64);
2225 if (!checkBinderPermission(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002226 return ::PERMISSION_DENIED;
2227 }
2228
Robin Lee4b84fdc2014-09-24 11:56:57 +01002229 String8 prefix = String8::format("%u_", targetUid);
2230 Vector<String16> aliases;
2231 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002232 return ::SYSTEM_ERROR;
2233 }
2234
Robin Lee4b84fdc2014-09-24 11:56:57 +01002235 for (uint32_t i = 0; i < aliases.size(); i++) {
2236 String8 name8(aliases[i]);
2237 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2238 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002239 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002240 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002241 }
2242
Robin Lee4b84fdc2014-09-24 11:56:57 +01002243 int32_t reset_uid(int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002244 targetUid = getEffectiveUid(targetUid);
2245 if (!checkBinderPermission(P_RESET_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002246 return ::PERMISSION_DENIED;
2247 }
Chad Brubakerbbc76482015-04-16 15:16:44 -07002248 // Flush the auth token table to prevent stale tokens from sticking
2249 // around.
2250 mAuthTokenTable.Clear();
Robin Lee4e865752014-08-19 17:37:55 +01002251
Robin Lee4b84fdc2014-09-24 11:56:57 +01002252 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002253 }
2254
2255 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002256 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002257 return ::PERMISSION_DENIED;
2258 }
Chad Brubaker9489b792015-04-14 11:01:45 -07002259
Robin Lee4e865752014-08-19 17:37:55 +01002260 if (sourceUid == targetUid) {
2261 return ::SYSTEM_ERROR;
2262 }
2263
2264 // Initialise user keystore with existing master key held in-memory
2265 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2266 }
2267
2268 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002269 targetUid = getEffectiveUid(targetUid);
2270 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002271 return ::PERMISSION_DENIED;
2272 }
Robin Lee4e865752014-08-19 17:37:55 +01002273 const String8 password8(pw);
2274
2275 switch (mKeyStore->getState(targetUid)) {
2276 case ::STATE_UNINITIALIZED: {
2277 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2278 return mKeyStore->initializeUser(password8, targetUid);
2279 }
2280 case ::STATE_NO_ERROR: {
2281 // rewrite master key with new password.
2282 return mKeyStore->writeMasterKey(password8, targetUid);
2283 }
2284 case ::STATE_LOCKED: {
2285 // read master key, decrypt with password, initialize mMasterKey*.
2286 return mKeyStore->readMasterKey(password8, targetUid);
2287 }
2288 }
2289 return ::SYSTEM_ERROR;
2290 }
2291
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002292 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2293 const keymaster1_device_t* device = mKeyStore->getDevice();
2294 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2295 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2296 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2297 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2298 device->add_rng_entropy != NULL) {
2299 devResult = device->add_rng_entropy(device, data, dataLength);
2300 }
2301 if (fallback->add_rng_entropy) {
2302 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2303 }
2304 if (devResult) {
2305 return devResult;
2306 }
2307 if (fallbackResult) {
2308 return fallbackResult;
2309 }
2310 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002311 }
2312
Chad Brubaker17d68b92015-02-05 22:04:16 -08002313 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002314 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2315 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002316 uid = getEffectiveUid(uid);
2317 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2318 flags & KEYSTORE_FLAG_ENCRYPTED);
2319 if (rc != ::NO_ERROR) {
2320 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002321 }
2322
Chad Brubaker9489b792015-04-14 11:01:45 -07002323 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002324 bool isFallback = false;
2325 keymaster_key_blob_t blob;
2326 keymaster_key_characteristics_t *out = NULL;
2327
2328 const keymaster1_device_t* device = mKeyStore->getDevice();
2329 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2330 if (device == NULL) {
2331 return ::SYSTEM_ERROR;
2332 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002333 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002334 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2335 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002336 if (!entropy) {
2337 rc = KM_ERROR_OK;
2338 } else if (device->add_rng_entropy) {
2339 rc = device->add_rng_entropy(device, entropy, entropyLength);
2340 } else {
2341 rc = KM_ERROR_UNIMPLEMENTED;
2342 }
2343 if (rc == KM_ERROR_OK) {
2344 rc = device->generate_key(device, params.params.data(), params.params.size(),
2345 &blob, &out);
2346 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002347 }
2348 // If the HW device didn't support generate_key or generate_key failed
2349 // fall back to the software implementation.
2350 if (rc && fallback->generate_key != NULL) {
2351 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002352 if (!entropy) {
2353 rc = KM_ERROR_OK;
2354 } else if (fallback->add_rng_entropy) {
2355 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2356 } else {
2357 rc = KM_ERROR_UNIMPLEMENTED;
2358 }
2359 if (rc == KM_ERROR_OK) {
2360 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2361 &blob,
2362 &out);
2363 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002364 }
2365
2366 if (out) {
2367 if (outCharacteristics) {
2368 outCharacteristics->characteristics = *out;
2369 } else {
2370 keymaster_free_characteristics(out);
2371 }
2372 free(out);
2373 }
2374
2375 if (rc) {
2376 return rc;
2377 }
2378
2379 String8 name8(name);
2380 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2381
2382 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2383 keyBlob.setFallback(isFallback);
2384 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2385
2386 free(const_cast<uint8_t*>(blob.key_material));
2387
2388 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002389 }
2390
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002391 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002392 const keymaster_blob_t* clientId,
2393 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002394 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002395 if (!outCharacteristics) {
2396 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2397 }
2398
2399 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2400
2401 Blob keyBlob;
2402 String8 name8(name);
2403 int rc;
2404
2405 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2406 TYPE_KEYMASTER_10);
2407 if (responseCode != ::NO_ERROR) {
2408 return responseCode;
2409 }
2410 keymaster_key_blob_t key;
2411 key.key_material_size = keyBlob.getLength();
2412 key.key_material = keyBlob.getValue();
2413 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2414 keymaster_key_characteristics_t *out = NULL;
2415 if (!dev->get_key_characteristics) {
2416 ALOGW("device does not implement get_key_characteristics");
2417 return KM_ERROR_UNIMPLEMENTED;
2418 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002419 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002420 if (out) {
2421 outCharacteristics->characteristics = *out;
2422 free(out);
2423 }
2424 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002425 }
2426
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002427 int32_t importKey(const String16& name, const KeymasterArguments& params,
2428 keymaster_key_format_t format, const uint8_t *keyData,
2429 size_t keyLength, int uid, int flags,
2430 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002431 uid = getEffectiveUid(uid);
2432 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2433 flags & KEYSTORE_FLAG_ENCRYPTED);
2434 if (rc != ::NO_ERROR) {
2435 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002436 }
2437
Chad Brubaker9489b792015-04-14 11:01:45 -07002438 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002439 bool isFallback = false;
2440 keymaster_key_blob_t blob;
2441 keymaster_key_characteristics_t *out = NULL;
2442
2443 const keymaster1_device_t* device = mKeyStore->getDevice();
2444 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2445 if (device == NULL) {
2446 return ::SYSTEM_ERROR;
2447 }
2448 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2449 device->import_key != NULL) {
2450 rc = device->import_key(device, params.params.data(), params.params.size(),
2451 format, keyData, keyLength, &blob, &out);
2452 }
2453 if (rc && fallback->import_key != NULL) {
2454 isFallback = true;
2455 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2456 format, keyData, keyLength, &blob, &out);
2457 }
2458 if (out) {
2459 if (outCharacteristics) {
2460 outCharacteristics->characteristics = *out;
2461 } else {
2462 keymaster_free_characteristics(out);
2463 }
2464 free(out);
2465 }
2466 if (rc) {
2467 return rc;
2468 }
2469
2470 String8 name8(name);
2471 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2472
2473 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2474 keyBlob.setFallback(isFallback);
2475 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2476
2477 free((void*) blob.key_material);
2478
2479 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002480 }
2481
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002482 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002483 const keymaster_blob_t* clientId,
2484 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002485
2486 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2487
2488 Blob keyBlob;
2489 String8 name8(name);
2490 int rc;
2491
2492 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2493 TYPE_KEYMASTER_10);
2494 if (responseCode != ::NO_ERROR) {
2495 result->resultCode = responseCode;
2496 return;
2497 }
2498 keymaster_key_blob_t key;
2499 key.key_material_size = keyBlob.getLength();
2500 key.key_material = keyBlob.getValue();
2501 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2502 if (!dev->export_key) {
2503 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2504 return;
2505 }
2506 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002507 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002508 &ptr, &result->dataLength);
2509 result->exportData.reset(ptr);
2510 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002511 }
2512
Chad Brubakerad6514a2015-04-09 14:00:26 -07002513
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002514 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002515 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2516 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002517 if (!result || !outParams) {
2518 ALOGE("Unexpected null arguments to begin()");
2519 return;
2520 }
2521 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2522 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2523 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2524 result->resultCode = ::PERMISSION_DENIED;
2525 return;
2526 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002527 if (!checkAllowedOperationParams(params.params)) {
2528 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2529 return;
2530 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002531 Blob keyBlob;
2532 String8 name8(name);
2533 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2534 TYPE_KEYMASTER_10);
2535 if (responseCode != ::NO_ERROR) {
2536 result->resultCode = responseCode;
2537 return;
2538 }
2539 keymaster_key_blob_t key;
2540 key.key_material_size = keyBlob.getLength();
2541 key.key_material = keyBlob.getValue();
2542 keymaster_key_param_t* out;
2543 size_t outSize;
2544 keymaster_operation_handle_t handle;
2545 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002546 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002547 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002548 Unique_keymaster_key_characteristics characteristics;
2549 characteristics.reset(new keymaster_key_characteristics_t);
2550 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2551 if (err) {
2552 result->resultCode = err;
2553 return;
2554 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002555 const hw_auth_token_t* authToken = NULL;
2556 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002557 /*failOnTokenMissing*/ false);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002558 // If per-operation auth is needed we need to begin the operation and
2559 // the client will need to authorize that operation before calling
2560 // update. Any other auth issues stop here.
2561 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2562 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002563 return;
2564 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002565 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002566 // Add entropy to the device first.
2567 if (entropy) {
2568 if (dev->add_rng_entropy) {
2569 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2570 } else {
2571 err = KM_ERROR_UNIMPLEMENTED;
2572 }
2573 if (err) {
2574 result->resultCode = err;
2575 return;
2576 }
2577 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002578 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2579 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002580
2581 // If there are too many operations abort the oldest operation that was
2582 // started as pruneable and try again.
2583 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2584 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2585 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2586 if (abort(oldest) != ::NO_ERROR) {
2587 break;
2588 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002589 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002590 &handle);
2591 }
2592 if (err) {
2593 result->resultCode = err;
2594 return;
2595 }
2596 if (out) {
2597 outParams->params.assign(out, out + outSize);
2598 free(out);
2599 }
2600
Chad Brubakerad6514a2015-04-09 14:00:26 -07002601 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2602 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002603 pruneable);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002604 if (authToken) {
2605 mOperationMap.setOperationAuthToken(operationToken, authToken);
2606 }
2607 // Return the authentication lookup result. If this is a per operation
2608 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2609 // application should get an auth token using the handle before the
2610 // first call to update, which will fail if keystore hasn't received the
2611 // auth token.
2612 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002613 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002614 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002615 }
2616
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002617 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2618 size_t dataLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002619 if (!checkAllowedOperationParams(params.params)) {
2620 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2621 return;
2622 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002623 const keymaster1_device_t* dev;
2624 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002625 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002626 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2627 return;
2628 }
2629 uint8_t* output_buf = NULL;
2630 size_t output_length = 0;
2631 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002632 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002633 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2634 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002635 result->resultCode = authResult;
2636 return;
2637 }
2638 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2639 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002640 result->data.reset(output_buf);
2641 result->dataLength = output_length;
2642 result->inputConsumed = consumed;
2643 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002644 }
2645
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002646 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2647 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002648 if (!checkAllowedOperationParams(params.params)) {
2649 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2650 return;
2651 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002652 const keymaster1_device_t* dev;
2653 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002654 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002655 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2656 return;
2657 }
2658 uint8_t* output_buf = NULL;
2659 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002660 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002661 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2662 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002663 result->resultCode = authResult;
2664 return;
2665 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002666
Chad Brubaker06801e02015-03-31 15:13:13 -07002667 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2668 signature, signatureLength, &output_buf,
2669 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002670 // Remove the operation regardless of the result
2671 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002672 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002673 result->data.reset(output_buf);
2674 result->dataLength = output_length;
2675 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002676 }
2677
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002678 int32_t abort(const sp<IBinder>& token) {
2679 const keymaster1_device_t* dev;
2680 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002681 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002682 return KM_ERROR_INVALID_OPERATION_HANDLE;
2683 }
2684 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002685 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002686 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002687 rc = KM_ERROR_UNIMPLEMENTED;
2688 } else {
2689 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002690 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002691 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002692 if (rc) {
2693 return rc;
2694 }
2695 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002696 }
2697
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002698 bool isOperationAuthorized(const sp<IBinder>& token) {
2699 const keymaster1_device_t* dev;
2700 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002701 const keymaster_key_characteristics_t* characteristics;
2702 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002703 return false;
2704 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002705 const hw_auth_token_t* authToken = NULL;
2706 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002707 std::vector<keymaster_key_param_t> ignored;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002708 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2709 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002710 }
2711
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002712 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002713 if (!checkBinderPermission(P_ADD_AUTH)) {
2714 ALOGW("addAuthToken: permission denied for %d",
2715 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002716 return ::PERMISSION_DENIED;
2717 }
2718 if (length != sizeof(hw_auth_token_t)) {
2719 return KM_ERROR_INVALID_ARGUMENT;
2720 }
2721 hw_auth_token_t* authToken = new hw_auth_token_t;
2722 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2723 // The table takes ownership of authToken.
2724 mAuthTokenTable.AddAuthenticationToken(authToken);
2725 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002726 }
2727
Kenny Root07438c82012-11-02 15:41:02 -07002728private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002729 static const int32_t UID_SELF = -1;
2730
2731 /**
2732 * Get the effective target uid for a binder operation that takes an
2733 * optional uid as the target.
2734 */
2735 inline uid_t getEffectiveUid(int32_t targetUid) {
2736 if (targetUid == UID_SELF) {
2737 return IPCThreadState::self()->getCallingUid();
2738 }
2739 return static_cast<uid_t>(targetUid);
2740 }
2741
2742 /**
2743 * Check if the caller of the current binder method has the required
2744 * permission and if acting on other uids the grants to do so.
2745 */
2746 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2747 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2748 pid_t spid = IPCThreadState::self()->getCallingPid();
2749 if (!has_permission(callingUid, permission, spid)) {
2750 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2751 return false;
2752 }
2753 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2754 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2755 return false;
2756 }
2757 return true;
2758 }
2759
2760 /**
2761 * Check if the caller of the current binder method has the required
2762 * permission or the target of the operation is the caller's uid. This is
2763 * for operation where the permission is only for cross-uid activity and all
2764 * uids are allowed to act on their own (ie: clearing all entries for a
2765 * given uid).
2766 */
2767 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2768 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2769 if (getEffectiveUid(targetUid) == callingUid) {
2770 return true;
2771 } else {
2772 return checkBinderPermission(permission, targetUid);
2773 }
2774 }
2775
2776 /**
2777 * Helper method to check that the caller has the required permission as
2778 * well as the keystore is in the unlocked state if checkUnlocked is true.
2779 *
2780 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2781 * otherwise the state of keystore when not unlocked and checkUnlocked is
2782 * true.
2783 */
2784 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2785 bool checkUnlocked = true) {
2786 if (!checkBinderPermission(permission, targetUid)) {
2787 return ::PERMISSION_DENIED;
2788 }
2789 State state = mKeyStore->getState(getEffectiveUid(targetUid));
2790 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2791 return state;
2792 }
2793
2794 return ::NO_ERROR;
2795
2796 }
2797
Kenny Root9d45d1c2013-02-14 10:32:30 -08002798 inline bool isKeystoreUnlocked(State state) {
2799 switch (state) {
2800 case ::STATE_NO_ERROR:
2801 return true;
2802 case ::STATE_UNINITIALIZED:
2803 case ::STATE_LOCKED:
2804 return false;
2805 }
2806 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002807 }
2808
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002809 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002810 const int32_t device_api = device->common.module->module_api_version;
2811 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2812 switch (keyType) {
2813 case TYPE_RSA:
2814 case TYPE_DSA:
2815 case TYPE_EC:
2816 return true;
2817 default:
2818 return false;
2819 }
2820 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2821 switch (keyType) {
2822 case TYPE_RSA:
2823 return true;
2824 case TYPE_DSA:
2825 return device->flags & KEYMASTER_SUPPORTS_DSA;
2826 case TYPE_EC:
2827 return device->flags & KEYMASTER_SUPPORTS_EC;
2828 default:
2829 return false;
2830 }
2831 } else {
2832 return keyType == TYPE_RSA;
2833 }
2834 }
2835
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002836 /**
2837 * Check that all keymaster_key_param_t's provided by the application are
2838 * allowed. Any parameter that keystore adds itself should be disallowed here.
2839 */
2840 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2841 for (auto param: params) {
2842 switch (param.tag) {
2843 case KM_TAG_AUTH_TOKEN:
2844 return false;
2845 default:
2846 break;
2847 }
2848 }
2849 return true;
2850 }
2851
2852 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2853 const keymaster1_device_t* dev,
2854 const std::vector<keymaster_key_param_t>& params,
2855 keymaster_key_characteristics_t* out) {
2856 UniquePtr<keymaster_blob_t> appId;
2857 UniquePtr<keymaster_blob_t> appData;
2858 for (auto param : params) {
2859 if (param.tag == KM_TAG_APPLICATION_ID) {
2860 appId.reset(new keymaster_blob_t);
2861 appId->data = param.blob.data;
2862 appId->data_length = param.blob.data_length;
2863 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2864 appData.reset(new keymaster_blob_t);
2865 appData->data = param.blob.data;
2866 appData->data_length = param.blob.data_length;
2867 }
2868 }
2869 keymaster_key_characteristics_t* result = NULL;
2870 if (!dev->get_key_characteristics) {
2871 return KM_ERROR_UNIMPLEMENTED;
2872 }
2873 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2874 appData.get(), &result);
2875 if (result) {
2876 *out = *result;
2877 free(result);
2878 }
2879 return error;
2880 }
2881
2882 /**
2883 * Get the auth token for this operation from the auth token table.
2884 *
2885 * Returns ::NO_ERROR if the auth token was set or none was required.
2886 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2887 * authorization token exists for that operation and
2888 * failOnTokenMissing is false.
2889 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2890 * token for the operation
2891 */
2892 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2893 keymaster_operation_handle_t handle,
2894 const hw_auth_token_t** authToken,
2895 bool failOnTokenMissing = true) {
2896
2897 std::vector<keymaster_key_param_t> allCharacteristics;
2898 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2899 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2900 }
2901 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2902 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2903 }
2904 keymaster::AuthTokenTable::Error err =
2905 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2906 allCharacteristics.size(), handle, authToken);
2907 switch (err) {
2908 case keymaster::AuthTokenTable::OK:
2909 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2910 return ::NO_ERROR;
2911 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2912 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2913 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2914 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2915 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2916 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2917 (int32_t) ::OP_AUTH_NEEDED;
2918 default:
2919 ALOGE("Unexpected FindAuthorization return value %d", err);
2920 return KM_ERROR_INVALID_ARGUMENT;
2921 }
2922 }
2923
2924 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2925 const hw_auth_token_t* token) {
2926 if (token) {
2927 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2928 reinterpret_cast<const uint8_t*>(token),
2929 sizeof(hw_auth_token_t)));
2930 }
2931 }
2932
2933 /**
2934 * Add the auth token for the operation to the param list if the operation
2935 * requires authorization. Uses the cached result in the OperationMap if available
2936 * otherwise gets the token from the AuthTokenTable and caches the result.
2937 *
2938 * Returns ::NO_ERROR if the auth token was added or not needed.
2939 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2940 * authenticated.
2941 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2942 * operation token.
2943 */
2944 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2945 std::vector<keymaster_key_param_t>* params) {
2946 const hw_auth_token_t* authToken = NULL;
2947 bool authTokenNeeded = !mOperationMap.getOperationAuthToken(token, &authToken);
2948 if (authTokenNeeded) {
2949 const keymaster1_device_t* dev;
2950 keymaster_operation_handle_t handle;
2951 const keymaster_key_characteristics_t* characteristics = NULL;
2952 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
2953 return KM_ERROR_INVALID_OPERATION_HANDLE;
2954 }
2955 int32_t result = getAuthToken(characteristics, handle, &authToken);
2956 if (result != ::NO_ERROR) {
2957 return result;
2958 }
2959 if (authToken) {
2960 mOperationMap.setOperationAuthToken(token, authToken);
2961 }
2962 }
2963 addAuthToParams(params, authToken);
2964 return ::NO_ERROR;
2965 }
2966
Kenny Root07438c82012-11-02 15:41:02 -07002967 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002968 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002969 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07002970};
2971
2972}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002973
2974int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002975 if (argc < 2) {
2976 ALOGE("A directory must be specified!");
2977 return 1;
2978 }
2979 if (chdir(argv[1]) == -1) {
2980 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2981 return 1;
2982 }
2983
2984 Entropy entropy;
2985 if (!entropy.open()) {
2986 return 1;
2987 }
Kenny Root70e3a862012-02-15 17:20:23 -08002988
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002989 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002990 if (keymaster_device_initialize(&dev)) {
2991 ALOGE("keystore keymaster could not be initialized; exiting");
2992 return 1;
2993 }
2994
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002995 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002996 if (fallback_keymaster_device_initialize(&fallback)) {
2997 ALOGE("software keymaster could not be initialized; exiting");
2998 return 1;
2999 }
3000
Riley Spahneaabae92014-06-30 12:39:52 -07003001 ks_is_selinux_enabled = is_selinux_enabled();
3002 if (ks_is_selinux_enabled) {
3003 union selinux_callback cb;
3004 cb.func_log = selinux_log_callback;
3005 selinux_set_callback(SELINUX_CB_LOG, cb);
3006 if (getcon(&tctx) != 0) {
3007 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3008 return -1;
3009 }
3010 } else {
3011 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3012 }
3013
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003014 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003015 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003016 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3017 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3018 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3019 if (ret != android::OK) {
3020 ALOGE("Couldn't register binder service!");
3021 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003022 }
Kenny Root07438c82012-11-02 15:41:02 -07003023
3024 /*
3025 * We're the only thread in existence, so we're just going to process
3026 * Binder transaction as a single-threaded program.
3027 */
3028 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003029
3030 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003031 return 1;
3032}