blob: 24c137aae920cc3bdba9ed96f32c98ab95fd05bb [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Kenny Root17208e02013-09-04 13:56:03 -070046#include <keymaster/softkeymaster.h>
Chad Brubaker67d2a502015-03-11 17:21:18 +000047#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 Willden80843db2015-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 Willden80843db2015-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 Brubaker67d2a502015-03-11 17:21:18 +0000132static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
133 keymaster::SoftKeymasterDevice* softkeymaster =
134 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600135 *dev = softkeymaster->keymaster_device();
136 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800137 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800138}
139
Shawn Willden80843db2015-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) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800498 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800499 mBlob.length = valueLength;
500 memcpy(mBlob.value, value, valueLength);
501
502 mBlob.info = infoLength;
503 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700504
Kenny Root07438c82012-11-02 15:41:02 -0700505 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700506 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700507
Kenny Rootee8068b2013-10-07 09:49:15 -0700508 if (type == TYPE_MASTER_KEY) {
509 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
510 } else {
511 mBlob.flags = KEYSTORE_FLAG_NONE;
512 }
Kenny Roota91203b2012-02-15 15:00:46 -0800513 }
514
515 Blob(blob b) {
516 mBlob = b;
517 }
518
Alex Klyubin1773b442015-02-20 12:33:33 -0800519 Blob() {
520 memset(&mBlob, 0, sizeof(mBlob));
521 }
Kenny Roota91203b2012-02-15 15:00:46 -0800522
Kenny Root51878182012-03-13 12:53:19 -0700523 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800524 return mBlob.value;
525 }
526
Kenny Root51878182012-03-13 12:53:19 -0700527 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800528 return mBlob.length;
529 }
530
Kenny Root51878182012-03-13 12:53:19 -0700531 const uint8_t* getInfo() const {
532 return mBlob.value + mBlob.length;
533 }
534
535 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800536 return mBlob.info;
537 }
538
Kenny Root822c3a92012-03-23 16:34:39 -0700539 uint8_t getVersion() const {
540 return mBlob.version;
541 }
542
Kenny Rootf9119d62013-04-03 09:22:15 -0700543 bool isEncrypted() const {
544 if (mBlob.version < 2) {
545 return true;
546 }
547
548 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
549 }
550
551 void setEncrypted(bool encrypted) {
552 if (encrypted) {
553 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
554 } else {
555 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
556 }
557 }
558
Kenny Root17208e02013-09-04 13:56:03 -0700559 bool isFallback() const {
560 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
561 }
562
563 void setFallback(bool fallback) {
564 if (fallback) {
565 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
566 } else {
567 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
568 }
569 }
570
Kenny Root822c3a92012-03-23 16:34:39 -0700571 void setVersion(uint8_t version) {
572 mBlob.version = version;
573 }
574
575 BlobType getType() const {
576 return BlobType(mBlob.type);
577 }
578
579 void setType(BlobType type) {
580 mBlob.type = uint8_t(type);
581 }
582
Kenny Rootf9119d62013-04-03 09:22:15 -0700583 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
584 ALOGV("writing blob %s", filename);
585 if (isEncrypted()) {
586 if (state != STATE_NO_ERROR) {
587 ALOGD("couldn't insert encrypted blob while not unlocked");
588 return LOCKED;
589 }
590
591 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
592 ALOGW("Could not read random data for: %s", filename);
593 return SYSTEM_ERROR;
594 }
Kenny Roota91203b2012-02-15 15:00:46 -0800595 }
596
597 // data includes the value and the value's length
598 size_t dataLength = mBlob.length + sizeof(mBlob.length);
599 // pad data to the AES_BLOCK_SIZE
600 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
601 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
602 // encrypted data includes the digest value
603 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
604 // move info after space for padding
605 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
606 // zero padding area
607 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
608
609 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800610
Kenny Rootf9119d62013-04-03 09:22:15 -0700611 if (isEncrypted()) {
612 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800613
Kenny Rootf9119d62013-04-03 09:22:15 -0700614 uint8_t vector[AES_BLOCK_SIZE];
615 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
616 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
617 aes_key, vector, AES_ENCRYPT);
618 }
619
Kenny Roota91203b2012-02-15 15:00:46 -0800620 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
621 size_t fileLength = encryptedLength + headerLength + mBlob.info;
622
623 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800624 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
625 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
626 if (out < 0) {
627 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800628 return SYSTEM_ERROR;
629 }
630 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
631 if (close(out) != 0) {
632 return SYSTEM_ERROR;
633 }
634 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800635 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800636 unlink(tmpFileName);
637 return SYSTEM_ERROR;
638 }
Kenny Root150ca932012-11-14 14:29:02 -0800639 if (rename(tmpFileName, filename) == -1) {
640 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
641 return SYSTEM_ERROR;
642 }
643 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800644 }
645
Kenny Rootf9119d62013-04-03 09:22:15 -0700646 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
647 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800648 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
649 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800650 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
651 }
652 // fileLength may be less than sizeof(mBlob) since the in
653 // memory version has extra padding to tolerate rounding up to
654 // the AES_BLOCK_SIZE
655 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
656 if (close(in) != 0) {
657 return SYSTEM_ERROR;
658 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700659
660 if (isEncrypted() && (state != STATE_NO_ERROR)) {
661 return LOCKED;
662 }
663
Kenny Roota91203b2012-02-15 15:00:46 -0800664 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
665 if (fileLength < headerLength) {
666 return VALUE_CORRUPTED;
667 }
668
669 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700670 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800671 return VALUE_CORRUPTED;
672 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700673
674 ssize_t digestedLength;
675 if (isEncrypted()) {
676 if (encryptedLength % AES_BLOCK_SIZE != 0) {
677 return VALUE_CORRUPTED;
678 }
679
680 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
681 mBlob.vector, AES_DECRYPT);
682 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
683 uint8_t computedDigest[MD5_DIGEST_LENGTH];
684 MD5(mBlob.digested, digestedLength, computedDigest);
685 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
686 return VALUE_CORRUPTED;
687 }
688 } else {
689 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800690 }
691
692 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
693 mBlob.length = ntohl(mBlob.length);
694 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
695 return VALUE_CORRUPTED;
696 }
697 if (mBlob.info != 0) {
698 // move info from after padding to after data
699 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
700 }
Kenny Root07438c82012-11-02 15:41:02 -0700701 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800702 }
703
704private:
705 struct blob mBlob;
706};
707
Kenny Root655b9582013-04-04 08:37:42 -0700708class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800709public:
Kenny Root655b9582013-04-04 08:37:42 -0700710 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
711 asprintf(&mUserDir, "user_%u", mUserId);
712 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
713 }
714
715 ~UserState() {
716 free(mUserDir);
717 free(mMasterKeyFile);
718 }
719
720 bool initialize() {
721 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
722 ALOGE("Could not create directory '%s'", mUserDir);
723 return false;
724 }
725
726 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800727 setState(STATE_LOCKED);
728 } else {
729 setState(STATE_UNINITIALIZED);
730 }
Kenny Root70e3a862012-02-15 17:20:23 -0800731
Kenny Root655b9582013-04-04 08:37:42 -0700732 return true;
733 }
734
735 uid_t getUserId() const {
736 return mUserId;
737 }
738
739 const char* getUserDirName() const {
740 return mUserDir;
741 }
742
743 const char* getMasterKeyFileName() const {
744 return mMasterKeyFile;
745 }
746
747 void setState(State state) {
748 mState = state;
749 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
750 mRetry = MAX_RETRY;
751 }
Kenny Roota91203b2012-02-15 15:00:46 -0800752 }
753
Kenny Root51878182012-03-13 12:53:19 -0700754 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800755 return mState;
756 }
757
Kenny Root51878182012-03-13 12:53:19 -0700758 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800759 return mRetry;
760 }
761
Kenny Root655b9582013-04-04 08:37:42 -0700762 void zeroizeMasterKeysInMemory() {
763 memset(mMasterKey, 0, sizeof(mMasterKey));
764 memset(mSalt, 0, sizeof(mSalt));
765 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
766 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800767 }
768
Kenny Root655b9582013-04-04 08:37:42 -0700769 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
770 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800771 return SYSTEM_ERROR;
772 }
Kenny Root655b9582013-04-04 08:37:42 -0700773 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800774 if (response != NO_ERROR) {
775 return response;
776 }
777 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700778 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800779 }
780
Robin Lee4e865752014-08-19 17:37:55 +0100781 ResponseCode copyMasterKey(UserState* src) {
782 if (mState != STATE_UNINITIALIZED) {
783 return ::SYSTEM_ERROR;
784 }
785 if (src->getState() != STATE_NO_ERROR) {
786 return ::SYSTEM_ERROR;
787 }
788 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
789 setupMasterKeys();
790 return ::NO_ERROR;
791 }
792
Kenny Root655b9582013-04-04 08:37:42 -0700793 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800794 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
795 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
796 AES_KEY passwordAesKey;
797 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700798 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700799 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800800 }
801
Kenny Root655b9582013-04-04 08:37:42 -0700802 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
803 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800804 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800805 return SYSTEM_ERROR;
806 }
807
808 // we read the raw blob to just to get the salt to generate
809 // the AES key, then we create the Blob to use with decryptBlob
810 blob rawBlob;
811 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
812 if (close(in) != 0) {
813 return SYSTEM_ERROR;
814 }
815 // find salt at EOF if present, otherwise we have an old file
816 uint8_t* salt;
817 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
818 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
819 } else {
820 salt = NULL;
821 }
822 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
823 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
824 AES_KEY passwordAesKey;
825 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
826 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700827 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
828 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800829 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700830 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800831 }
832 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
833 // if salt was missing, generate one and write a new master key file with the salt.
834 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700835 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800836 return SYSTEM_ERROR;
837 }
Kenny Root655b9582013-04-04 08:37:42 -0700838 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800839 }
840 if (response == NO_ERROR) {
841 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
842 setupMasterKeys();
843 }
844 return response;
845 }
846 if (mRetry <= 0) {
847 reset();
848 return UNINITIALIZED;
849 }
850 --mRetry;
851 switch (mRetry) {
852 case 0: return WRONG_PASSWORD_0;
853 case 1: return WRONG_PASSWORD_1;
854 case 2: return WRONG_PASSWORD_2;
855 case 3: return WRONG_PASSWORD_3;
856 default: return WRONG_PASSWORD_3;
857 }
858 }
859
Kenny Root655b9582013-04-04 08:37:42 -0700860 AES_KEY* getEncryptionKey() {
861 return &mMasterKeyEncryption;
862 }
863
864 AES_KEY* getDecryptionKey() {
865 return &mMasterKeyDecryption;
866 }
867
Kenny Roota91203b2012-02-15 15:00:46 -0800868 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700869 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800870 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700871 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800872 return false;
873 }
Kenny Root655b9582013-04-04 08:37:42 -0700874
875 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800876 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700877 // We only care about files.
878 if (file->d_type != DT_REG) {
879 continue;
880 }
881
882 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700883 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700884 continue;
885 }
886
887 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800888 }
889 closedir(dir);
890 return true;
891 }
892
Kenny Root655b9582013-04-04 08:37:42 -0700893private:
894 static const int MASTER_KEY_SIZE_BYTES = 16;
895 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
896
897 static const int MAX_RETRY = 4;
898 static const size_t SALT_SIZE = 16;
899
900 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
901 uint8_t* salt) {
902 size_t saltSize;
903 if (salt != NULL) {
904 saltSize = SALT_SIZE;
905 } else {
906 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
907 salt = (uint8_t*) "keystore";
908 // sizeof = 9, not strlen = 8
909 saltSize = sizeof("keystore");
910 }
911
912 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
913 saltSize, 8192, keySize, key);
914 }
915
916 bool generateSalt(Entropy* entropy) {
917 return entropy->generate_random_data(mSalt, sizeof(mSalt));
918 }
919
920 bool generateMasterKey(Entropy* entropy) {
921 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
922 return false;
923 }
924 if (!generateSalt(entropy)) {
925 return false;
926 }
927 return true;
928 }
929
930 void setupMasterKeys() {
931 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
932 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
933 setState(STATE_NO_ERROR);
934 }
935
936 uid_t mUserId;
937
938 char* mUserDir;
939 char* mMasterKeyFile;
940
941 State mState;
942 int8_t mRetry;
943
944 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
945 uint8_t mSalt[SALT_SIZE];
946
947 AES_KEY mMasterKeyEncryption;
948 AES_KEY mMasterKeyDecryption;
949};
950
951typedef struct {
952 uint32_t uid;
953 const uint8_t* filename;
954} grant_t;
955
956class KeyStore {
957public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000958 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700959 : mEntropy(entropy)
960 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800961 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700962 {
963 memset(&mMetaData, '\0', sizeof(mMetaData));
964 }
965
966 ~KeyStore() {
967 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
968 it != mGrants.end(); it++) {
969 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700970 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800971 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700972
973 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
974 it != mMasterKeys.end(); it++) {
975 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700976 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800977 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700978 }
979
Chad Brubaker67d2a502015-03-11 17:21:18 +0000980 /**
981 * Depending on the hardware keymaster version is this may return a
982 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
983 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
984 * be guarded by a check on the device's version.
985 */
986 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700987 return mDevice;
988 }
989
Chad Brubaker67d2a502015-03-11 17:21:18 +0000990 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800991 return mFallbackDevice;
992 }
993
Chad Brubaker67d2a502015-03-11 17:21:18 +0000994 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800995 return blob.isFallback() ? mFallbackDevice: mDevice;
996 }
997
Kenny Root655b9582013-04-04 08:37:42 -0700998 ResponseCode initialize() {
999 readMetaData();
1000 if (upgradeKeystore()) {
1001 writeMetaData();
1002 }
1003
1004 return ::NO_ERROR;
1005 }
1006
1007 State getState(uid_t uid) {
1008 return getUserState(uid)->getState();
1009 }
1010
1011 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1012 UserState* userState = getUserState(uid);
1013 return userState->initialize(pw, mEntropy);
1014 }
1015
Robin Lee4e865752014-08-19 17:37:55 +01001016 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1017 UserState *userState = getUserState(uid);
1018 UserState *initState = getUserState(src);
1019 return userState->copyMasterKey(initState);
1020 }
1021
Kenny Root655b9582013-04-04 08:37:42 -07001022 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001023 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001024 return userState->writeMasterKey(pw, mEntropy);
1025 }
1026
1027 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001028 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001029 return userState->readMasterKey(pw, mEntropy);
1030 }
1031
1032 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001033 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001034 encode_key(encoded, keyName);
1035 return android::String8(encoded);
1036 }
1037
1038 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001039 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001040 encode_key(encoded, keyName);
1041 return android::String8::format("%u_%s", uid, encoded);
1042 }
1043
1044 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001045 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001046 encode_key(encoded, keyName);
1047 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1048 encoded);
1049 }
1050
1051 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001052 android::String8 prefix("");
1053 android::Vector<android::String16> aliases;
1054 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1055 return ::SYSTEM_ERROR;
1056 }
1057
Kenny Root655b9582013-04-04 08:37:42 -07001058 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001059 for (uint32_t i = 0; i < aliases.size(); i++) {
1060 android::String8 filename(aliases[i]);
1061 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1062 getKeyName(filename).string());
1063 del(filename, ::TYPE_ANY, uid);
1064 }
1065
Kenny Root655b9582013-04-04 08:37:42 -07001066 userState->zeroizeMasterKeysInMemory();
1067 userState->setState(STATE_UNINITIALIZED);
1068 return userState->reset();
1069 }
1070
1071 bool isEmpty(uid_t uid) const {
1072 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001073 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001074 return true;
1075 }
1076
1077 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001078 if (!dir) {
1079 return true;
1080 }
Kenny Root31e27462014-09-10 11:28:03 -07001081
Kenny Roota91203b2012-02-15 15:00:46 -08001082 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001083 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001084 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001085 // We only care about files.
1086 if (file->d_type != DT_REG) {
1087 continue;
1088 }
1089
1090 // Skip anything that starts with a "."
1091 if (file->d_name[0] == '.') {
1092 continue;
1093 }
1094
Kenny Root31e27462014-09-10 11:28:03 -07001095 result = false;
1096 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001097 }
1098 closedir(dir);
1099 return result;
1100 }
1101
Kenny Root655b9582013-04-04 08:37:42 -07001102 void lock(uid_t uid) {
1103 UserState* userState = getUserState(uid);
1104 userState->zeroizeMasterKeysInMemory();
1105 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001106 }
1107
Kenny Root655b9582013-04-04 08:37:42 -07001108 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1109 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001110 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1111 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001112 if (rc != NO_ERROR) {
1113 return rc;
1114 }
1115
1116 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001117 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001118 /* If we upgrade the key, we need to write it to disk again. Then
1119 * it must be read it again since the blob is encrypted each time
1120 * it's written.
1121 */
Kenny Root655b9582013-04-04 08:37:42 -07001122 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1123 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001124 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1125 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001126 return rc;
1127 }
1128 }
Kenny Root822c3a92012-03-23 16:34:39 -07001129 }
1130
Kenny Root17208e02013-09-04 13:56:03 -07001131 /*
1132 * This will upgrade software-backed keys to hardware-backed keys when
1133 * the HAL for the device supports the newer key types.
1134 */
1135 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1136 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1137 && keyBlob->isFallback()) {
1138 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1139 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1140
1141 // The HAL allowed the import, reget the key to have the "fresh"
1142 // version.
1143 if (imported == NO_ERROR) {
1144 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1145 }
1146 }
1147
Kenny Rootd53bc922013-03-21 14:10:15 -07001148 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001149 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1150 return KEY_NOT_FOUND;
1151 }
1152
1153 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001154 }
1155
Kenny Root655b9582013-04-04 08:37:42 -07001156 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1157 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001158 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1159 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001160 }
1161
Robin Lee4b84fdc2014-09-24 11:56:57 +01001162 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1163 Blob keyBlob;
1164 ResponseCode rc = get(filename, &keyBlob, type, uid);
1165 if (rc != ::NO_ERROR) {
1166 return rc;
1167 }
1168
1169 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1170 // A device doesn't have to implement delete_keypair.
1171 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1172 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1173 rc = ::SYSTEM_ERROR;
1174 }
1175 }
1176 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001177 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1178 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1179 if (dev->delete_key) {
1180 keymaster_key_blob_t blob;
1181 blob.key_material = keyBlob.getValue();
1182 blob.key_material_size = keyBlob.getLength();
1183 dev->delete_key(dev, &blob);
1184 }
1185 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001186 if (rc != ::NO_ERROR) {
1187 return rc;
1188 }
1189
1190 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1191 }
1192
1193 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1194 uid_t uid) {
1195
1196 UserState* userState = getUserState(uid);
1197 size_t n = prefix.length();
1198
1199 DIR* dir = opendir(userState->getUserDirName());
1200 if (!dir) {
1201 ALOGW("can't open directory for user: %s", strerror(errno));
1202 return ::SYSTEM_ERROR;
1203 }
1204
1205 struct dirent* file;
1206 while ((file = readdir(dir)) != NULL) {
1207 // We only care about files.
1208 if (file->d_type != DT_REG) {
1209 continue;
1210 }
1211
1212 // Skip anything that starts with a "."
1213 if (file->d_name[0] == '.') {
1214 continue;
1215 }
1216
1217 if (!strncmp(prefix.string(), file->d_name, n)) {
1218 const char* p = &file->d_name[n];
1219 size_t plen = strlen(p);
1220
1221 size_t extra = decode_key_length(p, plen);
1222 char *match = (char*) malloc(extra + 1);
1223 if (match != NULL) {
1224 decode_key(match, p, plen);
1225 matches->push(android::String16(match, extra));
1226 free(match);
1227 } else {
1228 ALOGW("could not allocate match of size %zd", extra);
1229 }
1230 }
1231 }
1232 closedir(dir);
1233 return ::NO_ERROR;
1234 }
1235
Kenny Root07438c82012-11-02 15:41:02 -07001236 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001237 const grant_t* existing = getGrant(filename, granteeUid);
1238 if (existing == NULL) {
1239 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001240 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001241 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001242 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001243 }
1244 }
1245
Kenny Root07438c82012-11-02 15:41:02 -07001246 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001247 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1248 it != mGrants.end(); it++) {
1249 grant_t* grant = *it;
1250 if (grant->uid == granteeUid
1251 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1252 mGrants.erase(it);
1253 return true;
1254 }
Kenny Root70e3a862012-02-15 17:20:23 -08001255 }
Kenny Root70e3a862012-02-15 17:20:23 -08001256 return false;
1257 }
1258
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001259 bool hasGrant(const char* filename, const uid_t uid) const {
1260 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001261 }
1262
Kenny Rootf9119d62013-04-03 09:22:15 -07001263 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1264 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001265 uint8_t* data;
1266 size_t dataLength;
1267 int rc;
1268
1269 if (mDevice->import_keypair == NULL) {
1270 ALOGE("Keymaster doesn't support import!");
1271 return SYSTEM_ERROR;
1272 }
1273
Kenny Root17208e02013-09-04 13:56:03 -07001274 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001275 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001276 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001277 /*
1278 * Maybe the device doesn't support this type of key. Try to use the
1279 * software fallback keymaster implementation. This is a little bit
1280 * lazier than checking the PKCS#8 key type, but the software
1281 * implementation will do that anyway.
1282 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001283 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001284 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001285
1286 if (rc) {
1287 ALOGE("Error while importing keypair: %d", rc);
1288 return SYSTEM_ERROR;
1289 }
Kenny Root822c3a92012-03-23 16:34:39 -07001290 }
1291
1292 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1293 free(data);
1294
Kenny Rootf9119d62013-04-03 09:22:15 -07001295 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001296 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001297
Kenny Root655b9582013-04-04 08:37:42 -07001298 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001299 }
1300
Kenny Root1b0e3932013-09-05 13:06:32 -07001301 bool isHardwareBacked(const android::String16& keyType) const {
1302 if (mDevice == NULL) {
1303 ALOGW("can't get keymaster device");
1304 return false;
1305 }
1306
1307 if (sRSAKeyType == keyType) {
1308 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1309 } else {
1310 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1311 && (mDevice->common.module->module_api_version
1312 >= KEYMASTER_MODULE_API_VERSION_0_2);
1313 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001314 }
1315
Kenny Root655b9582013-04-04 08:37:42 -07001316 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1317 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001318 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001319
1320 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1321 if (responseCode == NO_ERROR) {
1322 return responseCode;
1323 }
1324
1325 // If this is one of the legacy UID->UID mappings, use it.
1326 uid_t euid = get_keystore_euid(uid);
1327 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001328 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001329 responseCode = get(filepath8.string(), keyBlob, type, uid);
1330 if (responseCode == NO_ERROR) {
1331 return responseCode;
1332 }
1333 }
1334
1335 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001336 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001337 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001338 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001339 if (end[0] != '_' || end[1] == 0) {
1340 return KEY_NOT_FOUND;
1341 }
Kenny Root86b16e82013-09-09 11:15:54 -07001342 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1343 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001344 if (!hasGrant(filepath8.string(), uid)) {
1345 return responseCode;
1346 }
1347
1348 // It is a granted key. Try to load it.
1349 return get(filepath8.string(), keyBlob, type, uid);
1350 }
1351
1352 /**
1353 * Returns any existing UserState or creates it if it doesn't exist.
1354 */
1355 UserState* getUserState(uid_t uid) {
1356 uid_t userId = get_user_id(uid);
1357
1358 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1359 it != mMasterKeys.end(); it++) {
1360 UserState* state = *it;
1361 if (state->getUserId() == userId) {
1362 return state;
1363 }
1364 }
1365
1366 UserState* userState = new UserState(userId);
1367 if (!userState->initialize()) {
1368 /* There's not much we can do if initialization fails. Trying to
1369 * unlock the keystore for that user will fail as well, so any
1370 * subsequent request for this user will just return SYSTEM_ERROR.
1371 */
1372 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1373 }
1374 mMasterKeys.add(userState);
1375 return userState;
1376 }
1377
1378 /**
1379 * Returns NULL if the UserState doesn't already exist.
1380 */
1381 const UserState* getUserState(uid_t uid) const {
1382 uid_t userId = get_user_id(uid);
1383
1384 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1385 it != mMasterKeys.end(); it++) {
1386 UserState* state = *it;
1387 if (state->getUserId() == userId) {
1388 return state;
1389 }
1390 }
1391
1392 return NULL;
1393 }
1394
Kenny Roota91203b2012-02-15 15:00:46 -08001395private:
Kenny Root655b9582013-04-04 08:37:42 -07001396 static const char* sOldMasterKey;
1397 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001398 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001399 Entropy* mEntropy;
1400
Chad Brubaker67d2a502015-03-11 17:21:18 +00001401 keymaster1_device_t* mDevice;
1402 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001403
Kenny Root655b9582013-04-04 08:37:42 -07001404 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001405
Kenny Root655b9582013-04-04 08:37:42 -07001406 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001407
Kenny Root655b9582013-04-04 08:37:42 -07001408 typedef struct {
1409 uint32_t version;
1410 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001411
Kenny Root655b9582013-04-04 08:37:42 -07001412 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001413
Kenny Root655b9582013-04-04 08:37:42 -07001414 const grant_t* getGrant(const char* filename, uid_t uid) const {
1415 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1416 it != mGrants.end(); it++) {
1417 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001418 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001419 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001420 return grant;
1421 }
1422 }
Kenny Root70e3a862012-02-15 17:20:23 -08001423 return NULL;
1424 }
1425
Kenny Root822c3a92012-03-23 16:34:39 -07001426 /**
1427 * Upgrade code. This will upgrade the key from the current version
1428 * to whatever is newest.
1429 */
Kenny Root655b9582013-04-04 08:37:42 -07001430 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1431 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001432 bool updated = false;
1433 uint8_t version = oldVersion;
1434
1435 /* From V0 -> V1: All old types were unknown */
1436 if (version == 0) {
1437 ALOGV("upgrading to version 1 and setting type %d", type);
1438
1439 blob->setType(type);
1440 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001441 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001442 }
1443 version = 1;
1444 updated = true;
1445 }
1446
Kenny Rootf9119d62013-04-03 09:22:15 -07001447 /* From V1 -> V2: All old keys were encrypted */
1448 if (version == 1) {
1449 ALOGV("upgrading to version 2");
1450
1451 blob->setEncrypted(true);
1452 version = 2;
1453 updated = true;
1454 }
1455
Kenny Root822c3a92012-03-23 16:34:39 -07001456 /*
1457 * If we've updated, set the key blob to the right version
1458 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001459 */
Kenny Root822c3a92012-03-23 16:34:39 -07001460 if (updated) {
1461 ALOGV("updated and writing file %s", filename);
1462 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001463 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001464
1465 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001466 }
1467
1468 /**
1469 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1470 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1471 * Then it overwrites the original blob with the new blob
1472 * format that is returned from the keymaster.
1473 */
Kenny Root655b9582013-04-04 08:37:42 -07001474 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001475 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1476 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1477 if (b.get() == NULL) {
1478 ALOGE("Problem instantiating BIO");
1479 return SYSTEM_ERROR;
1480 }
1481
1482 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1483 if (pkey.get() == NULL) {
1484 ALOGE("Couldn't read old PEM file");
1485 return SYSTEM_ERROR;
1486 }
1487
1488 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1489 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1490 if (len < 0) {
1491 ALOGE("Couldn't measure PKCS#8 length");
1492 return SYSTEM_ERROR;
1493 }
1494
Kenny Root70c98892013-02-07 09:10:36 -08001495 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1496 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001497 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1498 ALOGE("Couldn't convert to PKCS#8");
1499 return SYSTEM_ERROR;
1500 }
1501
Kenny Rootf9119d62013-04-03 09:22:15 -07001502 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1503 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001504 if (rc != NO_ERROR) {
1505 return rc;
1506 }
1507
Kenny Root655b9582013-04-04 08:37:42 -07001508 return get(filename, blob, TYPE_KEY_PAIR, uid);
1509 }
1510
1511 void readMetaData() {
1512 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1513 if (in < 0) {
1514 return;
1515 }
1516 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1517 if (fileLength != sizeof(mMetaData)) {
1518 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1519 sizeof(mMetaData));
1520 }
1521 close(in);
1522 }
1523
1524 void writeMetaData() {
1525 const char* tmpFileName = ".metadata.tmp";
1526 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1527 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1528 if (out < 0) {
1529 ALOGE("couldn't write metadata file: %s", strerror(errno));
1530 return;
1531 }
1532 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1533 if (fileLength != sizeof(mMetaData)) {
1534 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1535 sizeof(mMetaData));
1536 }
1537 close(out);
1538 rename(tmpFileName, sMetaDataFile);
1539 }
1540
1541 bool upgradeKeystore() {
1542 bool upgraded = false;
1543
1544 if (mMetaData.version == 0) {
1545 UserState* userState = getUserState(0);
1546
1547 // Initialize first so the directory is made.
1548 userState->initialize();
1549
1550 // Migrate the old .masterkey file to user 0.
1551 if (access(sOldMasterKey, R_OK) == 0) {
1552 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1553 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1554 return false;
1555 }
1556 }
1557
1558 // Initialize again in case we had a key.
1559 userState->initialize();
1560
1561 // Try to migrate existing keys.
1562 DIR* dir = opendir(".");
1563 if (!dir) {
1564 // Give up now; maybe we can upgrade later.
1565 ALOGE("couldn't open keystore's directory; something is wrong");
1566 return false;
1567 }
1568
1569 struct dirent* file;
1570 while ((file = readdir(dir)) != NULL) {
1571 // We only care about files.
1572 if (file->d_type != DT_REG) {
1573 continue;
1574 }
1575
1576 // Skip anything that starts with a "."
1577 if (file->d_name[0] == '.') {
1578 continue;
1579 }
1580
1581 // Find the current file's user.
1582 char* end;
1583 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1584 if (end[0] != '_' || end[1] == 0) {
1585 continue;
1586 }
1587 UserState* otherUser = getUserState(thisUid);
1588 if (otherUser->getUserId() != 0) {
1589 unlinkat(dirfd(dir), file->d_name, 0);
1590 }
1591
1592 // Rename the file into user directory.
1593 DIR* otherdir = opendir(otherUser->getUserDirName());
1594 if (otherdir == NULL) {
1595 ALOGW("couldn't open user directory for rename");
1596 continue;
1597 }
1598 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1599 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1600 }
1601 closedir(otherdir);
1602 }
1603 closedir(dir);
1604
1605 mMetaData.version = 1;
1606 upgraded = true;
1607 }
1608
1609 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001610 }
Kenny Roota91203b2012-02-15 15:00:46 -08001611};
1612
Kenny Root655b9582013-04-04 08:37:42 -07001613const char* KeyStore::sOldMasterKey = ".masterkey";
1614const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001615
Kenny Root1b0e3932013-09-05 13:06:32 -07001616const android::String16 KeyStore::sRSAKeyType("RSA");
1617
Kenny Root07438c82012-11-02 15:41:02 -07001618namespace android {
1619class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1620public:
1621 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001622 : mKeyStore(keyStore),
1623 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001624 {
Kenny Roota91203b2012-02-15 15:00:46 -08001625 }
Kenny Roota91203b2012-02-15 15:00:46 -08001626
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001627 void binderDied(const wp<IBinder>& who) {
1628 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1629 for (auto token: operations) {
1630 abort(token);
1631 }
Kenny Root822c3a92012-03-23 16:34:39 -07001632 }
Kenny Roota91203b2012-02-15 15:00:46 -08001633
Kenny Root07438c82012-11-02 15:41:02 -07001634 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001635 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001636 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001637 }
Kenny Roota91203b2012-02-15 15:00:46 -08001638
Chad Brubaker9489b792015-04-14 11:01:45 -07001639 return mKeyStore->getState(IPCThreadState::self()->getCallingUid());
Kenny Root298e7b12012-03-26 13:54:44 -07001640 }
1641
Kenny Root07438c82012-11-02 15:41:02 -07001642 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001643 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001644 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001645 }
Kenny Root07438c82012-11-02 15:41:02 -07001646
Chad Brubaker9489b792015-04-14 11:01:45 -07001647 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001648 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001649 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001650
Kenny Root655b9582013-04-04 08:37:42 -07001651 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001652 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001653 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001654 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001655 *item = NULL;
1656 *itemLength = 0;
1657 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001658 }
Kenny Roota91203b2012-02-15 15:00:46 -08001659
Kenny Root07438c82012-11-02 15:41:02 -07001660 *item = (uint8_t*) malloc(keyBlob.getLength());
1661 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1662 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001663
Kenny Root07438c82012-11-02 15:41:02 -07001664 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001665 }
1666
Kenny Rootf9119d62013-04-03 09:22:15 -07001667 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1668 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001669 targetUid = getEffectiveUid(targetUid);
1670 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1671 flags & KEYSTORE_FLAG_ENCRYPTED);
1672 if (result != ::NO_ERROR) {
1673 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001674 }
1675
Kenny Root07438c82012-11-02 15:41:02 -07001676 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001677 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001678
1679 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001680 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1681
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001682 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001683 }
1684
Kenny Root49468902013-03-19 13:41:33 -07001685 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001686 targetUid = getEffectiveUid(targetUid);
1687 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001688 return ::PERMISSION_DENIED;
1689 }
Kenny Root07438c82012-11-02 15:41:02 -07001690 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001691 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001692 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001693 }
1694
Kenny Root49468902013-03-19 13:41:33 -07001695 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001696 targetUid = getEffectiveUid(targetUid);
1697 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001698 return ::PERMISSION_DENIED;
1699 }
1700
Kenny Root07438c82012-11-02 15:41:02 -07001701 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001702 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001703
Kenny Root655b9582013-04-04 08:37:42 -07001704 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001705 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1706 }
1707 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001708 }
1709
Kenny Root49468902013-03-19 13:41:33 -07001710 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001711 targetUid = getEffectiveUid(targetUid);
1712 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001713 return ::PERMISSION_DENIED;
1714 }
Kenny Root07438c82012-11-02 15:41:02 -07001715 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001716 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001717
Robin Lee4b84fdc2014-09-24 11:56:57 +01001718 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1719 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001720 }
Kenny Root07438c82012-11-02 15:41:02 -07001721 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001722 }
1723
Kenny Root07438c82012-11-02 15:41:02 -07001724 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001725 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001726 return ::PERMISSION_DENIED;
1727 }
1728
Chad Brubaker9489b792015-04-14 11:01:45 -07001729 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01001730 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001731 }
1732
Kenny Root07438c82012-11-02 15:41:02 -07001733 /*
1734 * Here is the history. To improve the security, the parameters to generate the
1735 * master key has been changed. To make a seamless transition, we update the
1736 * file using the same password when the user unlock it for the first time. If
1737 * any thing goes wrong during the transition, the new file will not overwrite
1738 * the old one. This avoids permanent damages of the existing data.
1739 */
1740 int32_t password(const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001741 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001742 return ::PERMISSION_DENIED;
1743 }
Kenny Root70e3a862012-02-15 17:20:23 -08001744
Kenny Root07438c82012-11-02 15:41:02 -07001745 const String8 password8(password);
Chad Brubaker9489b792015-04-14 11:01:45 -07001746 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root70e3a862012-02-15 17:20:23 -08001747
Kenny Root655b9582013-04-04 08:37:42 -07001748 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001749 case ::STATE_UNINITIALIZED: {
1750 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001751 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001752 }
1753 case ::STATE_NO_ERROR: {
1754 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001755 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001756 }
1757 case ::STATE_LOCKED: {
1758 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001759 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001760 }
1761 }
1762 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001763 }
1764
Kenny Root07438c82012-11-02 15:41:02 -07001765 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001766 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001767 return ::PERMISSION_DENIED;
1768 }
Kenny Root70e3a862012-02-15 17:20:23 -08001769
Chad Brubaker9489b792015-04-14 11:01:45 -07001770 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001771 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001772 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001773 ALOGD("calling lock in state: %d", state);
1774 return state;
1775 }
1776
Kenny Root655b9582013-04-04 08:37:42 -07001777 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001778 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001779 }
1780
Kenny Root07438c82012-11-02 15:41:02 -07001781 int32_t unlock(const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001782 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001783 return ::PERMISSION_DENIED;
1784 }
1785
Chad Brubaker9489b792015-04-14 11:01:45 -07001786 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001787 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001788 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001789 ALOGD("calling unlock when not locked");
1790 return state;
1791 }
1792
1793 const String8 password8(pw);
1794 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001795 }
1796
Kenny Root07438c82012-11-02 15:41:02 -07001797 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001798 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001799 return -1;
1800 }
Kenny Root70e3a862012-02-15 17:20:23 -08001801
Chad Brubaker9489b792015-04-14 11:01:45 -07001802 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001803 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001804 }
1805
Kenny Root96427ba2013-08-16 14:02:41 -07001806 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1807 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001808 targetUid = getEffectiveUid(targetUid);
1809 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1810 flags & KEYSTORE_FLAG_ENCRYPTED);
1811 if (result != ::NO_ERROR) {
1812 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001813 }
Kenny Root07438c82012-11-02 15:41:02 -07001814 uint8_t* data;
1815 size_t dataLength;
1816 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001817 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001818
Chad Brubaker67d2a502015-03-11 17:21:18 +00001819 const keymaster1_device_t* device = mKeyStore->getDevice();
1820 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001821 if (device == NULL) {
1822 return ::SYSTEM_ERROR;
1823 }
1824
1825 if (device->generate_keypair == NULL) {
1826 return ::SYSTEM_ERROR;
1827 }
1828
Kenny Root17208e02013-09-04 13:56:03 -07001829 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001830 keymaster_dsa_keygen_params_t dsa_params;
1831 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001832
Kenny Root96427ba2013-08-16 14:02:41 -07001833 if (keySize == -1) {
1834 keySize = DSA_DEFAULT_KEY_SIZE;
1835 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1836 || keySize > DSA_MAX_KEY_SIZE) {
1837 ALOGI("invalid key size %d", keySize);
1838 return ::SYSTEM_ERROR;
1839 }
1840 dsa_params.key_size = keySize;
1841
1842 if (args->size() == 3) {
1843 sp<KeystoreArg> gArg = args->itemAt(0);
1844 sp<KeystoreArg> pArg = args->itemAt(1);
1845 sp<KeystoreArg> qArg = args->itemAt(2);
1846
1847 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1848 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1849 dsa_params.generator_len = gArg->size();
1850
1851 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1852 dsa_params.prime_p_len = pArg->size();
1853
1854 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1855 dsa_params.prime_q_len = qArg->size();
1856 } else {
1857 ALOGI("not all DSA parameters were read");
1858 return ::SYSTEM_ERROR;
1859 }
1860 } else if (args->size() != 0) {
1861 ALOGI("DSA args must be 3");
1862 return ::SYSTEM_ERROR;
1863 }
1864
Kenny Root1d448c02013-11-21 10:36:53 -08001865 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001866 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1867 } else {
1868 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001869 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1870 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001871 }
1872 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001873 keymaster_ec_keygen_params_t ec_params;
1874 memset(&ec_params, '\0', sizeof(ec_params));
1875
1876 if (keySize == -1) {
1877 keySize = EC_DEFAULT_KEY_SIZE;
1878 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1879 ALOGI("invalid key size %d", keySize);
1880 return ::SYSTEM_ERROR;
1881 }
1882 ec_params.field_size = keySize;
1883
Kenny Root1d448c02013-11-21 10:36:53 -08001884 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001885 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1886 } else {
1887 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001888 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001889 }
Kenny Root96427ba2013-08-16 14:02:41 -07001890 } else if (keyType == EVP_PKEY_RSA) {
1891 keymaster_rsa_keygen_params_t rsa_params;
1892 memset(&rsa_params, '\0', sizeof(rsa_params));
1893 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1894
1895 if (keySize == -1) {
1896 keySize = RSA_DEFAULT_KEY_SIZE;
1897 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1898 ALOGI("invalid key size %d", keySize);
1899 return ::SYSTEM_ERROR;
1900 }
1901 rsa_params.modulus_size = keySize;
1902
1903 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001904 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001905 return ::SYSTEM_ERROR;
1906 } else if (args->size() == 1) {
1907 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1908 if (pubExpBlob != NULL) {
1909 Unique_BIGNUM pubExpBn(
1910 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1911 pubExpBlob->size(), NULL));
1912 if (pubExpBn.get() == NULL) {
1913 ALOGI("Could not convert public exponent to BN");
1914 return ::SYSTEM_ERROR;
1915 }
1916 unsigned long pubExp = BN_get_word(pubExpBn.get());
1917 if (pubExp == 0xFFFFFFFFL) {
1918 ALOGI("cannot represent public exponent as a long value");
1919 return ::SYSTEM_ERROR;
1920 }
1921 rsa_params.public_exponent = pubExp;
1922 }
1923 }
1924
1925 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1926 } else {
1927 ALOGW("Unsupported key type %d", keyType);
1928 rc = -1;
1929 }
1930
Kenny Root07438c82012-11-02 15:41:02 -07001931 if (rc) {
1932 return ::SYSTEM_ERROR;
1933 }
1934
Kenny Root655b9582013-04-04 08:37:42 -07001935 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07001936 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001937
1938 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1939 free(data);
1940
Kenny Rootee8068b2013-10-07 09:49:15 -07001941 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001942 keyBlob.setFallback(isFallback);
1943
Chad Brubaker9489b792015-04-14 11:01:45 -07001944 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001945 }
1946
Kenny Rootf9119d62013-04-03 09:22:15 -07001947 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1948 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001949 targetUid = getEffectiveUid(targetUid);
1950 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1951 flags & KEYSTORE_FLAG_ENCRYPTED);
1952 if (result != ::NO_ERROR) {
1953 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001954 }
Kenny Root07438c82012-11-02 15:41:02 -07001955 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001956 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001957
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001958 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001959 }
1960
Kenny Root07438c82012-11-02 15:41:02 -07001961 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1962 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001963 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07001964 return ::PERMISSION_DENIED;
1965 }
Kenny Root07438c82012-11-02 15:41:02 -07001966
Chad Brubaker9489b792015-04-14 11:01:45 -07001967 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001968 Blob keyBlob;
1969 String8 name8(name);
1970
Kenny Rootd38a0b02013-02-13 12:59:14 -08001971 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001972
Kenny Root655b9582013-04-04 08:37:42 -07001973 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001974 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001975 if (responseCode != ::NO_ERROR) {
1976 return responseCode;
1977 }
1978
Chad Brubaker67d2a502015-03-11 17:21:18 +00001979 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07001980 if (device == NULL) {
1981 ALOGE("no keymaster device; cannot sign");
1982 return ::SYSTEM_ERROR;
1983 }
1984
1985 if (device->sign_data == NULL) {
1986 ALOGE("device doesn't implement signing");
1987 return ::SYSTEM_ERROR;
1988 }
1989
1990 keymaster_rsa_sign_params_t params;
1991 params.digest_type = DIGEST_NONE;
1992 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07001993 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001994 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07001995 if (rc) {
1996 ALOGW("device couldn't sign data");
1997 return ::SYSTEM_ERROR;
1998 }
1999
2000 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002001 }
2002
Kenny Root07438c82012-11-02 15:41:02 -07002003 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2004 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002005 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002006 return ::PERMISSION_DENIED;
2007 }
Kenny Root70e3a862012-02-15 17:20:23 -08002008
Chad Brubaker9489b792015-04-14 11:01:45 -07002009 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002010 Blob keyBlob;
2011 String8 name8(name);
2012 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002013
Kenny Root655b9582013-04-04 08:37:42 -07002014 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002015 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002016 if (responseCode != ::NO_ERROR) {
2017 return responseCode;
2018 }
Kenny Root70e3a862012-02-15 17:20:23 -08002019
Chad Brubaker67d2a502015-03-11 17:21:18 +00002020 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002021 if (device == NULL) {
2022 return ::SYSTEM_ERROR;
2023 }
Kenny Root70e3a862012-02-15 17:20:23 -08002024
Kenny Root07438c82012-11-02 15:41:02 -07002025 if (device->verify_data == NULL) {
2026 return ::SYSTEM_ERROR;
2027 }
Kenny Root70e3a862012-02-15 17:20:23 -08002028
Kenny Root07438c82012-11-02 15:41:02 -07002029 keymaster_rsa_sign_params_t params;
2030 params.digest_type = DIGEST_NONE;
2031 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002032
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002033 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2034 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002035 if (rc) {
2036 return ::SYSTEM_ERROR;
2037 } else {
2038 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002039 }
2040 }
Kenny Root07438c82012-11-02 15:41:02 -07002041
2042 /*
2043 * TODO: The abstraction between things stored in hardware and regular blobs
2044 * of data stored on the filesystem should be moved down to keystore itself.
2045 * Unfortunately the Java code that calls this has naming conventions that it
2046 * knows about. Ideally keystore shouldn't be used to store random blobs of
2047 * data.
2048 *
2049 * Until that happens, it's necessary to have a separate "get_pubkey" and
2050 * "del_key" since the Java code doesn't really communicate what it's
2051 * intentions are.
2052 */
2053 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002054 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002055 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002056 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002057 return ::PERMISSION_DENIED;
2058 }
Kenny Root07438c82012-11-02 15:41:02 -07002059
Kenny Root07438c82012-11-02 15:41:02 -07002060 Blob keyBlob;
2061 String8 name8(name);
2062
Kenny Rootd38a0b02013-02-13 12:59:14 -08002063 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002064
Kenny Root655b9582013-04-04 08:37:42 -07002065 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002066 TYPE_KEY_PAIR);
2067 if (responseCode != ::NO_ERROR) {
2068 return responseCode;
2069 }
2070
Chad Brubaker67d2a502015-03-11 17:21:18 +00002071 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002072 if (device == NULL) {
2073 return ::SYSTEM_ERROR;
2074 }
2075
2076 if (device->get_keypair_public == NULL) {
2077 ALOGE("device has no get_keypair_public implementation!");
2078 return ::SYSTEM_ERROR;
2079 }
2080
Kenny Root17208e02013-09-04 13:56:03 -07002081 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002082 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2083 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002084 if (rc) {
2085 return ::SYSTEM_ERROR;
2086 }
2087
2088 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002089 }
Kenny Root07438c82012-11-02 15:41:02 -07002090
Kenny Root49468902013-03-19 13:41:33 -07002091 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002092 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002093 }
2094
2095 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002096 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002097 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2098 if (result != ::NO_ERROR) {
2099 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002100 }
2101
2102 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002103 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002104
Kenny Root655b9582013-04-04 08:37:42 -07002105 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002106 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2107 }
2108
Kenny Root655b9582013-04-04 08:37:42 -07002109 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002110 return ::NO_ERROR;
2111 }
2112
2113 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002114 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002115 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2116 if (result != ::NO_ERROR) {
2117 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002118 }
2119
2120 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002121 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002122
Kenny Root655b9582013-04-04 08:37:42 -07002123 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002124 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2125 }
2126
Kenny Root655b9582013-04-04 08:37:42 -07002127 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002128 }
2129
2130 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002131 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002132 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002133 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002134 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002135 }
Kenny Root07438c82012-11-02 15:41:02 -07002136
2137 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002138 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002139
Kenny Root655b9582013-04-04 08:37:42 -07002140 if (access(filename.string(), R_OK) == -1) {
2141 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002142 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002143 }
2144
Kenny Root655b9582013-04-04 08:37:42 -07002145 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002146 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002147 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002148 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002149 }
2150
2151 struct stat s;
2152 int ret = fstat(fd, &s);
2153 close(fd);
2154 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002155 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002156 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002157 }
2158
Kenny Root36a9e232013-02-04 14:24:15 -08002159 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002160 }
2161
Kenny Rootd53bc922013-03-21 14:10:15 -07002162 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2163 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002164 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002165 pid_t spid = IPCThreadState::self()->getCallingPid();
2166 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002167 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002168 return -1L;
2169 }
2170
Kenny Root655b9582013-04-04 08:37:42 -07002171 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002172 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002173 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002174 return state;
2175 }
2176
Kenny Rootd53bc922013-03-21 14:10:15 -07002177 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2178 srcUid = callingUid;
2179 } else if (!is_granted_to(callingUid, srcUid)) {
2180 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002181 return ::PERMISSION_DENIED;
2182 }
2183
Kenny Rootd53bc922013-03-21 14:10:15 -07002184 if (destUid == -1) {
2185 destUid = callingUid;
2186 }
2187
2188 if (srcUid != destUid) {
2189 if (static_cast<uid_t>(srcUid) != callingUid) {
2190 ALOGD("can only duplicate from caller to other or to same uid: "
2191 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2192 return ::PERMISSION_DENIED;
2193 }
2194
2195 if (!is_granted_to(callingUid, destUid)) {
2196 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2197 return ::PERMISSION_DENIED;
2198 }
2199 }
2200
2201 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002202 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002203
Kenny Rootd53bc922013-03-21 14:10:15 -07002204 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002205 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002206
Kenny Root655b9582013-04-04 08:37:42 -07002207 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2208 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002209 return ::SYSTEM_ERROR;
2210 }
2211
Kenny Rootd53bc922013-03-21 14:10:15 -07002212 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002213 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002214 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002215 if (responseCode != ::NO_ERROR) {
2216 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002217 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002218
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002219 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002220 }
2221
Kenny Root1b0e3932013-09-05 13:06:32 -07002222 int32_t is_hardware_backed(const String16& keyType) {
2223 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002224 }
2225
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002226 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002227 uid_t targetUid = getEffectiveUid(targetUid64);
2228 if (!checkBinderPermission(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002229 return ::PERMISSION_DENIED;
2230 }
2231
Robin Lee4b84fdc2014-09-24 11:56:57 +01002232 String8 prefix = String8::format("%u_", targetUid);
2233 Vector<String16> aliases;
2234 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002235 return ::SYSTEM_ERROR;
2236 }
2237
Robin Lee4b84fdc2014-09-24 11:56:57 +01002238 for (uint32_t i = 0; i < aliases.size(); i++) {
2239 String8 name8(aliases[i]);
2240 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2241 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002242 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002243 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002244 }
2245
Robin Lee4b84fdc2014-09-24 11:56:57 +01002246 int32_t reset_uid(int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002247 targetUid = getEffectiveUid(targetUid);
2248 if (!checkBinderPermission(P_RESET_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002249 return ::PERMISSION_DENIED;
2250 }
Chad Brubakerbbc76482015-04-16 15:16:44 -07002251 // Flush the auth token table to prevent stale tokens from sticking
2252 // around.
2253 mAuthTokenTable.Clear();
Robin Lee4e865752014-08-19 17:37:55 +01002254
Robin Lee4b84fdc2014-09-24 11:56:57 +01002255 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002256 }
2257
2258 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002259 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002260 return ::PERMISSION_DENIED;
2261 }
Chad Brubaker9489b792015-04-14 11:01:45 -07002262
Robin Lee4e865752014-08-19 17:37:55 +01002263 if (sourceUid == targetUid) {
2264 return ::SYSTEM_ERROR;
2265 }
2266
2267 // Initialise user keystore with existing master key held in-memory
2268 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2269 }
2270
2271 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002272 targetUid = getEffectiveUid(targetUid);
2273 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002274 return ::PERMISSION_DENIED;
2275 }
Robin Lee4e865752014-08-19 17:37:55 +01002276 const String8 password8(pw);
2277
2278 switch (mKeyStore->getState(targetUid)) {
2279 case ::STATE_UNINITIALIZED: {
2280 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2281 return mKeyStore->initializeUser(password8, targetUid);
2282 }
2283 case ::STATE_NO_ERROR: {
2284 // rewrite master key with new password.
2285 return mKeyStore->writeMasterKey(password8, targetUid);
2286 }
2287 case ::STATE_LOCKED: {
2288 // read master key, decrypt with password, initialize mMasterKey*.
2289 return mKeyStore->readMasterKey(password8, targetUid);
2290 }
2291 }
2292 return ::SYSTEM_ERROR;
2293 }
2294
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002295 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2296 const keymaster1_device_t* device = mKeyStore->getDevice();
2297 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2298 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2299 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2300 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2301 device->add_rng_entropy != NULL) {
2302 devResult = device->add_rng_entropy(device, data, dataLength);
2303 }
2304 if (fallback->add_rng_entropy) {
2305 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2306 }
2307 if (devResult) {
2308 return devResult;
2309 }
2310 if (fallbackResult) {
2311 return fallbackResult;
2312 }
2313 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002314 }
2315
Chad Brubaker17d68b92015-02-05 22:04:16 -08002316 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002317 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2318 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002319 uid = getEffectiveUid(uid);
2320 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2321 flags & KEYSTORE_FLAG_ENCRYPTED);
2322 if (rc != ::NO_ERROR) {
2323 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002324 }
2325
Chad Brubaker9489b792015-04-14 11:01:45 -07002326 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002327 bool isFallback = false;
2328 keymaster_key_blob_t blob;
2329 keymaster_key_characteristics_t *out = NULL;
2330
2331 const keymaster1_device_t* device = mKeyStore->getDevice();
2332 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2333 if (device == NULL) {
2334 return ::SYSTEM_ERROR;
2335 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002336 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002337 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2338 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002339 if (!entropy) {
2340 rc = KM_ERROR_OK;
2341 } else if (device->add_rng_entropy) {
2342 rc = device->add_rng_entropy(device, entropy, entropyLength);
2343 } else {
2344 rc = KM_ERROR_UNIMPLEMENTED;
2345 }
2346 if (rc == KM_ERROR_OK) {
2347 rc = device->generate_key(device, params.params.data(), params.params.size(),
2348 &blob, &out);
2349 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002350 }
2351 // If the HW device didn't support generate_key or generate_key failed
2352 // fall back to the software implementation.
2353 if (rc && fallback->generate_key != NULL) {
2354 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002355 if (!entropy) {
2356 rc = KM_ERROR_OK;
2357 } else if (fallback->add_rng_entropy) {
2358 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2359 } else {
2360 rc = KM_ERROR_UNIMPLEMENTED;
2361 }
2362 if (rc == KM_ERROR_OK) {
2363 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2364 &blob,
2365 &out);
2366 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002367 }
2368
2369 if (out) {
2370 if (outCharacteristics) {
2371 outCharacteristics->characteristics = *out;
2372 } else {
2373 keymaster_free_characteristics(out);
2374 }
2375 free(out);
2376 }
2377
2378 if (rc) {
2379 return rc;
2380 }
2381
2382 String8 name8(name);
2383 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2384
2385 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2386 keyBlob.setFallback(isFallback);
2387 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2388
2389 free(const_cast<uint8_t*>(blob.key_material));
2390
2391 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002392 }
2393
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002394 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002395 const keymaster_blob_t* clientId,
2396 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002397 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002398 if (!outCharacteristics) {
2399 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2400 }
2401
2402 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2403
2404 Blob keyBlob;
2405 String8 name8(name);
2406 int rc;
2407
2408 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2409 TYPE_KEYMASTER_10);
2410 if (responseCode != ::NO_ERROR) {
2411 return responseCode;
2412 }
2413 keymaster_key_blob_t key;
2414 key.key_material_size = keyBlob.getLength();
2415 key.key_material = keyBlob.getValue();
2416 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2417 keymaster_key_characteristics_t *out = NULL;
2418 if (!dev->get_key_characteristics) {
2419 ALOGW("device does not implement get_key_characteristics");
2420 return KM_ERROR_UNIMPLEMENTED;
2421 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002422 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002423 if (out) {
2424 outCharacteristics->characteristics = *out;
2425 free(out);
2426 }
2427 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002428 }
2429
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002430 int32_t importKey(const String16& name, const KeymasterArguments& params,
2431 keymaster_key_format_t format, const uint8_t *keyData,
2432 size_t keyLength, int uid, int flags,
2433 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002434 uid = getEffectiveUid(uid);
2435 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2436 flags & KEYSTORE_FLAG_ENCRYPTED);
2437 if (rc != ::NO_ERROR) {
2438 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002439 }
2440
Chad Brubaker9489b792015-04-14 11:01:45 -07002441 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002442 bool isFallback = false;
2443 keymaster_key_blob_t blob;
2444 keymaster_key_characteristics_t *out = NULL;
2445
2446 const keymaster1_device_t* device = mKeyStore->getDevice();
2447 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2448 if (device == NULL) {
2449 return ::SYSTEM_ERROR;
2450 }
2451 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2452 device->import_key != NULL) {
2453 rc = device->import_key(device, params.params.data(), params.params.size(),
2454 format, keyData, keyLength, &blob, &out);
2455 }
2456 if (rc && fallback->import_key != NULL) {
2457 isFallback = true;
2458 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2459 format, keyData, keyLength, &blob, &out);
2460 }
2461 if (out) {
2462 if (outCharacteristics) {
2463 outCharacteristics->characteristics = *out;
2464 } else {
2465 keymaster_free_characteristics(out);
2466 }
2467 free(out);
2468 }
2469 if (rc) {
2470 return rc;
2471 }
2472
2473 String8 name8(name);
2474 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2475
2476 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2477 keyBlob.setFallback(isFallback);
2478 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2479
2480 free((void*) blob.key_material);
2481
2482 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002483 }
2484
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002485 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002486 const keymaster_blob_t* clientId,
2487 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002488
2489 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2490
2491 Blob keyBlob;
2492 String8 name8(name);
2493 int rc;
2494
2495 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2496 TYPE_KEYMASTER_10);
2497 if (responseCode != ::NO_ERROR) {
2498 result->resultCode = responseCode;
2499 return;
2500 }
2501 keymaster_key_blob_t key;
2502 key.key_material_size = keyBlob.getLength();
2503 key.key_material = keyBlob.getValue();
2504 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2505 if (!dev->export_key) {
2506 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2507 return;
2508 }
2509 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002510 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002511 &ptr, &result->dataLength);
2512 result->exportData.reset(ptr);
2513 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002514 }
2515
Chad Brubakerad6514a2015-04-09 14:00:26 -07002516
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002517 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002518 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2519 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002520 if (!result || !outParams) {
2521 ALOGE("Unexpected null arguments to begin()");
2522 return;
2523 }
2524 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2525 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2526 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2527 result->resultCode = ::PERMISSION_DENIED;
2528 return;
2529 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002530 if (!checkAllowedOperationParams(params.params)) {
2531 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2532 return;
2533 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002534 Blob keyBlob;
2535 String8 name8(name);
2536 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2537 TYPE_KEYMASTER_10);
2538 if (responseCode != ::NO_ERROR) {
2539 result->resultCode = responseCode;
2540 return;
2541 }
2542 keymaster_key_blob_t key;
2543 key.key_material_size = keyBlob.getLength();
2544 key.key_material = keyBlob.getValue();
2545 keymaster_key_param_t* out;
2546 size_t outSize;
2547 keymaster_operation_handle_t handle;
2548 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002549 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002550 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002551 Unique_keymaster_key_characteristics characteristics;
2552 characteristics.reset(new keymaster_key_characteristics_t);
2553 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2554 if (err) {
2555 result->resultCode = err;
2556 return;
2557 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002558 const hw_auth_token_t* authToken = NULL;
2559 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002560 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002561 // If per-operation auth is needed we need to begin the operation and
2562 // the client will need to authorize that operation before calling
2563 // update. Any other auth issues stop here.
2564 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2565 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002566 return;
2567 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002568 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002569 // Add entropy to the device first.
2570 if (entropy) {
2571 if (dev->add_rng_entropy) {
2572 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2573 } else {
2574 err = KM_ERROR_UNIMPLEMENTED;
2575 }
2576 if (err) {
2577 result->resultCode = err;
2578 return;
2579 }
2580 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002581 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2582 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002583
2584 // If there are too many operations abort the oldest operation that was
2585 // started as pruneable and try again.
2586 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2587 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2588 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2589 if (abort(oldest) != ::NO_ERROR) {
2590 break;
2591 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002592 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002593 &handle);
2594 }
2595 if (err) {
2596 result->resultCode = err;
2597 return;
2598 }
2599 if (out) {
2600 outParams->params.assign(out, out + outSize);
2601 free(out);
2602 }
2603
Chad Brubakerad6514a2015-04-09 14:00:26 -07002604 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2605 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002606 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002607 if (authToken) {
2608 mOperationMap.setOperationAuthToken(operationToken, authToken);
2609 }
2610 // Return the authentication lookup result. If this is a per operation
2611 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2612 // application should get an auth token using the handle before the
2613 // first call to update, which will fail if keystore hasn't received the
2614 // auth token.
2615 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002616 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002617 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002618 }
2619
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002620 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2621 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002622 if (!checkAllowedOperationParams(params.params)) {
2623 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2624 return;
2625 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002626 const keymaster1_device_t* dev;
2627 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002628 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002629 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2630 return;
2631 }
2632 uint8_t* output_buf = NULL;
2633 size_t output_length = 0;
2634 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002635 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002636 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2637 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002638 result->resultCode = authResult;
2639 return;
2640 }
2641 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2642 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002643 result->data.reset(output_buf);
2644 result->dataLength = output_length;
2645 result->inputConsumed = consumed;
2646 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002647 }
2648
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002649 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2650 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002651 if (!checkAllowedOperationParams(params.params)) {
2652 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2653 return;
2654 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002655 const keymaster1_device_t* dev;
2656 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002657 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002658 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2659 return;
2660 }
2661 uint8_t* output_buf = NULL;
2662 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002663 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002664 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2665 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002666 result->resultCode = authResult;
2667 return;
2668 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002669
Chad Brubaker06801e02015-03-31 15:13:13 -07002670 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2671 signature, signatureLength, &output_buf,
2672 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002673 // Remove the operation regardless of the result
2674 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002675 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002676 result->data.reset(output_buf);
2677 result->dataLength = output_length;
2678 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002679 }
2680
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002681 int32_t abort(const sp<IBinder>& token) {
2682 const keymaster1_device_t* dev;
2683 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002684 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002685 return KM_ERROR_INVALID_OPERATION_HANDLE;
2686 }
2687 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002688 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002689 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002690 rc = KM_ERROR_UNIMPLEMENTED;
2691 } else {
2692 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002693 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002694 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002695 if (rc) {
2696 return rc;
2697 }
2698 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002699 }
2700
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002701 bool isOperationAuthorized(const sp<IBinder>& token) {
2702 const keymaster1_device_t* dev;
2703 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002704 const keymaster_key_characteristics_t* characteristics;
2705 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002706 return false;
2707 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002708 const hw_auth_token_t* authToken = NULL;
2709 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002710 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002711 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2712 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002713 }
2714
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002715 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002716 if (!checkBinderPermission(P_ADD_AUTH)) {
2717 ALOGW("addAuthToken: permission denied for %d",
2718 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002719 return ::PERMISSION_DENIED;
2720 }
2721 if (length != sizeof(hw_auth_token_t)) {
2722 return KM_ERROR_INVALID_ARGUMENT;
2723 }
2724 hw_auth_token_t* authToken = new hw_auth_token_t;
2725 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2726 // The table takes ownership of authToken.
2727 mAuthTokenTable.AddAuthenticationToken(authToken);
2728 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002729 }
2730
Kenny Root07438c82012-11-02 15:41:02 -07002731private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002732 static const int32_t UID_SELF = -1;
2733
2734 /**
2735 * Get the effective target uid for a binder operation that takes an
2736 * optional uid as the target.
2737 */
2738 inline uid_t getEffectiveUid(int32_t targetUid) {
2739 if (targetUid == UID_SELF) {
2740 return IPCThreadState::self()->getCallingUid();
2741 }
2742 return static_cast<uid_t>(targetUid);
2743 }
2744
2745 /**
2746 * Check if the caller of the current binder method has the required
2747 * permission and if acting on other uids the grants to do so.
2748 */
2749 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2750 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2751 pid_t spid = IPCThreadState::self()->getCallingPid();
2752 if (!has_permission(callingUid, permission, spid)) {
2753 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2754 return false;
2755 }
2756 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2757 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2758 return false;
2759 }
2760 return true;
2761 }
2762
2763 /**
2764 * Check if the caller of the current binder method has the required
2765 * permission or the target of the operation is the caller's uid. This is
2766 * for operation where the permission is only for cross-uid activity and all
2767 * uids are allowed to act on their own (ie: clearing all entries for a
2768 * given uid).
2769 */
2770 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2771 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2772 if (getEffectiveUid(targetUid) == callingUid) {
2773 return true;
2774 } else {
2775 return checkBinderPermission(permission, targetUid);
2776 }
2777 }
2778
2779 /**
2780 * Helper method to check that the caller has the required permission as
2781 * well as the keystore is in the unlocked state if checkUnlocked is true.
2782 *
2783 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2784 * otherwise the state of keystore when not unlocked and checkUnlocked is
2785 * true.
2786 */
2787 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2788 bool checkUnlocked = true) {
2789 if (!checkBinderPermission(permission, targetUid)) {
2790 return ::PERMISSION_DENIED;
2791 }
2792 State state = mKeyStore->getState(getEffectiveUid(targetUid));
2793 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2794 return state;
2795 }
2796
2797 return ::NO_ERROR;
2798
2799 }
2800
Kenny Root9d45d1c2013-02-14 10:32:30 -08002801 inline bool isKeystoreUnlocked(State state) {
2802 switch (state) {
2803 case ::STATE_NO_ERROR:
2804 return true;
2805 case ::STATE_UNINITIALIZED:
2806 case ::STATE_LOCKED:
2807 return false;
2808 }
2809 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002810 }
2811
Chad Brubaker67d2a502015-03-11 17:21:18 +00002812 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002813 const int32_t device_api = device->common.module->module_api_version;
2814 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2815 switch (keyType) {
2816 case TYPE_RSA:
2817 case TYPE_DSA:
2818 case TYPE_EC:
2819 return true;
2820 default:
2821 return false;
2822 }
2823 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2824 switch (keyType) {
2825 case TYPE_RSA:
2826 return true;
2827 case TYPE_DSA:
2828 return device->flags & KEYMASTER_SUPPORTS_DSA;
2829 case TYPE_EC:
2830 return device->flags & KEYMASTER_SUPPORTS_EC;
2831 default:
2832 return false;
2833 }
2834 } else {
2835 return keyType == TYPE_RSA;
2836 }
2837 }
2838
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002839 /**
2840 * Check that all keymaster_key_param_t's provided by the application are
2841 * allowed. Any parameter that keystore adds itself should be disallowed here.
2842 */
2843 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2844 for (auto param: params) {
2845 switch (param.tag) {
2846 case KM_TAG_AUTH_TOKEN:
2847 return false;
2848 default:
2849 break;
2850 }
2851 }
2852 return true;
2853 }
2854
2855 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2856 const keymaster1_device_t* dev,
2857 const std::vector<keymaster_key_param_t>& params,
2858 keymaster_key_characteristics_t* out) {
2859 UniquePtr<keymaster_blob_t> appId;
2860 UniquePtr<keymaster_blob_t> appData;
2861 for (auto param : params) {
2862 if (param.tag == KM_TAG_APPLICATION_ID) {
2863 appId.reset(new keymaster_blob_t);
2864 appId->data = param.blob.data;
2865 appId->data_length = param.blob.data_length;
2866 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2867 appData.reset(new keymaster_blob_t);
2868 appData->data = param.blob.data;
2869 appData->data_length = param.blob.data_length;
2870 }
2871 }
2872 keymaster_key_characteristics_t* result = NULL;
2873 if (!dev->get_key_characteristics) {
2874 return KM_ERROR_UNIMPLEMENTED;
2875 }
2876 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2877 appData.get(), &result);
2878 if (result) {
2879 *out = *result;
2880 free(result);
2881 }
2882 return error;
2883 }
2884
2885 /**
2886 * Get the auth token for this operation from the auth token table.
2887 *
2888 * Returns ::NO_ERROR if the auth token was set or none was required.
2889 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2890 * authorization token exists for that operation and
2891 * failOnTokenMissing is false.
2892 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2893 * token for the operation
2894 */
2895 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2896 keymaster_operation_handle_t handle,
2897 const hw_auth_token_t** authToken,
2898 bool failOnTokenMissing = true) {
2899
2900 std::vector<keymaster_key_param_t> allCharacteristics;
2901 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2902 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2903 }
2904 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2905 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2906 }
2907 keymaster::AuthTokenTable::Error err =
2908 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2909 allCharacteristics.size(), handle, authToken);
2910 switch (err) {
2911 case keymaster::AuthTokenTable::OK:
2912 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2913 return ::NO_ERROR;
2914 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2915 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2916 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2917 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2918 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2919 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2920 (int32_t) ::OP_AUTH_NEEDED;
2921 default:
2922 ALOGE("Unexpected FindAuthorization return value %d", err);
2923 return KM_ERROR_INVALID_ARGUMENT;
2924 }
2925 }
2926
2927 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2928 const hw_auth_token_t* token) {
2929 if (token) {
2930 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2931 reinterpret_cast<const uint8_t*>(token),
2932 sizeof(hw_auth_token_t)));
2933 }
2934 }
2935
2936 /**
2937 * Add the auth token for the operation to the param list if the operation
2938 * requires authorization. Uses the cached result in the OperationMap if available
2939 * otherwise gets the token from the AuthTokenTable and caches the result.
2940 *
2941 * Returns ::NO_ERROR if the auth token was added or not needed.
2942 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2943 * authenticated.
2944 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2945 * operation token.
2946 */
2947 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2948 std::vector<keymaster_key_param_t>* params) {
2949 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002950 mOperationMap.getOperationAuthToken(token, &authToken);
2951 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002952 const keymaster1_device_t* dev;
2953 keymaster_operation_handle_t handle;
2954 const keymaster_key_characteristics_t* characteristics = NULL;
2955 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
2956 return KM_ERROR_INVALID_OPERATION_HANDLE;
2957 }
2958 int32_t result = getAuthToken(characteristics, handle, &authToken);
2959 if (result != ::NO_ERROR) {
2960 return result;
2961 }
2962 if (authToken) {
2963 mOperationMap.setOperationAuthToken(token, authToken);
2964 }
2965 }
2966 addAuthToParams(params, authToken);
2967 return ::NO_ERROR;
2968 }
2969
Kenny Root07438c82012-11-02 15:41:02 -07002970 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002971 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002972 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07002973};
2974
2975}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002976
2977int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002978 if (argc < 2) {
2979 ALOGE("A directory must be specified!");
2980 return 1;
2981 }
2982 if (chdir(argv[1]) == -1) {
2983 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2984 return 1;
2985 }
2986
2987 Entropy entropy;
2988 if (!entropy.open()) {
2989 return 1;
2990 }
Kenny Root70e3a862012-02-15 17:20:23 -08002991
Shawn Willden80843db2015-02-24 09:31:25 -07002992 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002993 if (keymaster_device_initialize(&dev)) {
2994 ALOGE("keystore keymaster could not be initialized; exiting");
2995 return 1;
2996 }
2997
Chad Brubaker67d2a502015-03-11 17:21:18 +00002998 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002999 if (fallback_keymaster_device_initialize(&fallback)) {
3000 ALOGE("software keymaster could not be initialized; exiting");
3001 return 1;
3002 }
3003
Riley Spahneaabae92014-06-30 12:39:52 -07003004 ks_is_selinux_enabled = is_selinux_enabled();
3005 if (ks_is_selinux_enabled) {
3006 union selinux_callback cb;
3007 cb.func_log = selinux_log_callback;
3008 selinux_set_callback(SELINUX_CB_LOG, cb);
3009 if (getcon(&tctx) != 0) {
3010 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3011 return -1;
3012 }
3013 } else {
3014 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3015 }
3016
Chad Brubaker67d2a502015-03-11 17:21:18 +00003017 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003018 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003019 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3020 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3021 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3022 if (ret != android::OK) {
3023 ALOGE("Couldn't register binder service!");
3024 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003025 }
Kenny Root07438c82012-11-02 15:41:02 -07003026
3027 /*
3028 * We're the only thread in existence, so we're just going to process
3029 * Binder transaction as a single-threaded program.
3030 */
3031 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003032
3033 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003034 return 1;
3035}