blob: 2ee7324baa06fe31c559c99b8dcbb542a50de6df [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker919cb2a2015-02-05 21:58:25 -080046#include <keymaster/soft_keymaster_device.h>
Shawn Willden9e5016a2015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Shawn Willden9e5016a2015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willdenef572b62015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100155 P_TEST = 1 << 0,
156 P_GET = 1 << 1,
157 P_INSERT = 1 << 2,
158 P_DELETE = 1 << 3,
159 P_EXIST = 1 << 4,
160 P_SAW = 1 << 5,
161 P_RESET = 1 << 6,
162 P_PASSWORD = 1 << 7,
163 P_LOCK = 1 << 8,
164 P_UNLOCK = 1 << 9,
165 P_ZERO = 1 << 10,
166 P_SIGN = 1 << 11,
167 P_VERIFY = 1 << 12,
168 P_GRANT = 1 << 13,
169 P_DUPLICATE = 1 << 14,
170 P_CLEAR_UID = 1 << 15,
171 P_RESET_UID = 1 << 16,
172 P_SYNC_UID = 1 << 17,
173 P_PASSWORD_UID = 1 << 18,
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700174 P_ADD_AUTH = 1 << 19,
Kenny Root07438c82012-11-02 15:41:02 -0700175} perm_t;
176
177static struct user_euid {
178 uid_t uid;
179 uid_t euid;
180} user_euids[] = {
181 {AID_VPN, AID_SYSTEM},
182 {AID_WIFI, AID_SYSTEM},
183 {AID_ROOT, AID_SYSTEM},
184};
185
Riley Spahneaabae92014-06-30 12:39:52 -0700186/* perm_labels associcated with keystore_key SELinux class verbs. */
187const char *perm_labels[] = {
188 "test",
189 "get",
190 "insert",
191 "delete",
192 "exist",
193 "saw",
194 "reset",
195 "password",
196 "lock",
197 "unlock",
198 "zero",
199 "sign",
200 "verify",
201 "grant",
202 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100203 "clear_uid",
204 "reset_uid",
205 "sync_uid",
206 "password_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700207 "add_auth",
Riley Spahneaabae92014-06-30 12:39:52 -0700208};
209
Kenny Root07438c82012-11-02 15:41:02 -0700210static struct user_perm {
211 uid_t uid;
212 perm_t perms;
213} user_perms[] = {
214 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
215 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
216 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
217 {AID_ROOT, static_cast<perm_t>(P_GET) },
218};
219
220static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
221 | P_VERIFY);
222
Riley Spahneaabae92014-06-30 12:39:52 -0700223static char *tctx;
224static int ks_is_selinux_enabled;
225
226static const char *get_perm_label(perm_t perm) {
227 unsigned int index = ffs(perm);
228 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
229 return perm_labels[index - 1];
230 } else {
231 ALOGE("Keystore: Failed to retrieve permission label.\n");
232 abort();
233 }
234}
235
Kenny Root655b9582013-04-04 08:37:42 -0700236/**
237 * Returns the app ID (in the Android multi-user sense) for the current
238 * UNIX UID.
239 */
240static uid_t get_app_id(uid_t uid) {
241 return uid % AID_USER;
242}
243
244/**
245 * Returns the user ID (in the Android multi-user sense) for the current
246 * UNIX UID.
247 */
248static uid_t get_user_id(uid_t uid) {
249 return uid / AID_USER;
250}
251
Chad Brubakereecdd122015-05-07 10:19:40 -0700252static uid_t get_uid(uid_t userId, uid_t appId) {
253 return userId * AID_USER + get_app_id(appId);
254}
255
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700256static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700257 if (!ks_is_selinux_enabled) {
258 return true;
259 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000260
Riley Spahneaabae92014-06-30 12:39:52 -0700261 char *sctx = NULL;
262 const char *selinux_class = "keystore_key";
263 const char *str_perm = get_perm_label(perm);
264
265 if (!str_perm) {
266 return false;
267 }
268
269 if (getpidcon(spid, &sctx) != 0) {
270 ALOGE("SELinux: Failed to get source pid context.\n");
271 return false;
272 }
273
274 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
275 NULL) == 0;
276 freecon(sctx);
277 return allowed;
278}
279
280static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700281 // All system users are equivalent for multi-user support.
282 if (get_app_id(uid) == AID_SYSTEM) {
283 uid = AID_SYSTEM;
284 }
285
Kenny Root07438c82012-11-02 15:41:02 -0700286 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
287 struct user_perm user = user_perms[i];
288 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700289 return (user.perms & perm) &&
290 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700291 }
292 }
293
Riley Spahneaabae92014-06-30 12:39:52 -0700294 return (DEFAULT_PERMS & perm) &&
295 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700296}
297
Kenny Root49468902013-03-19 13:41:33 -0700298/**
299 * Returns the UID that the callingUid should act as. This is here for
300 * legacy support of the WiFi and VPN systems and should be removed
301 * when WiFi can operate in its own namespace.
302 */
Kenny Root07438c82012-11-02 15:41:02 -0700303static uid_t get_keystore_euid(uid_t uid) {
304 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
305 struct user_euid user = user_euids[i];
306 if (user.uid == uid) {
307 return user.euid;
308 }
309 }
310
311 return uid;
312}
313
Kenny Root49468902013-03-19 13:41:33 -0700314/**
315 * Returns true if the callingUid is allowed to interact in the targetUid's
316 * namespace.
317 */
318static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700319 if (callingUid == targetUid) {
320 return true;
321 }
Kenny Root49468902013-03-19 13:41:33 -0700322 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
323 struct user_euid user = user_euids[i];
324 if (user.euid == callingUid && user.uid == targetUid) {
325 return true;
326 }
327 }
328
329 return false;
330}
331
Kenny Roota91203b2012-02-15 15:00:46 -0800332/* Here is the encoding of keys. This is necessary in order to allow arbitrary
333 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
334 * into two bytes. The first byte is one of [+-.] which represents the first
335 * two bits of the character. The second byte encodes the rest of the bits into
336 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
337 * that Base64 cannot be used here due to the need of prefix match on keys. */
338
Kenny Root655b9582013-04-04 08:37:42 -0700339static size_t encode_key_length(const android::String8& keyName) {
340 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
341 size_t length = keyName.length();
342 for (int i = length; i > 0; --i, ++in) {
343 if (*in < '0' || *in > '~') {
344 ++length;
345 }
346 }
347 return length;
348}
349
Kenny Root07438c82012-11-02 15:41:02 -0700350static int encode_key(char* out, const android::String8& keyName) {
351 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
352 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800353 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700354 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800355 *out = '+' + (*in >> 6);
356 *++out = '0' + (*in & 0x3F);
357 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700358 } else {
359 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800360 }
361 }
362 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800363 return length;
364}
365
Kenny Root07438c82012-11-02 15:41:02 -0700366/*
367 * Converts from the "escaped" format on disk to actual name.
368 * This will be smaller than the input string.
369 *
370 * Characters that should combine with the next at the end will be truncated.
371 */
372static size_t decode_key_length(const char* in, size_t length) {
373 size_t outLength = 0;
374
375 for (const char* end = in + length; in < end; in++) {
376 /* This combines with the next character. */
377 if (*in < '0' || *in > '~') {
378 continue;
379 }
380
381 outLength++;
382 }
383 return outLength;
384}
385
386static void decode_key(char* out, const char* in, size_t length) {
387 for (const char* end = in + length; in < end; in++) {
388 if (*in < '0' || *in > '~') {
389 /* Truncate combining characters at the end. */
390 if (in + 1 >= end) {
391 break;
392 }
393
394 *out = (*in++ - '+') << 6;
395 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800396 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700397 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800398 }
399 }
400 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800401}
402
403static size_t readFully(int fd, uint8_t* data, size_t size) {
404 size_t remaining = size;
405 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800406 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800407 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800408 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800409 }
410 data += n;
411 remaining -= n;
412 }
413 return size;
414}
415
416static size_t writeFully(int fd, uint8_t* data, size_t size) {
417 size_t remaining = size;
418 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800419 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
420 if (n < 0) {
421 ALOGW("write failed: %s", strerror(errno));
422 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800423 }
424 data += n;
425 remaining -= n;
426 }
427 return size;
428}
429
430class Entropy {
431public:
432 Entropy() : mRandom(-1) {}
433 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800434 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800435 close(mRandom);
436 }
437 }
438
439 bool open() {
440 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800441 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
442 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800443 ALOGE("open: %s: %s", randomDevice, strerror(errno));
444 return false;
445 }
446 return true;
447 }
448
Kenny Root51878182012-03-13 12:53:19 -0700449 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800450 return (readFully(mRandom, data, size) == size);
451 }
452
453private:
454 int mRandom;
455};
456
457/* Here is the file format. There are two parts in blob.value, the secret and
458 * the description. The secret is stored in ciphertext, and its original size
459 * can be found in blob.length. The description is stored after the secret in
460 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700461 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700462 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800463 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
464 * and decryptBlob(). Thus they should not be accessed from outside. */
465
Kenny Root822c3a92012-03-23 16:34:39 -0700466/* ** Note to future implementors of encryption: **
467 * Currently this is the construction:
468 * metadata || Enc(MD5(data) || data)
469 *
470 * This should be the construction used for encrypting if re-implementing:
471 *
472 * Derive independent keys for encryption and MAC:
473 * Kenc = AES_encrypt(masterKey, "Encrypt")
474 * Kmac = AES_encrypt(masterKey, "MAC")
475 *
476 * Store this:
477 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
478 * HMAC(Kmac, metadata || Enc(data))
479 */
Kenny Roota91203b2012-02-15 15:00:46 -0800480struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700481 uint8_t version;
482 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700483 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800484 uint8_t info;
485 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700486 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800487 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700488 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800489 int32_t length; // in network byte order when encrypted
490 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
491};
492
Kenny Root822c3a92012-03-23 16:34:39 -0700493typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700494 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700495 TYPE_GENERIC = 1,
496 TYPE_MASTER_KEY = 2,
497 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800498 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700499} BlobType;
500
Kenny Rootf9119d62013-04-03 09:22:15 -0700501static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700502
Kenny Roota91203b2012-02-15 15:00:46 -0800503class Blob {
504public:
Kenny Root07438c82012-11-02 15:41:02 -0700505 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
506 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800507 mBlob.length = valueLength;
508 memcpy(mBlob.value, value, valueLength);
509
510 mBlob.info = infoLength;
511 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700512
Kenny Root07438c82012-11-02 15:41:02 -0700513 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700514 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700515
Kenny Rootee8068b2013-10-07 09:49:15 -0700516 if (type == TYPE_MASTER_KEY) {
517 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
518 } else {
519 mBlob.flags = KEYSTORE_FLAG_NONE;
520 }
Kenny Roota91203b2012-02-15 15:00:46 -0800521 }
522
523 Blob(blob b) {
524 mBlob = b;
525 }
526
527 Blob() {}
528
Kenny Root51878182012-03-13 12:53:19 -0700529 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800530 return mBlob.value;
531 }
532
Kenny Root51878182012-03-13 12:53:19 -0700533 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800534 return mBlob.length;
535 }
536
Kenny Root51878182012-03-13 12:53:19 -0700537 const uint8_t* getInfo() const {
538 return mBlob.value + mBlob.length;
539 }
540
541 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800542 return mBlob.info;
543 }
544
Kenny Root822c3a92012-03-23 16:34:39 -0700545 uint8_t getVersion() const {
546 return mBlob.version;
547 }
548
Kenny Rootf9119d62013-04-03 09:22:15 -0700549 bool isEncrypted() const {
550 if (mBlob.version < 2) {
551 return true;
552 }
553
554 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
555 }
556
557 void setEncrypted(bool encrypted) {
558 if (encrypted) {
559 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
560 } else {
561 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
562 }
563 }
564
Kenny Root17208e02013-09-04 13:56:03 -0700565 bool isFallback() const {
566 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
567 }
568
569 void setFallback(bool fallback) {
570 if (fallback) {
571 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
572 } else {
573 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
574 }
575 }
576
Kenny Root822c3a92012-03-23 16:34:39 -0700577 void setVersion(uint8_t version) {
578 mBlob.version = version;
579 }
580
581 BlobType getType() const {
582 return BlobType(mBlob.type);
583 }
584
585 void setType(BlobType type) {
586 mBlob.type = uint8_t(type);
587 }
588
Kenny Rootf9119d62013-04-03 09:22:15 -0700589 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
590 ALOGV("writing blob %s", filename);
591 if (isEncrypted()) {
592 if (state != STATE_NO_ERROR) {
593 ALOGD("couldn't insert encrypted blob while not unlocked");
594 return LOCKED;
595 }
596
597 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
598 ALOGW("Could not read random data for: %s", filename);
599 return SYSTEM_ERROR;
600 }
Kenny Roota91203b2012-02-15 15:00:46 -0800601 }
602
603 // data includes the value and the value's length
604 size_t dataLength = mBlob.length + sizeof(mBlob.length);
605 // pad data to the AES_BLOCK_SIZE
606 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
607 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
608 // encrypted data includes the digest value
609 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
610 // move info after space for padding
611 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
612 // zero padding area
613 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
614
615 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800616
Kenny Rootf9119d62013-04-03 09:22:15 -0700617 if (isEncrypted()) {
618 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800619
Kenny Rootf9119d62013-04-03 09:22:15 -0700620 uint8_t vector[AES_BLOCK_SIZE];
621 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
622 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
623 aes_key, vector, AES_ENCRYPT);
624 }
625
Kenny Roota91203b2012-02-15 15:00:46 -0800626 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
627 size_t fileLength = encryptedLength + headerLength + mBlob.info;
628
629 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800630 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
631 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
632 if (out < 0) {
633 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800634 return SYSTEM_ERROR;
635 }
636 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
637 if (close(out) != 0) {
638 return SYSTEM_ERROR;
639 }
640 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800641 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800642 unlink(tmpFileName);
643 return SYSTEM_ERROR;
644 }
Kenny Root150ca932012-11-14 14:29:02 -0800645 if (rename(tmpFileName, filename) == -1) {
646 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
647 return SYSTEM_ERROR;
648 }
649 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800650 }
651
Kenny Rootf9119d62013-04-03 09:22:15 -0700652 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
653 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800654 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
655 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800656 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
657 }
658 // fileLength may be less than sizeof(mBlob) since the in
659 // memory version has extra padding to tolerate rounding up to
660 // the AES_BLOCK_SIZE
661 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
662 if (close(in) != 0) {
663 return SYSTEM_ERROR;
664 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700665
666 if (isEncrypted() && (state != STATE_NO_ERROR)) {
667 return LOCKED;
668 }
669
Kenny Roota91203b2012-02-15 15:00:46 -0800670 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
671 if (fileLength < headerLength) {
672 return VALUE_CORRUPTED;
673 }
674
675 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700676 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800677 return VALUE_CORRUPTED;
678 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700679
680 ssize_t digestedLength;
681 if (isEncrypted()) {
682 if (encryptedLength % AES_BLOCK_SIZE != 0) {
683 return VALUE_CORRUPTED;
684 }
685
686 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
687 mBlob.vector, AES_DECRYPT);
688 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
689 uint8_t computedDigest[MD5_DIGEST_LENGTH];
690 MD5(mBlob.digested, digestedLength, computedDigest);
691 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
692 return VALUE_CORRUPTED;
693 }
694 } else {
695 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800696 }
697
698 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
699 mBlob.length = ntohl(mBlob.length);
700 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
701 return VALUE_CORRUPTED;
702 }
703 if (mBlob.info != 0) {
704 // move info from after padding to after data
705 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
706 }
Kenny Root07438c82012-11-02 15:41:02 -0700707 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800708 }
709
710private:
711 struct blob mBlob;
712};
713
Kenny Root655b9582013-04-04 08:37:42 -0700714class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800715public:
Kenny Root655b9582013-04-04 08:37:42 -0700716 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
717 asprintf(&mUserDir, "user_%u", mUserId);
718 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
719 }
720
721 ~UserState() {
722 free(mUserDir);
723 free(mMasterKeyFile);
724 }
725
726 bool initialize() {
727 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
728 ALOGE("Could not create directory '%s'", mUserDir);
729 return false;
730 }
731
732 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800733 setState(STATE_LOCKED);
734 } else {
735 setState(STATE_UNINITIALIZED);
736 }
Kenny Root70e3a862012-02-15 17:20:23 -0800737
Kenny Root655b9582013-04-04 08:37:42 -0700738 return true;
739 }
740
741 uid_t getUserId() const {
742 return mUserId;
743 }
744
745 const char* getUserDirName() const {
746 return mUserDir;
747 }
748
749 const char* getMasterKeyFileName() const {
750 return mMasterKeyFile;
751 }
752
753 void setState(State state) {
754 mState = state;
755 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
756 mRetry = MAX_RETRY;
757 }
Kenny Roota91203b2012-02-15 15:00:46 -0800758 }
759
Kenny Root51878182012-03-13 12:53:19 -0700760 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800761 return mState;
762 }
763
Kenny Root51878182012-03-13 12:53:19 -0700764 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800765 return mRetry;
766 }
767
Kenny Root655b9582013-04-04 08:37:42 -0700768 void zeroizeMasterKeysInMemory() {
769 memset(mMasterKey, 0, sizeof(mMasterKey));
770 memset(mSalt, 0, sizeof(mSalt));
771 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
772 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800773 }
774
Chad Brubakereecdd122015-05-07 10:19:40 -0700775 bool deleteMasterKey() {
776 setState(STATE_UNINITIALIZED);
777 zeroizeMasterKeysInMemory();
778 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
779 }
780
Kenny Root655b9582013-04-04 08:37:42 -0700781 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
782 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800783 return SYSTEM_ERROR;
784 }
Kenny Root655b9582013-04-04 08:37:42 -0700785 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800786 if (response != NO_ERROR) {
787 return response;
788 }
789 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700790 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800791 }
792
Robin Lee4e865752014-08-19 17:37:55 +0100793 ResponseCode copyMasterKey(UserState* src) {
794 if (mState != STATE_UNINITIALIZED) {
795 return ::SYSTEM_ERROR;
796 }
797 if (src->getState() != STATE_NO_ERROR) {
798 return ::SYSTEM_ERROR;
799 }
800 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
801 setupMasterKeys();
802 return ::NO_ERROR;
803 }
804
Kenny Root655b9582013-04-04 08:37:42 -0700805 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800806 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
807 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
808 AES_KEY passwordAesKey;
809 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700810 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700811 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800812 }
813
Kenny Root655b9582013-04-04 08:37:42 -0700814 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
815 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800816 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800817 return SYSTEM_ERROR;
818 }
819
820 // we read the raw blob to just to get the salt to generate
821 // the AES key, then we create the Blob to use with decryptBlob
822 blob rawBlob;
823 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
824 if (close(in) != 0) {
825 return SYSTEM_ERROR;
826 }
827 // find salt at EOF if present, otherwise we have an old file
828 uint8_t* salt;
829 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
830 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
831 } else {
832 salt = NULL;
833 }
834 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
835 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
836 AES_KEY passwordAesKey;
837 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
838 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700839 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
840 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800841 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700842 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800843 }
844 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
845 // if salt was missing, generate one and write a new master key file with the salt.
846 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700847 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800848 return SYSTEM_ERROR;
849 }
Kenny Root655b9582013-04-04 08:37:42 -0700850 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800851 }
852 if (response == NO_ERROR) {
853 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
854 setupMasterKeys();
855 }
856 return response;
857 }
858 if (mRetry <= 0) {
859 reset();
860 return UNINITIALIZED;
861 }
862 --mRetry;
863 switch (mRetry) {
864 case 0: return WRONG_PASSWORD_0;
865 case 1: return WRONG_PASSWORD_1;
866 case 2: return WRONG_PASSWORD_2;
867 case 3: return WRONG_PASSWORD_3;
868 default: return WRONG_PASSWORD_3;
869 }
870 }
871
Kenny Root655b9582013-04-04 08:37:42 -0700872 AES_KEY* getEncryptionKey() {
873 return &mMasterKeyEncryption;
874 }
875
876 AES_KEY* getDecryptionKey() {
877 return &mMasterKeyDecryption;
878 }
879
Kenny Roota91203b2012-02-15 15:00:46 -0800880 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700881 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800882 if (!dir) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700883 // If the directory doesn't exist then nothing to do.
884 if (errno == ENOENT) {
885 return true;
886 }
Kenny Root655b9582013-04-04 08:37:42 -0700887 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800888 return false;
889 }
Kenny Root655b9582013-04-04 08:37:42 -0700890
891 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800892 while ((file = readdir(dir)) != NULL) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700893 // skip . and ..
894 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700895 continue;
896 }
897
898 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800899 }
900 closedir(dir);
901 return true;
902 }
903
Kenny Root655b9582013-04-04 08:37:42 -0700904private:
905 static const int MASTER_KEY_SIZE_BYTES = 16;
906 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
907
908 static const int MAX_RETRY = 4;
909 static const size_t SALT_SIZE = 16;
910
911 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
912 uint8_t* salt) {
913 size_t saltSize;
914 if (salt != NULL) {
915 saltSize = SALT_SIZE;
916 } else {
917 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
918 salt = (uint8_t*) "keystore";
919 // sizeof = 9, not strlen = 8
920 saltSize = sizeof("keystore");
921 }
922
923 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
924 saltSize, 8192, keySize, key);
925 }
926
927 bool generateSalt(Entropy* entropy) {
928 return entropy->generate_random_data(mSalt, sizeof(mSalt));
929 }
930
931 bool generateMasterKey(Entropy* entropy) {
932 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
933 return false;
934 }
935 if (!generateSalt(entropy)) {
936 return false;
937 }
938 return true;
939 }
940
941 void setupMasterKeys() {
942 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
943 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
944 setState(STATE_NO_ERROR);
945 }
946
947 uid_t mUserId;
948
949 char* mUserDir;
950 char* mMasterKeyFile;
951
952 State mState;
953 int8_t mRetry;
954
955 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
956 uint8_t mSalt[SALT_SIZE];
957
958 AES_KEY mMasterKeyEncryption;
959 AES_KEY mMasterKeyDecryption;
960};
961
962typedef struct {
963 uint32_t uid;
964 const uint8_t* filename;
965} grant_t;
966
967class KeyStore {
968public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800969 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700970 : mEntropy(entropy)
971 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800972 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700973 {
974 memset(&mMetaData, '\0', sizeof(mMetaData));
975 }
976
977 ~KeyStore() {
978 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
979 it != mGrants.end(); it++) {
980 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700981 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800982 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700983
984 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
985 it != mMasterKeys.end(); it++) {
986 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700987 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800988 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700989 }
990
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800991 /**
992 * Depending on the hardware keymaster version is this may return a
993 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
994 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
995 * be guarded by a check on the device's version.
996 */
997 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700998 return mDevice;
999 }
1000
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001001 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001002 return mFallbackDevice;
1003 }
1004
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001005 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001006 return blob.isFallback() ? mFallbackDevice: mDevice;
1007 }
1008
Kenny Root655b9582013-04-04 08:37:42 -07001009 ResponseCode initialize() {
1010 readMetaData();
1011 if (upgradeKeystore()) {
1012 writeMetaData();
1013 }
1014
1015 return ::NO_ERROR;
1016 }
1017
1018 State getState(uid_t uid) {
1019 return getUserState(uid)->getState();
1020 }
1021
1022 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1023 UserState* userState = getUserState(uid);
1024 return userState->initialize(pw, mEntropy);
1025 }
1026
Robin Lee4e865752014-08-19 17:37:55 +01001027 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1028 UserState *userState = getUserState(uid);
1029 UserState *initState = getUserState(src);
1030 return userState->copyMasterKey(initState);
1031 }
1032
Kenny Root655b9582013-04-04 08:37:42 -07001033 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001034 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001035 return userState->writeMasterKey(pw, mEntropy);
1036 }
1037
1038 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001039 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001040 return userState->readMasterKey(pw, mEntropy);
1041 }
1042
1043 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001044 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001045 encode_key(encoded, keyName);
1046 return android::String8(encoded);
1047 }
1048
1049 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001050 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001051 encode_key(encoded, keyName);
1052 return android::String8::format("%u_%s", uid, encoded);
1053 }
1054
1055 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001056 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001057 encode_key(encoded, keyName);
1058 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1059 encoded);
1060 }
1061
Chad Brubakereecdd122015-05-07 10:19:40 -07001062 /*
1063 * Delete entries owned by userId. If keepUnencryptedEntries is true
1064 * then only encrypted entries will be removed, otherwise all entries will
1065 * be removed.
1066 */
1067 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001068 android::String8 prefix("");
1069 android::Vector<android::String16> aliases;
Chad Brubakereecdd122015-05-07 10:19:40 -07001070 uid_t uid = get_uid(userId, AID_SYSTEM);
Kenny Root655b9582013-04-04 08:37:42 -07001071 UserState* userState = getUserState(uid);
Chad Brubakereecdd122015-05-07 10:19:40 -07001072 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1073 return;
1074 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001075 for (uint32_t i = 0; i < aliases.size(); i++) {
1076 android::String8 filename(aliases[i]);
1077 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubakereecdd122015-05-07 10:19:40 -07001078 getKeyName(filename).string());
1079 bool shouldDelete = true;
1080 if (keepUnenryptedEntries) {
1081 Blob blob;
1082 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001083
Chad Brubakereecdd122015-05-07 10:19:40 -07001084 /* get can fail if the blob is encrypted and the state is
1085 * not unlocked, only skip deleting blobs that were loaded and
1086 * who are not encrypted. If there are blobs we fail to read for
1087 * other reasons err on the safe side and delete them since we
1088 * can't tell if they're encrypted.
1089 */
1090 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1091 }
1092 if (shouldDelete) {
1093 del(filename, ::TYPE_ANY, uid);
1094 }
1095 }
1096 if (!userState->deleteMasterKey()) {
1097 ALOGE("Failed to delete user %d's master key", userId);
1098 }
1099 if (!keepUnenryptedEntries) {
1100 if(!userState->reset()) {
1101 ALOGE("Failed to remove user %d's directory", userId);
1102 }
1103 }
Kenny Root655b9582013-04-04 08:37:42 -07001104 }
1105
1106 bool isEmpty(uid_t uid) const {
1107 const UserState* userState = getUserState(uid);
Chad Brubakereecdd122015-05-07 10:19:40 -07001108 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001109 return true;
1110 }
1111
1112 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001113 if (!dir) {
1114 return true;
1115 }
Kenny Root31e27462014-09-10 11:28:03 -07001116
Kenny Roota91203b2012-02-15 15:00:46 -08001117 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001118 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001119 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001120 // We only care about files.
1121 if (file->d_type != DT_REG) {
1122 continue;
1123 }
1124
1125 // Skip anything that starts with a "."
1126 if (file->d_name[0] == '.') {
1127 continue;
1128 }
1129
Kenny Root31e27462014-09-10 11:28:03 -07001130 result = false;
1131 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001132 }
1133 closedir(dir);
1134 return result;
1135 }
1136
Kenny Root655b9582013-04-04 08:37:42 -07001137 void lock(uid_t uid) {
1138 UserState* userState = getUserState(uid);
1139 userState->zeroizeMasterKeysInMemory();
1140 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001141 }
1142
Kenny Root655b9582013-04-04 08:37:42 -07001143 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1144 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001145 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1146 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001147 if (rc != NO_ERROR) {
1148 return rc;
1149 }
1150
1151 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001152 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001153 /* If we upgrade the key, we need to write it to disk again. Then
1154 * it must be read it again since the blob is encrypted each time
1155 * it's written.
1156 */
Kenny Root655b9582013-04-04 08:37:42 -07001157 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1158 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001159 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1160 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001161 return rc;
1162 }
1163 }
Kenny Root822c3a92012-03-23 16:34:39 -07001164 }
1165
Kenny Root17208e02013-09-04 13:56:03 -07001166 /*
1167 * This will upgrade software-backed keys to hardware-backed keys when
1168 * the HAL for the device supports the newer key types.
1169 */
1170 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1171 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1172 && keyBlob->isFallback()) {
1173 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1174 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1175
1176 // The HAL allowed the import, reget the key to have the "fresh"
1177 // version.
1178 if (imported == NO_ERROR) {
1179 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1180 }
1181 }
1182
Kenny Rootd53bc922013-03-21 14:10:15 -07001183 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001184 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1185 return KEY_NOT_FOUND;
1186 }
1187
1188 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001189 }
1190
Kenny Root655b9582013-04-04 08:37:42 -07001191 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1192 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001193 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1194 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001195 }
1196
Robin Lee4b84fdc2014-09-24 11:56:57 +01001197 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1198 Blob keyBlob;
1199 ResponseCode rc = get(filename, &keyBlob, type, uid);
1200 if (rc != ::NO_ERROR) {
1201 return rc;
1202 }
1203
1204 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1205 // A device doesn't have to implement delete_keypair.
1206 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1207 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1208 rc = ::SYSTEM_ERROR;
1209 }
1210 }
1211 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001212 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1213 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1214 if (dev->delete_key) {
1215 keymaster_key_blob_t blob;
1216 blob.key_material = keyBlob.getValue();
1217 blob.key_material_size = keyBlob.getLength();
1218 dev->delete_key(dev, &blob);
1219 }
1220 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001221 if (rc != ::NO_ERROR) {
1222 return rc;
1223 }
1224
1225 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1226 }
1227
1228 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1229 uid_t uid) {
1230
1231 UserState* userState = getUserState(uid);
1232 size_t n = prefix.length();
1233
1234 DIR* dir = opendir(userState->getUserDirName());
1235 if (!dir) {
1236 ALOGW("can't open directory for user: %s", strerror(errno));
1237 return ::SYSTEM_ERROR;
1238 }
1239
1240 struct dirent* file;
1241 while ((file = readdir(dir)) != NULL) {
1242 // We only care about files.
1243 if (file->d_type != DT_REG) {
1244 continue;
1245 }
1246
1247 // Skip anything that starts with a "."
1248 if (file->d_name[0] == '.') {
1249 continue;
1250 }
1251
1252 if (!strncmp(prefix.string(), file->d_name, n)) {
1253 const char* p = &file->d_name[n];
1254 size_t plen = strlen(p);
1255
1256 size_t extra = decode_key_length(p, plen);
1257 char *match = (char*) malloc(extra + 1);
1258 if (match != NULL) {
1259 decode_key(match, p, plen);
1260 matches->push(android::String16(match, extra));
1261 free(match);
1262 } else {
1263 ALOGW("could not allocate match of size %zd", extra);
1264 }
1265 }
1266 }
1267 closedir(dir);
1268 return ::NO_ERROR;
1269 }
1270
Kenny Root07438c82012-11-02 15:41:02 -07001271 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001272 const grant_t* existing = getGrant(filename, granteeUid);
1273 if (existing == NULL) {
1274 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001275 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001276 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001277 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001278 }
1279 }
1280
Kenny Root07438c82012-11-02 15:41:02 -07001281 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001282 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1283 it != mGrants.end(); it++) {
1284 grant_t* grant = *it;
1285 if (grant->uid == granteeUid
1286 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1287 mGrants.erase(it);
1288 return true;
1289 }
Kenny Root70e3a862012-02-15 17:20:23 -08001290 }
Kenny Root70e3a862012-02-15 17:20:23 -08001291 return false;
1292 }
1293
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001294 bool hasGrant(const char* filename, const uid_t uid) const {
1295 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001296 }
1297
Kenny Rootf9119d62013-04-03 09:22:15 -07001298 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1299 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001300 uint8_t* data;
1301 size_t dataLength;
1302 int rc;
1303
1304 if (mDevice->import_keypair == NULL) {
1305 ALOGE("Keymaster doesn't support import!");
1306 return SYSTEM_ERROR;
1307 }
1308
Kenny Root17208e02013-09-04 13:56:03 -07001309 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001310 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001311 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001312 /*
1313 * Maybe the device doesn't support this type of key. Try to use the
1314 * software fallback keymaster implementation. This is a little bit
1315 * lazier than checking the PKCS#8 key type, but the software
1316 * implementation will do that anyway.
1317 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001318 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001319 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001320
1321 if (rc) {
1322 ALOGE("Error while importing keypair: %d", rc);
1323 return SYSTEM_ERROR;
1324 }
Kenny Root822c3a92012-03-23 16:34:39 -07001325 }
1326
1327 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1328 free(data);
1329
Kenny Rootf9119d62013-04-03 09:22:15 -07001330 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001331 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001332
Kenny Root655b9582013-04-04 08:37:42 -07001333 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001334 }
1335
Kenny Root1b0e3932013-09-05 13:06:32 -07001336 bool isHardwareBacked(const android::String16& keyType) const {
1337 if (mDevice == NULL) {
1338 ALOGW("can't get keymaster device");
1339 return false;
1340 }
1341
1342 if (sRSAKeyType == keyType) {
1343 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1344 } else {
1345 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1346 && (mDevice->common.module->module_api_version
1347 >= KEYMASTER_MODULE_API_VERSION_0_2);
1348 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001349 }
1350
Kenny Root655b9582013-04-04 08:37:42 -07001351 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1352 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001353 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001354
1355 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1356 if (responseCode == NO_ERROR) {
1357 return responseCode;
1358 }
1359
1360 // If this is one of the legacy UID->UID mappings, use it.
1361 uid_t euid = get_keystore_euid(uid);
1362 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001363 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001364 responseCode = get(filepath8.string(), keyBlob, type, uid);
1365 if (responseCode == NO_ERROR) {
1366 return responseCode;
1367 }
1368 }
1369
1370 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001371 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001372 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001373 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001374 if (end[0] != '_' || end[1] == 0) {
1375 return KEY_NOT_FOUND;
1376 }
Kenny Root86b16e82013-09-09 11:15:54 -07001377 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1378 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001379 if (!hasGrant(filepath8.string(), uid)) {
1380 return responseCode;
1381 }
1382
1383 // It is a granted key. Try to load it.
1384 return get(filepath8.string(), keyBlob, type, uid);
1385 }
1386
1387 /**
1388 * Returns any existing UserState or creates it if it doesn't exist.
1389 */
1390 UserState* getUserState(uid_t uid) {
1391 uid_t userId = get_user_id(uid);
1392
1393 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1394 it != mMasterKeys.end(); it++) {
1395 UserState* state = *it;
1396 if (state->getUserId() == userId) {
1397 return state;
1398 }
1399 }
1400
1401 UserState* userState = new UserState(userId);
1402 if (!userState->initialize()) {
1403 /* There's not much we can do if initialization fails. Trying to
1404 * unlock the keystore for that user will fail as well, so any
1405 * subsequent request for this user will just return SYSTEM_ERROR.
1406 */
1407 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1408 }
1409 mMasterKeys.add(userState);
1410 return userState;
1411 }
1412
1413 /**
1414 * Returns NULL if the UserState doesn't already exist.
1415 */
1416 const UserState* getUserState(uid_t uid) const {
1417 uid_t userId = get_user_id(uid);
1418
1419 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1420 it != mMasterKeys.end(); it++) {
1421 UserState* state = *it;
1422 if (state->getUserId() == userId) {
1423 return state;
1424 }
1425 }
1426
1427 return NULL;
1428 }
1429
Kenny Roota91203b2012-02-15 15:00:46 -08001430private:
Kenny Root655b9582013-04-04 08:37:42 -07001431 static const char* sOldMasterKey;
1432 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001433 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001434 Entropy* mEntropy;
1435
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001436 keymaster1_device_t* mDevice;
1437 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001438
Kenny Root655b9582013-04-04 08:37:42 -07001439 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001440
Kenny Root655b9582013-04-04 08:37:42 -07001441 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001442
Kenny Root655b9582013-04-04 08:37:42 -07001443 typedef struct {
1444 uint32_t version;
1445 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001446
Kenny Root655b9582013-04-04 08:37:42 -07001447 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001448
Kenny Root655b9582013-04-04 08:37:42 -07001449 const grant_t* getGrant(const char* filename, uid_t uid) const {
1450 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1451 it != mGrants.end(); it++) {
1452 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001453 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001454 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001455 return grant;
1456 }
1457 }
Kenny Root70e3a862012-02-15 17:20:23 -08001458 return NULL;
1459 }
1460
Kenny Root822c3a92012-03-23 16:34:39 -07001461 /**
1462 * Upgrade code. This will upgrade the key from the current version
1463 * to whatever is newest.
1464 */
Kenny Root655b9582013-04-04 08:37:42 -07001465 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1466 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001467 bool updated = false;
1468 uint8_t version = oldVersion;
1469
1470 /* From V0 -> V1: All old types were unknown */
1471 if (version == 0) {
1472 ALOGV("upgrading to version 1 and setting type %d", type);
1473
1474 blob->setType(type);
1475 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001476 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001477 }
1478 version = 1;
1479 updated = true;
1480 }
1481
Kenny Rootf9119d62013-04-03 09:22:15 -07001482 /* From V1 -> V2: All old keys were encrypted */
1483 if (version == 1) {
1484 ALOGV("upgrading to version 2");
1485
1486 blob->setEncrypted(true);
1487 version = 2;
1488 updated = true;
1489 }
1490
Kenny Root822c3a92012-03-23 16:34:39 -07001491 /*
1492 * If we've updated, set the key blob to the right version
1493 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001494 */
Kenny Root822c3a92012-03-23 16:34:39 -07001495 if (updated) {
1496 ALOGV("updated and writing file %s", filename);
1497 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001498 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001499
1500 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001501 }
1502
1503 /**
1504 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1505 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1506 * Then it overwrites the original blob with the new blob
1507 * format that is returned from the keymaster.
1508 */
Kenny Root655b9582013-04-04 08:37:42 -07001509 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001510 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1511 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1512 if (b.get() == NULL) {
1513 ALOGE("Problem instantiating BIO");
1514 return SYSTEM_ERROR;
1515 }
1516
1517 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1518 if (pkey.get() == NULL) {
1519 ALOGE("Couldn't read old PEM file");
1520 return SYSTEM_ERROR;
1521 }
1522
1523 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1524 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1525 if (len < 0) {
1526 ALOGE("Couldn't measure PKCS#8 length");
1527 return SYSTEM_ERROR;
1528 }
1529
Kenny Root70c98892013-02-07 09:10:36 -08001530 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1531 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001532 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1533 ALOGE("Couldn't convert to PKCS#8");
1534 return SYSTEM_ERROR;
1535 }
1536
Kenny Rootf9119d62013-04-03 09:22:15 -07001537 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1538 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001539 if (rc != NO_ERROR) {
1540 return rc;
1541 }
1542
Kenny Root655b9582013-04-04 08:37:42 -07001543 return get(filename, blob, TYPE_KEY_PAIR, uid);
1544 }
1545
1546 void readMetaData() {
1547 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1548 if (in < 0) {
1549 return;
1550 }
1551 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1552 if (fileLength != sizeof(mMetaData)) {
1553 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1554 sizeof(mMetaData));
1555 }
1556 close(in);
1557 }
1558
1559 void writeMetaData() {
1560 const char* tmpFileName = ".metadata.tmp";
1561 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1562 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1563 if (out < 0) {
1564 ALOGE("couldn't write metadata file: %s", strerror(errno));
1565 return;
1566 }
1567 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1568 if (fileLength != sizeof(mMetaData)) {
1569 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1570 sizeof(mMetaData));
1571 }
1572 close(out);
1573 rename(tmpFileName, sMetaDataFile);
1574 }
1575
1576 bool upgradeKeystore() {
1577 bool upgraded = false;
1578
1579 if (mMetaData.version == 0) {
1580 UserState* userState = getUserState(0);
1581
1582 // Initialize first so the directory is made.
1583 userState->initialize();
1584
1585 // Migrate the old .masterkey file to user 0.
1586 if (access(sOldMasterKey, R_OK) == 0) {
1587 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1588 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1589 return false;
1590 }
1591 }
1592
1593 // Initialize again in case we had a key.
1594 userState->initialize();
1595
1596 // Try to migrate existing keys.
1597 DIR* dir = opendir(".");
1598 if (!dir) {
1599 // Give up now; maybe we can upgrade later.
1600 ALOGE("couldn't open keystore's directory; something is wrong");
1601 return false;
1602 }
1603
1604 struct dirent* file;
1605 while ((file = readdir(dir)) != NULL) {
1606 // We only care about files.
1607 if (file->d_type != DT_REG) {
1608 continue;
1609 }
1610
1611 // Skip anything that starts with a "."
1612 if (file->d_name[0] == '.') {
1613 continue;
1614 }
1615
1616 // Find the current file's user.
1617 char* end;
1618 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1619 if (end[0] != '_' || end[1] == 0) {
1620 continue;
1621 }
1622 UserState* otherUser = getUserState(thisUid);
1623 if (otherUser->getUserId() != 0) {
1624 unlinkat(dirfd(dir), file->d_name, 0);
1625 }
1626
1627 // Rename the file into user directory.
1628 DIR* otherdir = opendir(otherUser->getUserDirName());
1629 if (otherdir == NULL) {
1630 ALOGW("couldn't open user directory for rename");
1631 continue;
1632 }
1633 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1634 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1635 }
1636 closedir(otherdir);
1637 }
1638 closedir(dir);
1639
1640 mMetaData.version = 1;
1641 upgraded = true;
1642 }
1643
1644 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001645 }
Kenny Roota91203b2012-02-15 15:00:46 -08001646};
1647
Kenny Root655b9582013-04-04 08:37:42 -07001648const char* KeyStore::sOldMasterKey = ".masterkey";
1649const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001650
Kenny Root1b0e3932013-09-05 13:06:32 -07001651const android::String16 KeyStore::sRSAKeyType("RSA");
1652
Kenny Root07438c82012-11-02 15:41:02 -07001653namespace android {
1654class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1655public:
1656 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001657 : mKeyStore(keyStore),
1658 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001659 {
Kenny Roota91203b2012-02-15 15:00:46 -08001660 }
Kenny Roota91203b2012-02-15 15:00:46 -08001661
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001662 void binderDied(const wp<IBinder>& who) {
1663 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1664 for (auto token: operations) {
1665 abort(token);
1666 }
Kenny Root822c3a92012-03-23 16:34:39 -07001667 }
Kenny Roota91203b2012-02-15 15:00:46 -08001668
Kenny Root07438c82012-11-02 15:41:02 -07001669 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001670 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001671 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001672 }
Kenny Roota91203b2012-02-15 15:00:46 -08001673
Chad Brubaker9489b792015-04-14 11:01:45 -07001674 return mKeyStore->getState(IPCThreadState::self()->getCallingUid());
Kenny Root298e7b12012-03-26 13:54:44 -07001675 }
1676
Kenny Root07438c82012-11-02 15:41:02 -07001677 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001678 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001679 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001680 }
Kenny Root07438c82012-11-02 15:41:02 -07001681
Chad Brubaker9489b792015-04-14 11:01:45 -07001682 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001683 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001684 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001685
Kenny Root655b9582013-04-04 08:37:42 -07001686 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001687 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001688 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001689 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001690 *item = NULL;
1691 *itemLength = 0;
1692 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001693 }
Kenny Roota91203b2012-02-15 15:00:46 -08001694
Kenny Root07438c82012-11-02 15:41:02 -07001695 *item = (uint8_t*) malloc(keyBlob.getLength());
1696 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1697 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001698
Kenny Root07438c82012-11-02 15:41:02 -07001699 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001700 }
1701
Kenny Rootf9119d62013-04-03 09:22:15 -07001702 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1703 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001704 targetUid = getEffectiveUid(targetUid);
1705 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1706 flags & KEYSTORE_FLAG_ENCRYPTED);
1707 if (result != ::NO_ERROR) {
1708 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001709 }
1710
Kenny Root07438c82012-11-02 15:41:02 -07001711 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001712 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001713
1714 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001715 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1716
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001717 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001718 }
1719
Kenny Root49468902013-03-19 13:41:33 -07001720 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001721 targetUid = getEffectiveUid(targetUid);
1722 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001723 return ::PERMISSION_DENIED;
1724 }
Kenny Root07438c82012-11-02 15:41:02 -07001725 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001726 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001727 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001728 }
1729
Kenny Root49468902013-03-19 13:41:33 -07001730 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001731 targetUid = getEffectiveUid(targetUid);
1732 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001733 return ::PERMISSION_DENIED;
1734 }
1735
Kenny Root07438c82012-11-02 15:41:02 -07001736 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001737 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001738
Kenny Root655b9582013-04-04 08:37:42 -07001739 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001740 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1741 }
1742 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001743 }
1744
Kenny Root49468902013-03-19 13:41:33 -07001745 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001746 targetUid = getEffectiveUid(targetUid);
1747 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001748 return ::PERMISSION_DENIED;
1749 }
Kenny Root07438c82012-11-02 15:41:02 -07001750 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001751 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001752
Robin Lee4b84fdc2014-09-24 11:56:57 +01001753 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1754 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001755 }
Kenny Root07438c82012-11-02 15:41:02 -07001756 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001757 }
1758
Kenny Root07438c82012-11-02 15:41:02 -07001759 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001760 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001761 return ::PERMISSION_DENIED;
1762 }
1763
Chad Brubaker9489b792015-04-14 11:01:45 -07001764 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubakereecdd122015-05-07 10:19:40 -07001765 mKeyStore->resetUser(get_user_id(callingUid), false);
1766 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001767 }
1768
Chad Brubakereecdd122015-05-07 10:19:40 -07001769 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001770 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001771 return ::PERMISSION_DENIED;
1772 }
Kenny Root70e3a862012-02-15 17:20:23 -08001773
Kenny Root07438c82012-11-02 15:41:02 -07001774 const String8 password8(password);
Chad Brubakereecdd122015-05-07 10:19:40 -07001775 uid_t uid = get_uid(userId, AID_SYSTEM);
Kenny Root70e3a862012-02-15 17:20:23 -08001776
Chad Brubakereecdd122015-05-07 10:19:40 -07001777 // Flush the auth token table to prevent stale tokens from sticking
1778 // around.
1779 mAuthTokenTable.Clear();
1780
1781 if (password.size() == 0) {
1782 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
1783 mKeyStore->resetUser(static_cast<uid_t>(userId), true);
1784 return ::NO_ERROR;
1785 } else {
1786 switch (mKeyStore->getState(uid)) {
1787 case ::STATE_UNINITIALIZED: {
1788 // generate master key, encrypt with password, write to file,
1789 // initialize mMasterKey*.
1790 return mKeyStore->initializeUser(password8, uid);
1791 }
1792 case ::STATE_NO_ERROR: {
1793 // rewrite master key with new password.
1794 return mKeyStore->writeMasterKey(password8, uid);
1795 }
1796 case ::STATE_LOCKED: {
1797 ALOGE("Changing user %d's password while locked, clearing old encryption",
1798 userId);
1799 mKeyStore->resetUser(static_cast<uid_t>(userId), true);
1800 return mKeyStore->initializeUser(password8, uid);
1801 }
Kenny Root07438c82012-11-02 15:41:02 -07001802 }
Chad Brubakereecdd122015-05-07 10:19:40 -07001803 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001804 }
Kenny Root70e3a862012-02-15 17:20:23 -08001805 }
1806
Kenny Root07438c82012-11-02 15:41:02 -07001807 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001808 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001809 return ::PERMISSION_DENIED;
1810 }
Kenny Root70e3a862012-02-15 17:20:23 -08001811
Chad Brubaker9489b792015-04-14 11:01:45 -07001812 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001813 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001814 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001815 ALOGD("calling lock in state: %d", state);
1816 return state;
1817 }
1818
Kenny Root655b9582013-04-04 08:37:42 -07001819 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001820 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001821 }
1822
Chad Brubakereecdd122015-05-07 10:19:40 -07001823 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001824 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001825 return ::PERMISSION_DENIED;
1826 }
1827
Chad Brubakereecdd122015-05-07 10:19:40 -07001828 uid_t uid = get_uid(userId, AID_SYSTEM);
1829 State state = mKeyStore->getState(uid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001830 if (state != ::STATE_LOCKED) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001831 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001832 return state;
1833 }
1834
1835 const String8 password8(pw);
Chad Brubakereecdd122015-05-07 10:19:40 -07001836 // read master key, decrypt with password, initialize mMasterKey*.
1837 return mKeyStore->readMasterKey(password8, uid);
Kenny Root70e3a862012-02-15 17:20:23 -08001838 }
1839
Kenny Root07438c82012-11-02 15:41:02 -07001840 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001841 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001842 return -1;
1843 }
Kenny Root70e3a862012-02-15 17:20:23 -08001844
Chad Brubaker9489b792015-04-14 11:01:45 -07001845 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001846 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001847 }
1848
Kenny Root96427ba2013-08-16 14:02:41 -07001849 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1850 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001851 targetUid = getEffectiveUid(targetUid);
1852 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1853 flags & KEYSTORE_FLAG_ENCRYPTED);
1854 if (result != ::NO_ERROR) {
1855 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001856 }
Kenny Root07438c82012-11-02 15:41:02 -07001857 uint8_t* data;
1858 size_t dataLength;
1859 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001860 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001861
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001862 const keymaster1_device_t* device = mKeyStore->getDevice();
1863 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001864 if (device == NULL) {
1865 return ::SYSTEM_ERROR;
1866 }
1867
1868 if (device->generate_keypair == NULL) {
1869 return ::SYSTEM_ERROR;
1870 }
1871
Kenny Root17208e02013-09-04 13:56:03 -07001872 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001873 keymaster_dsa_keygen_params_t dsa_params;
1874 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001875
Kenny Root96427ba2013-08-16 14:02:41 -07001876 if (keySize == -1) {
1877 keySize = DSA_DEFAULT_KEY_SIZE;
1878 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1879 || keySize > DSA_MAX_KEY_SIZE) {
1880 ALOGI("invalid key size %d", keySize);
1881 return ::SYSTEM_ERROR;
1882 }
1883 dsa_params.key_size = keySize;
1884
1885 if (args->size() == 3) {
1886 sp<KeystoreArg> gArg = args->itemAt(0);
1887 sp<KeystoreArg> pArg = args->itemAt(1);
1888 sp<KeystoreArg> qArg = args->itemAt(2);
1889
1890 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1891 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1892 dsa_params.generator_len = gArg->size();
1893
1894 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1895 dsa_params.prime_p_len = pArg->size();
1896
1897 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1898 dsa_params.prime_q_len = qArg->size();
1899 } else {
1900 ALOGI("not all DSA parameters were read");
1901 return ::SYSTEM_ERROR;
1902 }
1903 } else if (args->size() != 0) {
1904 ALOGI("DSA args must be 3");
1905 return ::SYSTEM_ERROR;
1906 }
1907
Kenny Root1d448c02013-11-21 10:36:53 -08001908 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001909 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1910 } else {
1911 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001912 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1913 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001914 }
1915 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001916 keymaster_ec_keygen_params_t ec_params;
1917 memset(&ec_params, '\0', sizeof(ec_params));
1918
1919 if (keySize == -1) {
1920 keySize = EC_DEFAULT_KEY_SIZE;
1921 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1922 ALOGI("invalid key size %d", keySize);
1923 return ::SYSTEM_ERROR;
1924 }
1925 ec_params.field_size = keySize;
1926
Kenny Root1d448c02013-11-21 10:36:53 -08001927 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001928 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1929 } else {
1930 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001931 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001932 }
Kenny Root96427ba2013-08-16 14:02:41 -07001933 } else if (keyType == EVP_PKEY_RSA) {
1934 keymaster_rsa_keygen_params_t rsa_params;
1935 memset(&rsa_params, '\0', sizeof(rsa_params));
1936 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1937
1938 if (keySize == -1) {
1939 keySize = RSA_DEFAULT_KEY_SIZE;
1940 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1941 ALOGI("invalid key size %d", keySize);
1942 return ::SYSTEM_ERROR;
1943 }
1944 rsa_params.modulus_size = keySize;
1945
1946 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001947 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001948 return ::SYSTEM_ERROR;
1949 } else if (args->size() == 1) {
1950 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1951 if (pubExpBlob != NULL) {
1952 Unique_BIGNUM pubExpBn(
1953 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1954 pubExpBlob->size(), NULL));
1955 if (pubExpBn.get() == NULL) {
1956 ALOGI("Could not convert public exponent to BN");
1957 return ::SYSTEM_ERROR;
1958 }
1959 unsigned long pubExp = BN_get_word(pubExpBn.get());
1960 if (pubExp == 0xFFFFFFFFL) {
1961 ALOGI("cannot represent public exponent as a long value");
1962 return ::SYSTEM_ERROR;
1963 }
1964 rsa_params.public_exponent = pubExp;
1965 }
1966 }
1967
1968 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1969 } else {
1970 ALOGW("Unsupported key type %d", keyType);
1971 rc = -1;
1972 }
1973
Kenny Root07438c82012-11-02 15:41:02 -07001974 if (rc) {
1975 return ::SYSTEM_ERROR;
1976 }
1977
Kenny Root655b9582013-04-04 08:37:42 -07001978 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07001979 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001980
1981 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1982 free(data);
1983
Kenny Rootee8068b2013-10-07 09:49:15 -07001984 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001985 keyBlob.setFallback(isFallback);
1986
Chad Brubaker9489b792015-04-14 11:01:45 -07001987 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001988 }
1989
Kenny Rootf9119d62013-04-03 09:22:15 -07001990 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1991 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001992 targetUid = getEffectiveUid(targetUid);
1993 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1994 flags & KEYSTORE_FLAG_ENCRYPTED);
1995 if (result != ::NO_ERROR) {
1996 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001997 }
Kenny Root07438c82012-11-02 15:41:02 -07001998 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001999 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002000
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002001 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002002 }
2003
Kenny Root07438c82012-11-02 15:41:02 -07002004 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2005 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002006 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002007 return ::PERMISSION_DENIED;
2008 }
Kenny Root07438c82012-11-02 15:41:02 -07002009
Chad Brubaker9489b792015-04-14 11:01:45 -07002010 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002011 Blob keyBlob;
2012 String8 name8(name);
2013
Kenny Rootd38a0b02013-02-13 12:59:14 -08002014 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002015
Kenny Root655b9582013-04-04 08:37:42 -07002016 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002017 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002018 if (responseCode != ::NO_ERROR) {
2019 return responseCode;
2020 }
2021
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002022 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002023 if (device == NULL) {
2024 ALOGE("no keymaster device; cannot sign");
2025 return ::SYSTEM_ERROR;
2026 }
2027
2028 if (device->sign_data == NULL) {
2029 ALOGE("device doesn't implement signing");
2030 return ::SYSTEM_ERROR;
2031 }
2032
2033 keymaster_rsa_sign_params_t params;
2034 params.digest_type = DIGEST_NONE;
2035 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002036 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002037 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002038 if (rc) {
2039 ALOGW("device couldn't sign data");
2040 return ::SYSTEM_ERROR;
2041 }
2042
2043 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002044 }
2045
Kenny Root07438c82012-11-02 15:41:02 -07002046 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2047 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002048 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002049 return ::PERMISSION_DENIED;
2050 }
Kenny Root70e3a862012-02-15 17:20:23 -08002051
Chad Brubaker9489b792015-04-14 11:01:45 -07002052 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002053 Blob keyBlob;
2054 String8 name8(name);
2055 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002056
Kenny Root655b9582013-04-04 08:37:42 -07002057 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002058 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002059 if (responseCode != ::NO_ERROR) {
2060 return responseCode;
2061 }
Kenny Root70e3a862012-02-15 17:20:23 -08002062
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002063 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002064 if (device == NULL) {
2065 return ::SYSTEM_ERROR;
2066 }
Kenny Root70e3a862012-02-15 17:20:23 -08002067
Kenny Root07438c82012-11-02 15:41:02 -07002068 if (device->verify_data == NULL) {
2069 return ::SYSTEM_ERROR;
2070 }
Kenny Root70e3a862012-02-15 17:20:23 -08002071
Kenny Root07438c82012-11-02 15:41:02 -07002072 keymaster_rsa_sign_params_t params;
2073 params.digest_type = DIGEST_NONE;
2074 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002075
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002076 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2077 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002078 if (rc) {
2079 return ::SYSTEM_ERROR;
2080 } else {
2081 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002082 }
2083 }
Kenny Root07438c82012-11-02 15:41:02 -07002084
2085 /*
2086 * TODO: The abstraction between things stored in hardware and regular blobs
2087 * of data stored on the filesystem should be moved down to keystore itself.
2088 * Unfortunately the Java code that calls this has naming conventions that it
2089 * knows about. Ideally keystore shouldn't be used to store random blobs of
2090 * data.
2091 *
2092 * Until that happens, it's necessary to have a separate "get_pubkey" and
2093 * "del_key" since the Java code doesn't really communicate what it's
2094 * intentions are.
2095 */
2096 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002097 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002098 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002099 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002100 return ::PERMISSION_DENIED;
2101 }
Kenny Root07438c82012-11-02 15:41:02 -07002102
Kenny Root07438c82012-11-02 15:41:02 -07002103 Blob keyBlob;
2104 String8 name8(name);
2105
Kenny Rootd38a0b02013-02-13 12:59:14 -08002106 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002107
Kenny Root655b9582013-04-04 08:37:42 -07002108 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002109 TYPE_KEY_PAIR);
2110 if (responseCode != ::NO_ERROR) {
2111 return responseCode;
2112 }
2113
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002114 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002115 if (device == NULL) {
2116 return ::SYSTEM_ERROR;
2117 }
2118
2119 if (device->get_keypair_public == NULL) {
2120 ALOGE("device has no get_keypair_public implementation!");
2121 return ::SYSTEM_ERROR;
2122 }
2123
Kenny Root17208e02013-09-04 13:56:03 -07002124 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002125 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2126 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002127 if (rc) {
2128 return ::SYSTEM_ERROR;
2129 }
2130
2131 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002132 }
Kenny Root07438c82012-11-02 15:41:02 -07002133
Kenny Root49468902013-03-19 13:41:33 -07002134 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002135 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002136 }
2137
2138 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002139 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002140 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2141 if (result != ::NO_ERROR) {
2142 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002143 }
2144
2145 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002146 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002147
Kenny Root655b9582013-04-04 08:37:42 -07002148 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002149 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2150 }
2151
Kenny Root655b9582013-04-04 08:37:42 -07002152 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002153 return ::NO_ERROR;
2154 }
2155
2156 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002157 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002158 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2159 if (result != ::NO_ERROR) {
2160 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002161 }
2162
2163 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002164 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002165
Kenny Root655b9582013-04-04 08:37:42 -07002166 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002167 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2168 }
2169
Kenny Root655b9582013-04-04 08:37:42 -07002170 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002171 }
2172
2173 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002174 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002175 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002176 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002177 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002178 }
Kenny Root07438c82012-11-02 15:41:02 -07002179
2180 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002181 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002182
Kenny Root655b9582013-04-04 08:37:42 -07002183 if (access(filename.string(), R_OK) == -1) {
2184 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002185 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002186 }
2187
Kenny Root655b9582013-04-04 08:37:42 -07002188 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002189 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002190 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002191 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002192 }
2193
2194 struct stat s;
2195 int ret = fstat(fd, &s);
2196 close(fd);
2197 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002198 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002199 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002200 }
2201
Kenny Root36a9e232013-02-04 14:24:15 -08002202 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002203 }
2204
Kenny Rootd53bc922013-03-21 14:10:15 -07002205 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2206 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002207 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002208 pid_t spid = IPCThreadState::self()->getCallingPid();
2209 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002210 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002211 return -1L;
2212 }
2213
Kenny Root655b9582013-04-04 08:37:42 -07002214 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002215 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002216 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002217 return state;
2218 }
2219
Kenny Rootd53bc922013-03-21 14:10:15 -07002220 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2221 srcUid = callingUid;
2222 } else if (!is_granted_to(callingUid, srcUid)) {
2223 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002224 return ::PERMISSION_DENIED;
2225 }
2226
Kenny Rootd53bc922013-03-21 14:10:15 -07002227 if (destUid == -1) {
2228 destUid = callingUid;
2229 }
2230
2231 if (srcUid != destUid) {
2232 if (static_cast<uid_t>(srcUid) != callingUid) {
2233 ALOGD("can only duplicate from caller to other or to same uid: "
2234 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2235 return ::PERMISSION_DENIED;
2236 }
2237
2238 if (!is_granted_to(callingUid, destUid)) {
2239 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2240 return ::PERMISSION_DENIED;
2241 }
2242 }
2243
2244 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002245 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002246
Kenny Rootd53bc922013-03-21 14:10:15 -07002247 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002248 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002249
Kenny Root655b9582013-04-04 08:37:42 -07002250 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2251 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002252 return ::SYSTEM_ERROR;
2253 }
2254
Kenny Rootd53bc922013-03-21 14:10:15 -07002255 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002256 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002257 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002258 if (responseCode != ::NO_ERROR) {
2259 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002260 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002261
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002262 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002263 }
2264
Kenny Root1b0e3932013-09-05 13:06:32 -07002265 int32_t is_hardware_backed(const String16& keyType) {
2266 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002267 }
2268
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002269 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002270 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubaker01771ae2015-05-01 10:21:27 -07002271 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002272 return ::PERMISSION_DENIED;
2273 }
2274
Robin Lee4b84fdc2014-09-24 11:56:57 +01002275 String8 prefix = String8::format("%u_", targetUid);
2276 Vector<String16> aliases;
2277 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002278 return ::SYSTEM_ERROR;
2279 }
2280
Robin Lee4b84fdc2014-09-24 11:56:57 +01002281 for (uint32_t i = 0; i < aliases.size(); i++) {
2282 String8 name8(aliases[i]);
2283 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2284 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002285 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002286 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002287 }
2288
Robin Lee4b84fdc2014-09-24 11:56:57 +01002289 int32_t reset_uid(int32_t targetUid) {
Chad Brubakereecdd122015-05-07 10:19:40 -07002290 // TODO: Remove this method from the binder interface
Chad Brubaker9489b792015-04-14 11:01:45 -07002291 targetUid = getEffectiveUid(targetUid);
Chad Brubakereecdd122015-05-07 10:19:40 -07002292 return onUserPasswordChanged(get_user_id(targetUid), String16(""));
Robin Lee4e865752014-08-19 17:37:55 +01002293 }
2294
2295 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002296 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002297 return ::PERMISSION_DENIED;
2298 }
Chad Brubaker9489b792015-04-14 11:01:45 -07002299
Robin Lee4e865752014-08-19 17:37:55 +01002300 if (sourceUid == targetUid) {
2301 return ::SYSTEM_ERROR;
2302 }
2303
2304 // Initialise user keystore with existing master key held in-memory
2305 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2306 }
2307
2308 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002309 targetUid = getEffectiveUid(targetUid);
2310 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002311 return ::PERMISSION_DENIED;
2312 }
Robin Lee4e865752014-08-19 17:37:55 +01002313 const String8 password8(pw);
2314
2315 switch (mKeyStore->getState(targetUid)) {
2316 case ::STATE_UNINITIALIZED: {
2317 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2318 return mKeyStore->initializeUser(password8, targetUid);
2319 }
2320 case ::STATE_NO_ERROR: {
2321 // rewrite master key with new password.
2322 return mKeyStore->writeMasterKey(password8, targetUid);
2323 }
2324 case ::STATE_LOCKED: {
2325 // read master key, decrypt with password, initialize mMasterKey*.
2326 return mKeyStore->readMasterKey(password8, targetUid);
2327 }
2328 }
2329 return ::SYSTEM_ERROR;
2330 }
2331
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002332 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2333 const keymaster1_device_t* device = mKeyStore->getDevice();
2334 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2335 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2336 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2337 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2338 device->add_rng_entropy != NULL) {
2339 devResult = device->add_rng_entropy(device, data, dataLength);
2340 }
2341 if (fallback->add_rng_entropy) {
2342 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2343 }
2344 if (devResult) {
2345 return devResult;
2346 }
2347 if (fallbackResult) {
2348 return fallbackResult;
2349 }
2350 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002351 }
2352
Chad Brubaker17d68b92015-02-05 22:04:16 -08002353 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002354 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2355 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002356 uid = getEffectiveUid(uid);
2357 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2358 flags & KEYSTORE_FLAG_ENCRYPTED);
2359 if (rc != ::NO_ERROR) {
2360 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002361 }
2362
Chad Brubaker9489b792015-04-14 11:01:45 -07002363 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002364 bool isFallback = false;
2365 keymaster_key_blob_t blob;
2366 keymaster_key_characteristics_t *out = NULL;
2367
2368 const keymaster1_device_t* device = mKeyStore->getDevice();
2369 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2370 if (device == NULL) {
2371 return ::SYSTEM_ERROR;
2372 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002373 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002374 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2375 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002376 if (!entropy) {
2377 rc = KM_ERROR_OK;
2378 } else if (device->add_rng_entropy) {
2379 rc = device->add_rng_entropy(device, entropy, entropyLength);
2380 } else {
2381 rc = KM_ERROR_UNIMPLEMENTED;
2382 }
2383 if (rc == KM_ERROR_OK) {
2384 rc = device->generate_key(device, params.params.data(), params.params.size(),
2385 &blob, &out);
2386 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002387 }
2388 // If the HW device didn't support generate_key or generate_key failed
2389 // fall back to the software implementation.
2390 if (rc && fallback->generate_key != NULL) {
2391 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002392 if (!entropy) {
2393 rc = KM_ERROR_OK;
2394 } else if (fallback->add_rng_entropy) {
2395 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2396 } else {
2397 rc = KM_ERROR_UNIMPLEMENTED;
2398 }
2399 if (rc == KM_ERROR_OK) {
2400 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2401 &blob,
2402 &out);
2403 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002404 }
2405
2406 if (out) {
2407 if (outCharacteristics) {
2408 outCharacteristics->characteristics = *out;
2409 } else {
2410 keymaster_free_characteristics(out);
2411 }
2412 free(out);
2413 }
2414
2415 if (rc) {
2416 return rc;
2417 }
2418
2419 String8 name8(name);
2420 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2421
2422 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2423 keyBlob.setFallback(isFallback);
2424 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2425
2426 free(const_cast<uint8_t*>(blob.key_material));
2427
2428 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002429 }
2430
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002431 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002432 const keymaster_blob_t* clientId,
2433 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002434 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002435 if (!outCharacteristics) {
2436 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2437 }
2438
2439 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2440
2441 Blob keyBlob;
2442 String8 name8(name);
2443 int rc;
2444
2445 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2446 TYPE_KEYMASTER_10);
2447 if (responseCode != ::NO_ERROR) {
2448 return responseCode;
2449 }
2450 keymaster_key_blob_t key;
2451 key.key_material_size = keyBlob.getLength();
2452 key.key_material = keyBlob.getValue();
2453 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2454 keymaster_key_characteristics_t *out = NULL;
2455 if (!dev->get_key_characteristics) {
2456 ALOGW("device does not implement get_key_characteristics");
2457 return KM_ERROR_UNIMPLEMENTED;
2458 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002459 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002460 if (out) {
2461 outCharacteristics->characteristics = *out;
2462 free(out);
2463 }
2464 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002465 }
2466
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002467 int32_t importKey(const String16& name, const KeymasterArguments& params,
2468 keymaster_key_format_t format, const uint8_t *keyData,
2469 size_t keyLength, int uid, int flags,
2470 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002471 uid = getEffectiveUid(uid);
2472 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2473 flags & KEYSTORE_FLAG_ENCRYPTED);
2474 if (rc != ::NO_ERROR) {
2475 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002476 }
2477
Chad Brubaker9489b792015-04-14 11:01:45 -07002478 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002479 bool isFallback = false;
2480 keymaster_key_blob_t blob;
2481 keymaster_key_characteristics_t *out = NULL;
2482
2483 const keymaster1_device_t* device = mKeyStore->getDevice();
2484 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2485 if (device == NULL) {
2486 return ::SYSTEM_ERROR;
2487 }
2488 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2489 device->import_key != NULL) {
2490 rc = device->import_key(device, params.params.data(), params.params.size(),
2491 format, keyData, keyLength, &blob, &out);
2492 }
2493 if (rc && fallback->import_key != NULL) {
2494 isFallback = true;
2495 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2496 format, keyData, keyLength, &blob, &out);
2497 }
2498 if (out) {
2499 if (outCharacteristics) {
2500 outCharacteristics->characteristics = *out;
2501 } else {
2502 keymaster_free_characteristics(out);
2503 }
2504 free(out);
2505 }
2506 if (rc) {
2507 return rc;
2508 }
2509
2510 String8 name8(name);
2511 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2512
2513 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2514 keyBlob.setFallback(isFallback);
2515 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2516
2517 free((void*) blob.key_material);
2518
2519 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002520 }
2521
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002522 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002523 const keymaster_blob_t* clientId,
2524 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002525
2526 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2527
2528 Blob keyBlob;
2529 String8 name8(name);
2530 int rc;
2531
2532 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2533 TYPE_KEYMASTER_10);
2534 if (responseCode != ::NO_ERROR) {
2535 result->resultCode = responseCode;
2536 return;
2537 }
2538 keymaster_key_blob_t key;
2539 key.key_material_size = keyBlob.getLength();
2540 key.key_material = keyBlob.getValue();
2541 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2542 if (!dev->export_key) {
2543 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2544 return;
2545 }
2546 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002547 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002548 &ptr, &result->dataLength);
2549 result->exportData.reset(ptr);
2550 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002551 }
2552
Chad Brubakerad6514a2015-04-09 14:00:26 -07002553
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002554 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002555 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2556 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002557 if (!result || !outParams) {
2558 ALOGE("Unexpected null arguments to begin()");
2559 return;
2560 }
2561 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2562 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2563 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2564 result->resultCode = ::PERMISSION_DENIED;
2565 return;
2566 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002567 if (!checkAllowedOperationParams(params.params)) {
2568 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2569 return;
2570 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002571 Blob keyBlob;
2572 String8 name8(name);
2573 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2574 TYPE_KEYMASTER_10);
2575 if (responseCode != ::NO_ERROR) {
2576 result->resultCode = responseCode;
2577 return;
2578 }
2579 keymaster_key_blob_t key;
2580 key.key_material_size = keyBlob.getLength();
2581 key.key_material = keyBlob.getValue();
2582 keymaster_key_param_t* out;
2583 size_t outSize;
2584 keymaster_operation_handle_t handle;
2585 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002586 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002587 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002588 Unique_keymaster_key_characteristics characteristics;
2589 characteristics.reset(new keymaster_key_characteristics_t);
2590 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2591 if (err) {
2592 result->resultCode = err;
2593 return;
2594 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002595 const hw_auth_token_t* authToken = NULL;
2596 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002597 /*failOnTokenMissing*/ false);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002598 // If per-operation auth is needed we need to begin the operation and
2599 // the client will need to authorize that operation before calling
2600 // update. Any other auth issues stop here.
2601 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2602 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002603 return;
2604 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002605 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002606 // Add entropy to the device first.
2607 if (entropy) {
2608 if (dev->add_rng_entropy) {
2609 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2610 } else {
2611 err = KM_ERROR_UNIMPLEMENTED;
2612 }
2613 if (err) {
2614 result->resultCode = err;
2615 return;
2616 }
2617 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002618 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2619 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002620
2621 // If there are too many operations abort the oldest operation that was
2622 // started as pruneable and try again.
2623 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2624 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2625 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2626 if (abort(oldest) != ::NO_ERROR) {
2627 break;
2628 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002629 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002630 &handle);
2631 }
2632 if (err) {
2633 result->resultCode = err;
2634 return;
2635 }
2636 if (out) {
2637 outParams->params.assign(out, out + outSize);
2638 free(out);
2639 }
2640
Chad Brubakerad6514a2015-04-09 14:00:26 -07002641 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2642 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002643 pruneable);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002644 if (authToken) {
2645 mOperationMap.setOperationAuthToken(operationToken, authToken);
2646 }
2647 // Return the authentication lookup result. If this is a per operation
2648 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2649 // application should get an auth token using the handle before the
2650 // first call to update, which will fail if keystore hasn't received the
2651 // auth token.
2652 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002653 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002654 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002655 }
2656
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002657 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2658 size_t dataLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002659 if (!checkAllowedOperationParams(params.params)) {
2660 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2661 return;
2662 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002663 const keymaster1_device_t* dev;
2664 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002665 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002666 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2667 return;
2668 }
2669 uint8_t* output_buf = NULL;
2670 size_t output_length = 0;
2671 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002672 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002673 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2674 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002675 result->resultCode = authResult;
2676 return;
2677 }
2678 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2679 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002680 result->data.reset(output_buf);
2681 result->dataLength = output_length;
2682 result->inputConsumed = consumed;
2683 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002684 }
2685
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002686 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2687 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002688 if (!checkAllowedOperationParams(params.params)) {
2689 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2690 return;
2691 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002692 const keymaster1_device_t* dev;
2693 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002694 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002695 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2696 return;
2697 }
2698 uint8_t* output_buf = NULL;
2699 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002700 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002701 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2702 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002703 result->resultCode = authResult;
2704 return;
2705 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002706
Chad Brubaker06801e02015-03-31 15:13:13 -07002707 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2708 signature, signatureLength, &output_buf,
2709 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002710 // Remove the operation regardless of the result
2711 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002712 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002713 result->data.reset(output_buf);
2714 result->dataLength = output_length;
2715 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002716 }
2717
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002718 int32_t abort(const sp<IBinder>& token) {
2719 const keymaster1_device_t* dev;
2720 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002721 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002722 return KM_ERROR_INVALID_OPERATION_HANDLE;
2723 }
2724 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002725 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002726 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002727 rc = KM_ERROR_UNIMPLEMENTED;
2728 } else {
2729 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002730 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002731 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002732 if (rc) {
2733 return rc;
2734 }
2735 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002736 }
2737
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002738 bool isOperationAuthorized(const sp<IBinder>& token) {
2739 const keymaster1_device_t* dev;
2740 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002741 const keymaster_key_characteristics_t* characteristics;
2742 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002743 return false;
2744 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002745 const hw_auth_token_t* authToken = NULL;
2746 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002747 std::vector<keymaster_key_param_t> ignored;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002748 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2749 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002750 }
2751
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002752 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002753 if (!checkBinderPermission(P_ADD_AUTH)) {
2754 ALOGW("addAuthToken: permission denied for %d",
2755 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002756 return ::PERMISSION_DENIED;
2757 }
2758 if (length != sizeof(hw_auth_token_t)) {
2759 return KM_ERROR_INVALID_ARGUMENT;
2760 }
2761 hw_auth_token_t* authToken = new hw_auth_token_t;
2762 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2763 // The table takes ownership of authToken.
2764 mAuthTokenTable.AddAuthenticationToken(authToken);
2765 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002766 }
2767
Kenny Root07438c82012-11-02 15:41:02 -07002768private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002769 static const int32_t UID_SELF = -1;
2770
2771 /**
2772 * Get the effective target uid for a binder operation that takes an
2773 * optional uid as the target.
2774 */
2775 inline uid_t getEffectiveUid(int32_t targetUid) {
2776 if (targetUid == UID_SELF) {
2777 return IPCThreadState::self()->getCallingUid();
2778 }
2779 return static_cast<uid_t>(targetUid);
2780 }
2781
2782 /**
2783 * Check if the caller of the current binder method has the required
2784 * permission and if acting on other uids the grants to do so.
2785 */
2786 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2787 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2788 pid_t spid = IPCThreadState::self()->getCallingPid();
2789 if (!has_permission(callingUid, permission, spid)) {
2790 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2791 return false;
2792 }
2793 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2794 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2795 return false;
2796 }
2797 return true;
2798 }
2799
2800 /**
2801 * Check if the caller of the current binder method has the required
Chad Brubaker01771ae2015-05-01 10:21:27 -07002802 * permission and the target uid is the caller or the caller is system.
2803 */
2804 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2805 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2806 pid_t spid = IPCThreadState::self()->getCallingPid();
2807 if (!has_permission(callingUid, permission, spid)) {
2808 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2809 return false;
2810 }
2811 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2812 }
2813
2814 /**
2815 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002816 * permission or the target of the operation is the caller's uid. This is
2817 * for operation where the permission is only for cross-uid activity and all
2818 * uids are allowed to act on their own (ie: clearing all entries for a
2819 * given uid).
2820 */
2821 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2822 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2823 if (getEffectiveUid(targetUid) == callingUid) {
2824 return true;
2825 } else {
2826 return checkBinderPermission(permission, targetUid);
2827 }
2828 }
2829
2830 /**
2831 * Helper method to check that the caller has the required permission as
2832 * well as the keystore is in the unlocked state if checkUnlocked is true.
2833 *
2834 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2835 * otherwise the state of keystore when not unlocked and checkUnlocked is
2836 * true.
2837 */
2838 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2839 bool checkUnlocked = true) {
2840 if (!checkBinderPermission(permission, targetUid)) {
2841 return ::PERMISSION_DENIED;
2842 }
2843 State state = mKeyStore->getState(getEffectiveUid(targetUid));
2844 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2845 return state;
2846 }
2847
2848 return ::NO_ERROR;
2849
2850 }
2851
Kenny Root9d45d1c2013-02-14 10:32:30 -08002852 inline bool isKeystoreUnlocked(State state) {
2853 switch (state) {
2854 case ::STATE_NO_ERROR:
2855 return true;
2856 case ::STATE_UNINITIALIZED:
2857 case ::STATE_LOCKED:
2858 return false;
2859 }
2860 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002861 }
2862
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002863 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002864 const int32_t device_api = device->common.module->module_api_version;
2865 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2866 switch (keyType) {
2867 case TYPE_RSA:
2868 case TYPE_DSA:
2869 case TYPE_EC:
2870 return true;
2871 default:
2872 return false;
2873 }
2874 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2875 switch (keyType) {
2876 case TYPE_RSA:
2877 return true;
2878 case TYPE_DSA:
2879 return device->flags & KEYMASTER_SUPPORTS_DSA;
2880 case TYPE_EC:
2881 return device->flags & KEYMASTER_SUPPORTS_EC;
2882 default:
2883 return false;
2884 }
2885 } else {
2886 return keyType == TYPE_RSA;
2887 }
2888 }
2889
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002890 /**
2891 * Check that all keymaster_key_param_t's provided by the application are
2892 * allowed. Any parameter that keystore adds itself should be disallowed here.
2893 */
2894 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2895 for (auto param: params) {
2896 switch (param.tag) {
2897 case KM_TAG_AUTH_TOKEN:
2898 return false;
2899 default:
2900 break;
2901 }
2902 }
2903 return true;
2904 }
2905
2906 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2907 const keymaster1_device_t* dev,
2908 const std::vector<keymaster_key_param_t>& params,
2909 keymaster_key_characteristics_t* out) {
2910 UniquePtr<keymaster_blob_t> appId;
2911 UniquePtr<keymaster_blob_t> appData;
2912 for (auto param : params) {
2913 if (param.tag == KM_TAG_APPLICATION_ID) {
2914 appId.reset(new keymaster_blob_t);
2915 appId->data = param.blob.data;
2916 appId->data_length = param.blob.data_length;
2917 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2918 appData.reset(new keymaster_blob_t);
2919 appData->data = param.blob.data;
2920 appData->data_length = param.blob.data_length;
2921 }
2922 }
2923 keymaster_key_characteristics_t* result = NULL;
2924 if (!dev->get_key_characteristics) {
2925 return KM_ERROR_UNIMPLEMENTED;
2926 }
2927 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2928 appData.get(), &result);
2929 if (result) {
2930 *out = *result;
2931 free(result);
2932 }
2933 return error;
2934 }
2935
2936 /**
2937 * Get the auth token for this operation from the auth token table.
2938 *
2939 * Returns ::NO_ERROR if the auth token was set or none was required.
2940 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2941 * authorization token exists for that operation and
2942 * failOnTokenMissing is false.
2943 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2944 * token for the operation
2945 */
2946 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2947 keymaster_operation_handle_t handle,
2948 const hw_auth_token_t** authToken,
2949 bool failOnTokenMissing = true) {
2950
2951 std::vector<keymaster_key_param_t> allCharacteristics;
2952 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2953 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2954 }
2955 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2956 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2957 }
2958 keymaster::AuthTokenTable::Error err =
2959 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2960 allCharacteristics.size(), handle, authToken);
2961 switch (err) {
2962 case keymaster::AuthTokenTable::OK:
2963 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2964 return ::NO_ERROR;
2965 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2966 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2967 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2968 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2969 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2970 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2971 (int32_t) ::OP_AUTH_NEEDED;
2972 default:
2973 ALOGE("Unexpected FindAuthorization return value %d", err);
2974 return KM_ERROR_INVALID_ARGUMENT;
2975 }
2976 }
2977
2978 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2979 const hw_auth_token_t* token) {
2980 if (token) {
2981 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2982 reinterpret_cast<const uint8_t*>(token),
2983 sizeof(hw_auth_token_t)));
2984 }
2985 }
2986
2987 /**
2988 * Add the auth token for the operation to the param list if the operation
2989 * requires authorization. Uses the cached result in the OperationMap if available
2990 * otherwise gets the token from the AuthTokenTable and caches the result.
2991 *
2992 * Returns ::NO_ERROR if the auth token was added or not needed.
2993 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2994 * authenticated.
2995 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2996 * operation token.
2997 */
2998 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2999 std::vector<keymaster_key_param_t>* params) {
3000 const hw_auth_token_t* authToken = NULL;
Chad Brubaker6b541162015-04-29 19:58:34 -07003001 mOperationMap.getOperationAuthToken(token, &authToken);
3002 if (!authToken) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07003003 const keymaster1_device_t* dev;
3004 keymaster_operation_handle_t handle;
3005 const keymaster_key_characteristics_t* characteristics = NULL;
3006 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3007 return KM_ERROR_INVALID_OPERATION_HANDLE;
3008 }
3009 int32_t result = getAuthToken(characteristics, handle, &authToken);
3010 if (result != ::NO_ERROR) {
3011 return result;
3012 }
3013 if (authToken) {
3014 mOperationMap.setOperationAuthToken(token, authToken);
3015 }
3016 }
3017 addAuthToParams(params, authToken);
3018 return ::NO_ERROR;
3019 }
3020
Kenny Root07438c82012-11-02 15:41:02 -07003021 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003022 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003023 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003024};
3025
3026}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003027
3028int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003029 if (argc < 2) {
3030 ALOGE("A directory must be specified!");
3031 return 1;
3032 }
3033 if (chdir(argv[1]) == -1) {
3034 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3035 return 1;
3036 }
3037
3038 Entropy entropy;
3039 if (!entropy.open()) {
3040 return 1;
3041 }
Kenny Root70e3a862012-02-15 17:20:23 -08003042
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07003043 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003044 if (keymaster_device_initialize(&dev)) {
3045 ALOGE("keystore keymaster could not be initialized; exiting");
3046 return 1;
3047 }
3048
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003049 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003050 if (fallback_keymaster_device_initialize(&fallback)) {
3051 ALOGE("software keymaster could not be initialized; exiting");
3052 return 1;
3053 }
3054
Riley Spahneaabae92014-06-30 12:39:52 -07003055 ks_is_selinux_enabled = is_selinux_enabled();
3056 if (ks_is_selinux_enabled) {
3057 union selinux_callback cb;
3058 cb.func_log = selinux_log_callback;
3059 selinux_set_callback(SELINUX_CB_LOG, cb);
3060 if (getcon(&tctx) != 0) {
3061 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3062 return -1;
3063 }
3064 } else {
3065 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3066 }
3067
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003068 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003069 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003070 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3071 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3072 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3073 if (ret != android::OK) {
3074 ALOGE("Couldn't register binder service!");
3075 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003076 }
Kenny Root07438c82012-11-02 15:41:02 -07003077
3078 /*
3079 * We're the only thread in existence, so we're just going to process
3080 * Binder transaction as a single-threaded program.
3081 */
3082 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003083
3084 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003085 return 1;
3086}