blob: 906992c18913da4a56a00432fe6405bd6d69d88e [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Shawn Willden80843db2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willden80843db2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Shawn Willden04006752015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker67d2a502015-03-11 17:21:18 +0000137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willden80843db2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
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 Brubaker96d6d782015-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) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800507 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800508 mBlob.length = valueLength;
509 memcpy(mBlob.value, value, valueLength);
510
511 mBlob.info = infoLength;
512 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700513
Kenny Root07438c82012-11-02 15:41:02 -0700514 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700515 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700516
Kenny Rootee8068b2013-10-07 09:49:15 -0700517 if (type == TYPE_MASTER_KEY) {
518 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
519 } else {
520 mBlob.flags = KEYSTORE_FLAG_NONE;
521 }
Kenny Roota91203b2012-02-15 15:00:46 -0800522 }
523
524 Blob(blob b) {
525 mBlob = b;
526 }
527
Alex Klyubin1773b442015-02-20 12:33:33 -0800528 Blob() {
529 memset(&mBlob, 0, sizeof(mBlob));
530 }
Kenny Roota91203b2012-02-15 15:00:46 -0800531
Kenny Root51878182012-03-13 12:53:19 -0700532 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.value;
534 }
535
Kenny Root51878182012-03-13 12:53:19 -0700536 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 return mBlob.length;
538 }
539
Kenny Root51878182012-03-13 12:53:19 -0700540 const uint8_t* getInfo() const {
541 return mBlob.value + mBlob.length;
542 }
543
544 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800545 return mBlob.info;
546 }
547
Kenny Root822c3a92012-03-23 16:34:39 -0700548 uint8_t getVersion() const {
549 return mBlob.version;
550 }
551
Kenny Rootf9119d62013-04-03 09:22:15 -0700552 bool isEncrypted() const {
553 if (mBlob.version < 2) {
554 return true;
555 }
556
557 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
558 }
559
560 void setEncrypted(bool encrypted) {
561 if (encrypted) {
562 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
563 } else {
564 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
565 }
566 }
567
Kenny Root17208e02013-09-04 13:56:03 -0700568 bool isFallback() const {
569 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
570 }
571
572 void setFallback(bool fallback) {
573 if (fallback) {
574 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
575 } else {
576 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
577 }
578 }
579
Kenny Root822c3a92012-03-23 16:34:39 -0700580 void setVersion(uint8_t version) {
581 mBlob.version = version;
582 }
583
584 BlobType getType() const {
585 return BlobType(mBlob.type);
586 }
587
588 void setType(BlobType type) {
589 mBlob.type = uint8_t(type);
590 }
591
Kenny Rootf9119d62013-04-03 09:22:15 -0700592 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
593 ALOGV("writing blob %s", filename);
594 if (isEncrypted()) {
595 if (state != STATE_NO_ERROR) {
596 ALOGD("couldn't insert encrypted blob while not unlocked");
597 return LOCKED;
598 }
599
600 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
601 ALOGW("Could not read random data for: %s", filename);
602 return SYSTEM_ERROR;
603 }
Kenny Roota91203b2012-02-15 15:00:46 -0800604 }
605
606 // data includes the value and the value's length
607 size_t dataLength = mBlob.length + sizeof(mBlob.length);
608 // pad data to the AES_BLOCK_SIZE
609 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
610 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
611 // encrypted data includes the digest value
612 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
613 // move info after space for padding
614 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
615 // zero padding area
616 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
617
618 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800619
Kenny Rootf9119d62013-04-03 09:22:15 -0700620 if (isEncrypted()) {
621 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800622
Kenny Rootf9119d62013-04-03 09:22:15 -0700623 uint8_t vector[AES_BLOCK_SIZE];
624 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
625 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
626 aes_key, vector, AES_ENCRYPT);
627 }
628
Kenny Roota91203b2012-02-15 15:00:46 -0800629 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
630 size_t fileLength = encryptedLength + headerLength + mBlob.info;
631
632 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800633 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
634 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
635 if (out < 0) {
636 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800637 return SYSTEM_ERROR;
638 }
639 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
640 if (close(out) != 0) {
641 return SYSTEM_ERROR;
642 }
643 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800644 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800645 unlink(tmpFileName);
646 return SYSTEM_ERROR;
647 }
Kenny Root150ca932012-11-14 14:29:02 -0800648 if (rename(tmpFileName, filename) == -1) {
649 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
650 return SYSTEM_ERROR;
651 }
652 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800653 }
654
Kenny Rootf9119d62013-04-03 09:22:15 -0700655 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
656 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800657 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
658 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800659 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
660 }
661 // fileLength may be less than sizeof(mBlob) since the in
662 // memory version has extra padding to tolerate rounding up to
663 // the AES_BLOCK_SIZE
664 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
665 if (close(in) != 0) {
666 return SYSTEM_ERROR;
667 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700668
669 if (isEncrypted() && (state != STATE_NO_ERROR)) {
670 return LOCKED;
671 }
672
Kenny Roota91203b2012-02-15 15:00:46 -0800673 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
674 if (fileLength < headerLength) {
675 return VALUE_CORRUPTED;
676 }
677
678 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700679 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800680 return VALUE_CORRUPTED;
681 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700682
683 ssize_t digestedLength;
684 if (isEncrypted()) {
685 if (encryptedLength % AES_BLOCK_SIZE != 0) {
686 return VALUE_CORRUPTED;
687 }
688
689 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
690 mBlob.vector, AES_DECRYPT);
691 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
692 uint8_t computedDigest[MD5_DIGEST_LENGTH];
693 MD5(mBlob.digested, digestedLength, computedDigest);
694 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
695 return VALUE_CORRUPTED;
696 }
697 } else {
698 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800699 }
700
701 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
702 mBlob.length = ntohl(mBlob.length);
703 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
704 return VALUE_CORRUPTED;
705 }
706 if (mBlob.info != 0) {
707 // move info from after padding to after data
708 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
709 }
Kenny Root07438c82012-11-02 15:41:02 -0700710 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800711 }
712
713private:
714 struct blob mBlob;
715};
716
Kenny Root655b9582013-04-04 08:37:42 -0700717class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800718public:
Kenny Root655b9582013-04-04 08:37:42 -0700719 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
720 asprintf(&mUserDir, "user_%u", mUserId);
721 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
722 }
723
724 ~UserState() {
725 free(mUserDir);
726 free(mMasterKeyFile);
727 }
728
729 bool initialize() {
730 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
731 ALOGE("Could not create directory '%s'", mUserDir);
732 return false;
733 }
734
735 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800736 setState(STATE_LOCKED);
737 } else {
738 setState(STATE_UNINITIALIZED);
739 }
Kenny Root70e3a862012-02-15 17:20:23 -0800740
Kenny Root655b9582013-04-04 08:37:42 -0700741 return true;
742 }
743
744 uid_t getUserId() const {
745 return mUserId;
746 }
747
748 const char* getUserDirName() const {
749 return mUserDir;
750 }
751
752 const char* getMasterKeyFileName() const {
753 return mMasterKeyFile;
754 }
755
756 void setState(State state) {
757 mState = state;
758 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
759 mRetry = MAX_RETRY;
760 }
Kenny Roota91203b2012-02-15 15:00:46 -0800761 }
762
Kenny Root51878182012-03-13 12:53:19 -0700763 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800764 return mState;
765 }
766
Kenny Root51878182012-03-13 12:53:19 -0700767 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800768 return mRetry;
769 }
770
Kenny Root655b9582013-04-04 08:37:42 -0700771 void zeroizeMasterKeysInMemory() {
772 memset(mMasterKey, 0, sizeof(mMasterKey));
773 memset(mSalt, 0, sizeof(mSalt));
774 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
775 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800776 }
777
Chad Brubaker96d6d782015-05-07 10:19:40 -0700778 bool deleteMasterKey() {
779 setState(STATE_UNINITIALIZED);
780 zeroizeMasterKeysInMemory();
781 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
782 }
783
Kenny Root655b9582013-04-04 08:37:42 -0700784 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
785 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800786 return SYSTEM_ERROR;
787 }
Kenny Root655b9582013-04-04 08:37:42 -0700788 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800789 if (response != NO_ERROR) {
790 return response;
791 }
792 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700793 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800794 }
795
Robin Lee4e865752014-08-19 17:37:55 +0100796 ResponseCode copyMasterKey(UserState* src) {
797 if (mState != STATE_UNINITIALIZED) {
798 return ::SYSTEM_ERROR;
799 }
800 if (src->getState() != STATE_NO_ERROR) {
801 return ::SYSTEM_ERROR;
802 }
803 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
804 setupMasterKeys();
805 return ::NO_ERROR;
806 }
807
Kenny Root655b9582013-04-04 08:37:42 -0700808 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800809 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
810 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
811 AES_KEY passwordAesKey;
812 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700813 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700814 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800815 }
816
Kenny Root655b9582013-04-04 08:37:42 -0700817 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
818 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800819 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800820 return SYSTEM_ERROR;
821 }
822
823 // we read the raw blob to just to get the salt to generate
824 // the AES key, then we create the Blob to use with decryptBlob
825 blob rawBlob;
826 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
827 if (close(in) != 0) {
828 return SYSTEM_ERROR;
829 }
830 // find salt at EOF if present, otherwise we have an old file
831 uint8_t* salt;
832 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
833 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
834 } else {
835 salt = NULL;
836 }
837 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
838 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
839 AES_KEY passwordAesKey;
840 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
841 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700842 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
843 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800844 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700845 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800846 }
847 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
848 // if salt was missing, generate one and write a new master key file with the salt.
849 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700850 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800851 return SYSTEM_ERROR;
852 }
Kenny Root655b9582013-04-04 08:37:42 -0700853 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800854 }
855 if (response == NO_ERROR) {
856 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
857 setupMasterKeys();
858 }
859 return response;
860 }
861 if (mRetry <= 0) {
862 reset();
863 return UNINITIALIZED;
864 }
865 --mRetry;
866 switch (mRetry) {
867 case 0: return WRONG_PASSWORD_0;
868 case 1: return WRONG_PASSWORD_1;
869 case 2: return WRONG_PASSWORD_2;
870 case 3: return WRONG_PASSWORD_3;
871 default: return WRONG_PASSWORD_3;
872 }
873 }
874
Kenny Root655b9582013-04-04 08:37:42 -0700875 AES_KEY* getEncryptionKey() {
876 return &mMasterKeyEncryption;
877 }
878
879 AES_KEY* getDecryptionKey() {
880 return &mMasterKeyDecryption;
881 }
882
Kenny Roota91203b2012-02-15 15:00:46 -0800883 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700884 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800885 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700886 // If the directory doesn't exist then nothing to do.
887 if (errno == ENOENT) {
888 return true;
889 }
Kenny Root655b9582013-04-04 08:37:42 -0700890 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800891 return false;
892 }
Kenny Root655b9582013-04-04 08:37:42 -0700893
894 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800895 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700896 // skip . and ..
897 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700898 continue;
899 }
900
901 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800902 }
903 closedir(dir);
904 return true;
905 }
906
Kenny Root655b9582013-04-04 08:37:42 -0700907private:
908 static const int MASTER_KEY_SIZE_BYTES = 16;
909 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
910
911 static const int MAX_RETRY = 4;
912 static const size_t SALT_SIZE = 16;
913
914 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
915 uint8_t* salt) {
916 size_t saltSize;
917 if (salt != NULL) {
918 saltSize = SALT_SIZE;
919 } else {
920 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
921 salt = (uint8_t*) "keystore";
922 // sizeof = 9, not strlen = 8
923 saltSize = sizeof("keystore");
924 }
925
926 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
927 saltSize, 8192, keySize, key);
928 }
929
930 bool generateSalt(Entropy* entropy) {
931 return entropy->generate_random_data(mSalt, sizeof(mSalt));
932 }
933
934 bool generateMasterKey(Entropy* entropy) {
935 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
936 return false;
937 }
938 if (!generateSalt(entropy)) {
939 return false;
940 }
941 return true;
942 }
943
944 void setupMasterKeys() {
945 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
946 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
947 setState(STATE_NO_ERROR);
948 }
949
950 uid_t mUserId;
951
952 char* mUserDir;
953 char* mMasterKeyFile;
954
955 State mState;
956 int8_t mRetry;
957
958 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
959 uint8_t mSalt[SALT_SIZE];
960
961 AES_KEY mMasterKeyEncryption;
962 AES_KEY mMasterKeyDecryption;
963};
964
965typedef struct {
966 uint32_t uid;
967 const uint8_t* filename;
968} grant_t;
969
970class KeyStore {
971public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000972 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700973 : mEntropy(entropy)
974 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800975 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700976 {
977 memset(&mMetaData, '\0', sizeof(mMetaData));
978 }
979
980 ~KeyStore() {
981 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
982 it != mGrants.end(); it++) {
983 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700984 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800985 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700986
987 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
988 it != mMasterKeys.end(); it++) {
989 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700990 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800991 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700992 }
993
Chad Brubaker67d2a502015-03-11 17:21:18 +0000994 /**
995 * Depending on the hardware keymaster version is this may return a
996 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
997 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
998 * be guarded by a check on the device's version.
999 */
1000 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001001 return mDevice;
1002 }
1003
Chad Brubaker67d2a502015-03-11 17:21:18 +00001004 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001005 return mFallbackDevice;
1006 }
1007
Chad Brubaker67d2a502015-03-11 17:21:18 +00001008 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001009 return blob.isFallback() ? mFallbackDevice: mDevice;
1010 }
1011
Kenny Root655b9582013-04-04 08:37:42 -07001012 ResponseCode initialize() {
1013 readMetaData();
1014 if (upgradeKeystore()) {
1015 writeMetaData();
1016 }
1017
1018 return ::NO_ERROR;
1019 }
1020
1021 State getState(uid_t uid) {
1022 return getUserState(uid)->getState();
1023 }
1024
1025 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1026 UserState* userState = getUserState(uid);
1027 return userState->initialize(pw, mEntropy);
1028 }
1029
Robin Lee4e865752014-08-19 17:37:55 +01001030 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1031 UserState *userState = getUserState(uid);
1032 UserState *initState = getUserState(src);
1033 return userState->copyMasterKey(initState);
1034 }
1035
Kenny Root655b9582013-04-04 08:37:42 -07001036 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001037 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001038 return userState->writeMasterKey(pw, mEntropy);
1039 }
1040
1041 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001042 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001043 return userState->readMasterKey(pw, mEntropy);
1044 }
1045
1046 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001047 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001048 encode_key(encoded, keyName);
1049 return android::String8(encoded);
1050 }
1051
1052 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001053 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001054 encode_key(encoded, keyName);
1055 return android::String8::format("%u_%s", uid, encoded);
1056 }
1057
1058 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001059 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001060 encode_key(encoded, keyName);
1061 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1062 encoded);
1063 }
1064
Chad Brubaker96d6d782015-05-07 10:19:40 -07001065 /*
1066 * Delete entries owned by userId. If keepUnencryptedEntries is true
1067 * then only encrypted entries will be removed, otherwise all entries will
1068 * be removed.
1069 */
1070 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001071 android::String8 prefix("");
1072 android::Vector<android::String16> aliases;
Chad Brubaker96d6d782015-05-07 10:19:40 -07001073 uid_t uid = get_uid(userId, AID_SYSTEM);
Kenny Root655b9582013-04-04 08:37:42 -07001074 UserState* userState = getUserState(uid);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001075 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1076 return;
1077 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001078 for (uint32_t i = 0; i < aliases.size(); i++) {
1079 android::String8 filename(aliases[i]);
1080 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001081 getKeyName(filename).string());
1082 bool shouldDelete = true;
1083 if (keepUnenryptedEntries) {
1084 Blob blob;
1085 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001086
Chad Brubaker96d6d782015-05-07 10:19:40 -07001087 /* get can fail if the blob is encrypted and the state is
1088 * not unlocked, only skip deleting blobs that were loaded and
1089 * who are not encrypted. If there are blobs we fail to read for
1090 * other reasons err on the safe side and delete them since we
1091 * can't tell if they're encrypted.
1092 */
1093 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1094 }
1095 if (shouldDelete) {
1096 del(filename, ::TYPE_ANY, uid);
1097 }
1098 }
1099 if (!userState->deleteMasterKey()) {
1100 ALOGE("Failed to delete user %d's master key", userId);
1101 }
1102 if (!keepUnenryptedEntries) {
1103 if(!userState->reset()) {
1104 ALOGE("Failed to remove user %d's directory", userId);
1105 }
1106 }
Kenny Root655b9582013-04-04 08:37:42 -07001107 }
1108
1109 bool isEmpty(uid_t uid) const {
1110 const UserState* userState = getUserState(uid);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001111 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001112 return true;
1113 }
1114
1115 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001116 if (!dir) {
1117 return true;
1118 }
Kenny Root31e27462014-09-10 11:28:03 -07001119
Kenny Roota91203b2012-02-15 15:00:46 -08001120 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001121 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001122 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001123 // We only care about files.
1124 if (file->d_type != DT_REG) {
1125 continue;
1126 }
1127
1128 // Skip anything that starts with a "."
1129 if (file->d_name[0] == '.') {
1130 continue;
1131 }
1132
Kenny Root31e27462014-09-10 11:28:03 -07001133 result = false;
1134 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001135 }
1136 closedir(dir);
1137 return result;
1138 }
1139
Kenny Root655b9582013-04-04 08:37:42 -07001140 void lock(uid_t uid) {
1141 UserState* userState = getUserState(uid);
1142 userState->zeroizeMasterKeysInMemory();
1143 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001144 }
1145
Kenny Root655b9582013-04-04 08:37:42 -07001146 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1147 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001148 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1149 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001150 if (rc != NO_ERROR) {
1151 return rc;
1152 }
1153
1154 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001155 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001156 /* If we upgrade the key, we need to write it to disk again. Then
1157 * it must be read it again since the blob is encrypted each time
1158 * it's written.
1159 */
Kenny Root655b9582013-04-04 08:37:42 -07001160 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1161 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001162 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1163 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001164 return rc;
1165 }
1166 }
Kenny Root822c3a92012-03-23 16:34:39 -07001167 }
1168
Kenny Root17208e02013-09-04 13:56:03 -07001169 /*
1170 * This will upgrade software-backed keys to hardware-backed keys when
1171 * the HAL for the device supports the newer key types.
1172 */
1173 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1174 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1175 && keyBlob->isFallback()) {
1176 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1177 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1178
1179 // The HAL allowed the import, reget the key to have the "fresh"
1180 // version.
1181 if (imported == NO_ERROR) {
1182 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1183 }
1184 }
1185
Kenny Rootd53bc922013-03-21 14:10:15 -07001186 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001187 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1188 return KEY_NOT_FOUND;
1189 }
1190
1191 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001192 }
1193
Kenny Root655b9582013-04-04 08:37:42 -07001194 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1195 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001196 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1197 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001198 }
1199
Robin Lee4b84fdc2014-09-24 11:56:57 +01001200 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1201 Blob keyBlob;
1202 ResponseCode rc = get(filename, &keyBlob, type, uid);
1203 if (rc != ::NO_ERROR) {
1204 return rc;
1205 }
1206
1207 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1208 // A device doesn't have to implement delete_keypair.
1209 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1210 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1211 rc = ::SYSTEM_ERROR;
1212 }
1213 }
1214 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001215 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1216 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1217 if (dev->delete_key) {
1218 keymaster_key_blob_t blob;
1219 blob.key_material = keyBlob.getValue();
1220 blob.key_material_size = keyBlob.getLength();
1221 dev->delete_key(dev, &blob);
1222 }
1223 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001224 if (rc != ::NO_ERROR) {
1225 return rc;
1226 }
1227
1228 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1229 }
1230
1231 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1232 uid_t uid) {
1233
1234 UserState* userState = getUserState(uid);
1235 size_t n = prefix.length();
1236
1237 DIR* dir = opendir(userState->getUserDirName());
1238 if (!dir) {
1239 ALOGW("can't open directory for user: %s", strerror(errno));
1240 return ::SYSTEM_ERROR;
1241 }
1242
1243 struct dirent* file;
1244 while ((file = readdir(dir)) != NULL) {
1245 // We only care about files.
1246 if (file->d_type != DT_REG) {
1247 continue;
1248 }
1249
1250 // Skip anything that starts with a "."
1251 if (file->d_name[0] == '.') {
1252 continue;
1253 }
1254
1255 if (!strncmp(prefix.string(), file->d_name, n)) {
1256 const char* p = &file->d_name[n];
1257 size_t plen = strlen(p);
1258
1259 size_t extra = decode_key_length(p, plen);
1260 char *match = (char*) malloc(extra + 1);
1261 if (match != NULL) {
1262 decode_key(match, p, plen);
1263 matches->push(android::String16(match, extra));
1264 free(match);
1265 } else {
1266 ALOGW("could not allocate match of size %zd", extra);
1267 }
1268 }
1269 }
1270 closedir(dir);
1271 return ::NO_ERROR;
1272 }
1273
Kenny Root07438c82012-11-02 15:41:02 -07001274 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001275 const grant_t* existing = getGrant(filename, granteeUid);
1276 if (existing == NULL) {
1277 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001278 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001279 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001280 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001281 }
1282 }
1283
Kenny Root07438c82012-11-02 15:41:02 -07001284 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001285 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1286 it != mGrants.end(); it++) {
1287 grant_t* grant = *it;
1288 if (grant->uid == granteeUid
1289 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1290 mGrants.erase(it);
1291 return true;
1292 }
Kenny Root70e3a862012-02-15 17:20:23 -08001293 }
Kenny Root70e3a862012-02-15 17:20:23 -08001294 return false;
1295 }
1296
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001297 bool hasGrant(const char* filename, const uid_t uid) const {
1298 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001299 }
1300
Kenny Rootf9119d62013-04-03 09:22:15 -07001301 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1302 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001303 uint8_t* data;
1304 size_t dataLength;
1305 int rc;
1306
1307 if (mDevice->import_keypair == NULL) {
1308 ALOGE("Keymaster doesn't support import!");
1309 return SYSTEM_ERROR;
1310 }
1311
Kenny Root17208e02013-09-04 13:56:03 -07001312 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001313 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001314 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001315 /*
1316 * Maybe the device doesn't support this type of key. Try to use the
1317 * software fallback keymaster implementation. This is a little bit
1318 * lazier than checking the PKCS#8 key type, but the software
1319 * implementation will do that anyway.
1320 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001321 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001322 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001323
1324 if (rc) {
1325 ALOGE("Error while importing keypair: %d", rc);
1326 return SYSTEM_ERROR;
1327 }
Kenny Root822c3a92012-03-23 16:34:39 -07001328 }
1329
1330 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1331 free(data);
1332
Kenny Rootf9119d62013-04-03 09:22:15 -07001333 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001334 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001335
Kenny Root655b9582013-04-04 08:37:42 -07001336 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001337 }
1338
Kenny Root1b0e3932013-09-05 13:06:32 -07001339 bool isHardwareBacked(const android::String16& keyType) const {
1340 if (mDevice == NULL) {
1341 ALOGW("can't get keymaster device");
1342 return false;
1343 }
1344
1345 if (sRSAKeyType == keyType) {
1346 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1347 } else {
1348 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1349 && (mDevice->common.module->module_api_version
1350 >= KEYMASTER_MODULE_API_VERSION_0_2);
1351 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001352 }
1353
Kenny Root655b9582013-04-04 08:37:42 -07001354 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1355 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001356 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001357
1358 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1359 if (responseCode == NO_ERROR) {
1360 return responseCode;
1361 }
1362
1363 // If this is one of the legacy UID->UID mappings, use it.
1364 uid_t euid = get_keystore_euid(uid);
1365 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001366 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001367 responseCode = get(filepath8.string(), keyBlob, type, uid);
1368 if (responseCode == NO_ERROR) {
1369 return responseCode;
1370 }
1371 }
1372
1373 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001374 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001375 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001376 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001377 if (end[0] != '_' || end[1] == 0) {
1378 return KEY_NOT_FOUND;
1379 }
Kenny Root86b16e82013-09-09 11:15:54 -07001380 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1381 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001382 if (!hasGrant(filepath8.string(), uid)) {
1383 return responseCode;
1384 }
1385
1386 // It is a granted key. Try to load it.
1387 return get(filepath8.string(), keyBlob, type, uid);
1388 }
1389
1390 /**
1391 * Returns any existing UserState or creates it if it doesn't exist.
1392 */
1393 UserState* getUserState(uid_t uid) {
1394 uid_t userId = get_user_id(uid);
1395
1396 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1397 it != mMasterKeys.end(); it++) {
1398 UserState* state = *it;
1399 if (state->getUserId() == userId) {
1400 return state;
1401 }
1402 }
1403
1404 UserState* userState = new UserState(userId);
1405 if (!userState->initialize()) {
1406 /* There's not much we can do if initialization fails. Trying to
1407 * unlock the keystore for that user will fail as well, so any
1408 * subsequent request for this user will just return SYSTEM_ERROR.
1409 */
1410 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1411 }
1412 mMasterKeys.add(userState);
1413 return userState;
1414 }
1415
1416 /**
1417 * Returns NULL if the UserState doesn't already exist.
1418 */
1419 const UserState* getUserState(uid_t uid) const {
1420 uid_t userId = get_user_id(uid);
1421
1422 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1423 it != mMasterKeys.end(); it++) {
1424 UserState* state = *it;
1425 if (state->getUserId() == userId) {
1426 return state;
1427 }
1428 }
1429
1430 return NULL;
1431 }
1432
Kenny Roota91203b2012-02-15 15:00:46 -08001433private:
Kenny Root655b9582013-04-04 08:37:42 -07001434 static const char* sOldMasterKey;
1435 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001436 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001437 Entropy* mEntropy;
1438
Chad Brubaker67d2a502015-03-11 17:21:18 +00001439 keymaster1_device_t* mDevice;
1440 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001441
Kenny Root655b9582013-04-04 08:37:42 -07001442 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001443
Kenny Root655b9582013-04-04 08:37:42 -07001444 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001445
Kenny Root655b9582013-04-04 08:37:42 -07001446 typedef struct {
1447 uint32_t version;
1448 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001449
Kenny Root655b9582013-04-04 08:37:42 -07001450 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001451
Kenny Root655b9582013-04-04 08:37:42 -07001452 const grant_t* getGrant(const char* filename, uid_t uid) const {
1453 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1454 it != mGrants.end(); it++) {
1455 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001456 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001457 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001458 return grant;
1459 }
1460 }
Kenny Root70e3a862012-02-15 17:20:23 -08001461 return NULL;
1462 }
1463
Kenny Root822c3a92012-03-23 16:34:39 -07001464 /**
1465 * Upgrade code. This will upgrade the key from the current version
1466 * to whatever is newest.
1467 */
Kenny Root655b9582013-04-04 08:37:42 -07001468 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1469 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001470 bool updated = false;
1471 uint8_t version = oldVersion;
1472
1473 /* From V0 -> V1: All old types were unknown */
1474 if (version == 0) {
1475 ALOGV("upgrading to version 1 and setting type %d", type);
1476
1477 blob->setType(type);
1478 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001479 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001480 }
1481 version = 1;
1482 updated = true;
1483 }
1484
Kenny Rootf9119d62013-04-03 09:22:15 -07001485 /* From V1 -> V2: All old keys were encrypted */
1486 if (version == 1) {
1487 ALOGV("upgrading to version 2");
1488
1489 blob->setEncrypted(true);
1490 version = 2;
1491 updated = true;
1492 }
1493
Kenny Root822c3a92012-03-23 16:34:39 -07001494 /*
1495 * If we've updated, set the key blob to the right version
1496 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001497 */
Kenny Root822c3a92012-03-23 16:34:39 -07001498 if (updated) {
1499 ALOGV("updated and writing file %s", filename);
1500 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001501 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001502
1503 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001504 }
1505
1506 /**
1507 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1508 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1509 * Then it overwrites the original blob with the new blob
1510 * format that is returned from the keymaster.
1511 */
Kenny Root655b9582013-04-04 08:37:42 -07001512 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001513 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1514 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1515 if (b.get() == NULL) {
1516 ALOGE("Problem instantiating BIO");
1517 return SYSTEM_ERROR;
1518 }
1519
1520 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1521 if (pkey.get() == NULL) {
1522 ALOGE("Couldn't read old PEM file");
1523 return SYSTEM_ERROR;
1524 }
1525
1526 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1527 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1528 if (len < 0) {
1529 ALOGE("Couldn't measure PKCS#8 length");
1530 return SYSTEM_ERROR;
1531 }
1532
Kenny Root70c98892013-02-07 09:10:36 -08001533 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1534 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001535 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1536 ALOGE("Couldn't convert to PKCS#8");
1537 return SYSTEM_ERROR;
1538 }
1539
Kenny Rootf9119d62013-04-03 09:22:15 -07001540 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1541 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001542 if (rc != NO_ERROR) {
1543 return rc;
1544 }
1545
Kenny Root655b9582013-04-04 08:37:42 -07001546 return get(filename, blob, TYPE_KEY_PAIR, uid);
1547 }
1548
1549 void readMetaData() {
1550 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1551 if (in < 0) {
1552 return;
1553 }
1554 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1555 if (fileLength != sizeof(mMetaData)) {
1556 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1557 sizeof(mMetaData));
1558 }
1559 close(in);
1560 }
1561
1562 void writeMetaData() {
1563 const char* tmpFileName = ".metadata.tmp";
1564 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1565 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1566 if (out < 0) {
1567 ALOGE("couldn't write metadata file: %s", strerror(errno));
1568 return;
1569 }
1570 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1571 if (fileLength != sizeof(mMetaData)) {
1572 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1573 sizeof(mMetaData));
1574 }
1575 close(out);
1576 rename(tmpFileName, sMetaDataFile);
1577 }
1578
1579 bool upgradeKeystore() {
1580 bool upgraded = false;
1581
1582 if (mMetaData.version == 0) {
1583 UserState* userState = getUserState(0);
1584
1585 // Initialize first so the directory is made.
1586 userState->initialize();
1587
1588 // Migrate the old .masterkey file to user 0.
1589 if (access(sOldMasterKey, R_OK) == 0) {
1590 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1591 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1592 return false;
1593 }
1594 }
1595
1596 // Initialize again in case we had a key.
1597 userState->initialize();
1598
1599 // Try to migrate existing keys.
1600 DIR* dir = opendir(".");
1601 if (!dir) {
1602 // Give up now; maybe we can upgrade later.
1603 ALOGE("couldn't open keystore's directory; something is wrong");
1604 return false;
1605 }
1606
1607 struct dirent* file;
1608 while ((file = readdir(dir)) != NULL) {
1609 // We only care about files.
1610 if (file->d_type != DT_REG) {
1611 continue;
1612 }
1613
1614 // Skip anything that starts with a "."
1615 if (file->d_name[0] == '.') {
1616 continue;
1617 }
1618
1619 // Find the current file's user.
1620 char* end;
1621 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1622 if (end[0] != '_' || end[1] == 0) {
1623 continue;
1624 }
1625 UserState* otherUser = getUserState(thisUid);
1626 if (otherUser->getUserId() != 0) {
1627 unlinkat(dirfd(dir), file->d_name, 0);
1628 }
1629
1630 // Rename the file into user directory.
1631 DIR* otherdir = opendir(otherUser->getUserDirName());
1632 if (otherdir == NULL) {
1633 ALOGW("couldn't open user directory for rename");
1634 continue;
1635 }
1636 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1637 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1638 }
1639 closedir(otherdir);
1640 }
1641 closedir(dir);
1642
1643 mMetaData.version = 1;
1644 upgraded = true;
1645 }
1646
1647 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001648 }
Kenny Roota91203b2012-02-15 15:00:46 -08001649};
1650
Kenny Root655b9582013-04-04 08:37:42 -07001651const char* KeyStore::sOldMasterKey = ".masterkey";
1652const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001653
Kenny Root1b0e3932013-09-05 13:06:32 -07001654const android::String16 KeyStore::sRSAKeyType("RSA");
1655
Kenny Root07438c82012-11-02 15:41:02 -07001656namespace android {
1657class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1658public:
1659 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001660 : mKeyStore(keyStore),
1661 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001662 {
Kenny Roota91203b2012-02-15 15:00:46 -08001663 }
Kenny Roota91203b2012-02-15 15:00:46 -08001664
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001665 void binderDied(const wp<IBinder>& who) {
1666 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1667 for (auto token: operations) {
1668 abort(token);
1669 }
Kenny Root822c3a92012-03-23 16:34:39 -07001670 }
Kenny Roota91203b2012-02-15 15:00:46 -08001671
Kenny Root07438c82012-11-02 15:41:02 -07001672 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001673 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001674 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001675 }
Kenny Roota91203b2012-02-15 15:00:46 -08001676
Chad Brubaker9489b792015-04-14 11:01:45 -07001677 return mKeyStore->getState(IPCThreadState::self()->getCallingUid());
Kenny Root298e7b12012-03-26 13:54:44 -07001678 }
1679
Kenny Root07438c82012-11-02 15:41:02 -07001680 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001681 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001682 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001683 }
Kenny Root07438c82012-11-02 15:41:02 -07001684
Chad Brubaker9489b792015-04-14 11:01:45 -07001685 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001686 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001687 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001688
Kenny Root655b9582013-04-04 08:37:42 -07001689 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001690 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001691 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001692 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001693 *item = NULL;
1694 *itemLength = 0;
1695 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001696 }
Kenny Roota91203b2012-02-15 15:00:46 -08001697
Kenny Root07438c82012-11-02 15:41:02 -07001698 *item = (uint8_t*) malloc(keyBlob.getLength());
1699 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1700 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001701
Kenny Root07438c82012-11-02 15:41:02 -07001702 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001703 }
1704
Kenny Rootf9119d62013-04-03 09:22:15 -07001705 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1706 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001707 targetUid = getEffectiveUid(targetUid);
1708 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1709 flags & KEYSTORE_FLAG_ENCRYPTED);
1710 if (result != ::NO_ERROR) {
1711 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001712 }
1713
Kenny Root07438c82012-11-02 15:41:02 -07001714 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001715 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001716
1717 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001718 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1719
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001720 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001721 }
1722
Kenny Root49468902013-03-19 13:41:33 -07001723 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001724 targetUid = getEffectiveUid(targetUid);
1725 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001726 return ::PERMISSION_DENIED;
1727 }
Kenny Root07438c82012-11-02 15:41:02 -07001728 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001729 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001730 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001731 }
1732
Kenny Root49468902013-03-19 13:41:33 -07001733 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001734 targetUid = getEffectiveUid(targetUid);
1735 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001736 return ::PERMISSION_DENIED;
1737 }
1738
Kenny Root07438c82012-11-02 15:41:02 -07001739 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001740 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001741
Kenny Root655b9582013-04-04 08:37:42 -07001742 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001743 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1744 }
1745 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001746 }
1747
Kenny Root49468902013-03-19 13:41:33 -07001748 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001749 targetUid = getEffectiveUid(targetUid);
1750 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001751 return ::PERMISSION_DENIED;
1752 }
Kenny Root07438c82012-11-02 15:41:02 -07001753 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001754 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001755
Robin Lee4b84fdc2014-09-24 11:56:57 +01001756 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1757 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001758 }
Kenny Root07438c82012-11-02 15:41:02 -07001759 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001760 }
1761
Kenny Root07438c82012-11-02 15:41:02 -07001762 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001763 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001764 return ::PERMISSION_DENIED;
1765 }
1766
Chad Brubaker9489b792015-04-14 11:01:45 -07001767 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001768 mKeyStore->resetUser(get_user_id(callingUid), false);
1769 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001770 }
1771
Chad Brubaker96d6d782015-05-07 10:19:40 -07001772 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001773 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001774 return ::PERMISSION_DENIED;
1775 }
Kenny Root70e3a862012-02-15 17:20:23 -08001776
Kenny Root07438c82012-11-02 15:41:02 -07001777 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001778 uid_t uid = get_uid(userId, AID_SYSTEM);
Kenny Root70e3a862012-02-15 17:20:23 -08001779
Chad Brubaker96d6d782015-05-07 10:19:40 -07001780 // Flush the auth token table to prevent stale tokens from sticking
1781 // around.
1782 mAuthTokenTable.Clear();
1783
1784 if (password.size() == 0) {
1785 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
1786 mKeyStore->resetUser(static_cast<uid_t>(userId), true);
1787 return ::NO_ERROR;
1788 } else {
1789 switch (mKeyStore->getState(uid)) {
1790 case ::STATE_UNINITIALIZED: {
1791 // generate master key, encrypt with password, write to file,
1792 // initialize mMasterKey*.
1793 return mKeyStore->initializeUser(password8, uid);
1794 }
1795 case ::STATE_NO_ERROR: {
1796 // rewrite master key with new password.
1797 return mKeyStore->writeMasterKey(password8, uid);
1798 }
1799 case ::STATE_LOCKED: {
1800 ALOGE("Changing user %d's password while locked, clearing old encryption",
1801 userId);
1802 mKeyStore->resetUser(static_cast<uid_t>(userId), true);
1803 return mKeyStore->initializeUser(password8, uid);
1804 }
Kenny Root07438c82012-11-02 15:41:02 -07001805 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001806 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001807 }
Kenny Root70e3a862012-02-15 17:20:23 -08001808 }
1809
Kenny Root07438c82012-11-02 15:41:02 -07001810 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001811 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001812 return ::PERMISSION_DENIED;
1813 }
Kenny Root70e3a862012-02-15 17:20:23 -08001814
Chad Brubaker9489b792015-04-14 11:01:45 -07001815 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001816 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001817 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001818 ALOGD("calling lock in state: %d", state);
1819 return state;
1820 }
1821
Kenny Root655b9582013-04-04 08:37:42 -07001822 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001823 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001824 }
1825
Chad Brubaker96d6d782015-05-07 10:19:40 -07001826 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001827 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001828 return ::PERMISSION_DENIED;
1829 }
1830
Chad Brubaker96d6d782015-05-07 10:19:40 -07001831 uid_t uid = get_uid(userId, AID_SYSTEM);
1832 State state = mKeyStore->getState(uid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001833 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001834 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001835 return state;
1836 }
1837
1838 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001839 // read master key, decrypt with password, initialize mMasterKey*.
1840 return mKeyStore->readMasterKey(password8, uid);
Kenny Root70e3a862012-02-15 17:20:23 -08001841 }
1842
Kenny Root07438c82012-11-02 15:41:02 -07001843 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001844 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001845 return -1;
1846 }
Kenny Root70e3a862012-02-15 17:20:23 -08001847
Chad Brubaker9489b792015-04-14 11:01:45 -07001848 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root655b9582013-04-04 08:37:42 -07001849 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001850 }
1851
Kenny Root96427ba2013-08-16 14:02:41 -07001852 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1853 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001854 targetUid = getEffectiveUid(targetUid);
1855 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1856 flags & KEYSTORE_FLAG_ENCRYPTED);
1857 if (result != ::NO_ERROR) {
1858 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001859 }
Kenny Root07438c82012-11-02 15:41:02 -07001860 uint8_t* data;
1861 size_t dataLength;
1862 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001863 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001864
Chad Brubaker67d2a502015-03-11 17:21:18 +00001865 const keymaster1_device_t* device = mKeyStore->getDevice();
1866 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001867 if (device == NULL) {
1868 return ::SYSTEM_ERROR;
1869 }
1870
1871 if (device->generate_keypair == NULL) {
1872 return ::SYSTEM_ERROR;
1873 }
1874
Kenny Root17208e02013-09-04 13:56:03 -07001875 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001876 keymaster_dsa_keygen_params_t dsa_params;
1877 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001878
Kenny Root96427ba2013-08-16 14:02:41 -07001879 if (keySize == -1) {
1880 keySize = DSA_DEFAULT_KEY_SIZE;
1881 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1882 || keySize > DSA_MAX_KEY_SIZE) {
1883 ALOGI("invalid key size %d", keySize);
1884 return ::SYSTEM_ERROR;
1885 }
1886 dsa_params.key_size = keySize;
1887
1888 if (args->size() == 3) {
1889 sp<KeystoreArg> gArg = args->itemAt(0);
1890 sp<KeystoreArg> pArg = args->itemAt(1);
1891 sp<KeystoreArg> qArg = args->itemAt(2);
1892
1893 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1894 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1895 dsa_params.generator_len = gArg->size();
1896
1897 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1898 dsa_params.prime_p_len = pArg->size();
1899
1900 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1901 dsa_params.prime_q_len = qArg->size();
1902 } else {
1903 ALOGI("not all DSA parameters were read");
1904 return ::SYSTEM_ERROR;
1905 }
1906 } else if (args->size() != 0) {
1907 ALOGI("DSA args must be 3");
1908 return ::SYSTEM_ERROR;
1909 }
1910
Kenny Root1d448c02013-11-21 10:36:53 -08001911 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001912 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1913 } else {
1914 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001915 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1916 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001917 }
1918 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001919 keymaster_ec_keygen_params_t ec_params;
1920 memset(&ec_params, '\0', sizeof(ec_params));
1921
1922 if (keySize == -1) {
1923 keySize = EC_DEFAULT_KEY_SIZE;
1924 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1925 ALOGI("invalid key size %d", keySize);
1926 return ::SYSTEM_ERROR;
1927 }
1928 ec_params.field_size = keySize;
1929
Kenny Root1d448c02013-11-21 10:36:53 -08001930 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001931 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1932 } else {
1933 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001934 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001935 }
Kenny Root96427ba2013-08-16 14:02:41 -07001936 } else if (keyType == EVP_PKEY_RSA) {
1937 keymaster_rsa_keygen_params_t rsa_params;
1938 memset(&rsa_params, '\0', sizeof(rsa_params));
1939 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1940
1941 if (keySize == -1) {
1942 keySize = RSA_DEFAULT_KEY_SIZE;
1943 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1944 ALOGI("invalid key size %d", keySize);
1945 return ::SYSTEM_ERROR;
1946 }
1947 rsa_params.modulus_size = keySize;
1948
1949 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001950 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001951 return ::SYSTEM_ERROR;
1952 } else if (args->size() == 1) {
1953 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1954 if (pubExpBlob != NULL) {
1955 Unique_BIGNUM pubExpBn(
1956 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1957 pubExpBlob->size(), NULL));
1958 if (pubExpBn.get() == NULL) {
1959 ALOGI("Could not convert public exponent to BN");
1960 return ::SYSTEM_ERROR;
1961 }
1962 unsigned long pubExp = BN_get_word(pubExpBn.get());
1963 if (pubExp == 0xFFFFFFFFL) {
1964 ALOGI("cannot represent public exponent as a long value");
1965 return ::SYSTEM_ERROR;
1966 }
1967 rsa_params.public_exponent = pubExp;
1968 }
1969 }
1970
1971 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1972 } else {
1973 ALOGW("Unsupported key type %d", keyType);
1974 rc = -1;
1975 }
1976
Kenny Root07438c82012-11-02 15:41:02 -07001977 if (rc) {
1978 return ::SYSTEM_ERROR;
1979 }
1980
Kenny Root655b9582013-04-04 08:37:42 -07001981 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07001982 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001983
1984 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1985 free(data);
1986
Kenny Rootee8068b2013-10-07 09:49:15 -07001987 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001988 keyBlob.setFallback(isFallback);
1989
Chad Brubaker9489b792015-04-14 11:01:45 -07001990 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001991 }
1992
Kenny Rootf9119d62013-04-03 09:22:15 -07001993 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1994 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001995 targetUid = getEffectiveUid(targetUid);
1996 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1997 flags & KEYSTORE_FLAG_ENCRYPTED);
1998 if (result != ::NO_ERROR) {
1999 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002000 }
Kenny Root07438c82012-11-02 15:41:02 -07002001 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002002 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002003
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002004 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002005 }
2006
Kenny Root07438c82012-11-02 15:41:02 -07002007 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2008 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002009 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002010 return ::PERMISSION_DENIED;
2011 }
Kenny Root07438c82012-11-02 15:41:02 -07002012
Chad Brubaker9489b792015-04-14 11:01:45 -07002013 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002014 Blob keyBlob;
2015 String8 name8(name);
2016
Kenny Rootd38a0b02013-02-13 12:59:14 -08002017 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002018
Kenny Root655b9582013-04-04 08:37:42 -07002019 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002020 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002021 if (responseCode != ::NO_ERROR) {
2022 return responseCode;
2023 }
2024
Chad Brubaker67d2a502015-03-11 17:21:18 +00002025 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002026 if (device == NULL) {
2027 ALOGE("no keymaster device; cannot sign");
2028 return ::SYSTEM_ERROR;
2029 }
2030
2031 if (device->sign_data == NULL) {
2032 ALOGE("device doesn't implement signing");
2033 return ::SYSTEM_ERROR;
2034 }
2035
2036 keymaster_rsa_sign_params_t params;
2037 params.digest_type = DIGEST_NONE;
2038 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002039 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002040 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002041 if (rc) {
2042 ALOGW("device couldn't sign data");
2043 return ::SYSTEM_ERROR;
2044 }
2045
2046 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002047 }
2048
Kenny Root07438c82012-11-02 15:41:02 -07002049 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2050 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002051 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002052 return ::PERMISSION_DENIED;
2053 }
Kenny Root70e3a862012-02-15 17:20:23 -08002054
Chad Brubaker9489b792015-04-14 11:01:45 -07002055 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002056 Blob keyBlob;
2057 String8 name8(name);
2058 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002059
Kenny Root655b9582013-04-04 08:37:42 -07002060 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002061 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002062 if (responseCode != ::NO_ERROR) {
2063 return responseCode;
2064 }
Kenny Root70e3a862012-02-15 17:20:23 -08002065
Chad Brubaker67d2a502015-03-11 17:21:18 +00002066 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002067 if (device == NULL) {
2068 return ::SYSTEM_ERROR;
2069 }
Kenny Root70e3a862012-02-15 17:20:23 -08002070
Kenny Root07438c82012-11-02 15:41:02 -07002071 if (device->verify_data == NULL) {
2072 return ::SYSTEM_ERROR;
2073 }
Kenny Root70e3a862012-02-15 17:20:23 -08002074
Kenny Root07438c82012-11-02 15:41:02 -07002075 keymaster_rsa_sign_params_t params;
2076 params.digest_type = DIGEST_NONE;
2077 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002078
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002079 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2080 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002081 if (rc) {
2082 return ::SYSTEM_ERROR;
2083 } else {
2084 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002085 }
2086 }
Kenny Root07438c82012-11-02 15:41:02 -07002087
2088 /*
2089 * TODO: The abstraction between things stored in hardware and regular blobs
2090 * of data stored on the filesystem should be moved down to keystore itself.
2091 * Unfortunately the Java code that calls this has naming conventions that it
2092 * knows about. Ideally keystore shouldn't be used to store random blobs of
2093 * data.
2094 *
2095 * Until that happens, it's necessary to have a separate "get_pubkey" and
2096 * "del_key" since the Java code doesn't really communicate what it's
2097 * intentions are.
2098 */
2099 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002100 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002101 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002102 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002103 return ::PERMISSION_DENIED;
2104 }
Kenny Root07438c82012-11-02 15:41:02 -07002105
Kenny Root07438c82012-11-02 15:41:02 -07002106 Blob keyBlob;
2107 String8 name8(name);
2108
Kenny Rootd38a0b02013-02-13 12:59:14 -08002109 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002110
Kenny Root655b9582013-04-04 08:37:42 -07002111 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002112 TYPE_KEY_PAIR);
2113 if (responseCode != ::NO_ERROR) {
2114 return responseCode;
2115 }
2116
Chad Brubaker67d2a502015-03-11 17:21:18 +00002117 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002118 if (device == NULL) {
2119 return ::SYSTEM_ERROR;
2120 }
2121
2122 if (device->get_keypair_public == NULL) {
2123 ALOGE("device has no get_keypair_public implementation!");
2124 return ::SYSTEM_ERROR;
2125 }
2126
Kenny Root17208e02013-09-04 13:56:03 -07002127 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002128 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2129 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002130 if (rc) {
2131 return ::SYSTEM_ERROR;
2132 }
2133
2134 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002135 }
Kenny Root07438c82012-11-02 15:41:02 -07002136
Kenny Root49468902013-03-19 13:41:33 -07002137 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002138 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002139 }
2140
2141 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002142 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002143 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2144 if (result != ::NO_ERROR) {
2145 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002146 }
2147
2148 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002149 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002150
Kenny Root655b9582013-04-04 08:37:42 -07002151 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002152 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2153 }
2154
Kenny Root655b9582013-04-04 08:37:42 -07002155 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002156 return ::NO_ERROR;
2157 }
2158
2159 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002160 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002161 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2162 if (result != ::NO_ERROR) {
2163 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002164 }
2165
2166 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002167 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002168
Kenny Root655b9582013-04-04 08:37:42 -07002169 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002170 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2171 }
2172
Kenny Root655b9582013-04-04 08:37:42 -07002173 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002174 }
2175
2176 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002177 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002178 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002179 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002180 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002181 }
Kenny Root07438c82012-11-02 15:41:02 -07002182
2183 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002184 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002185
Kenny Root655b9582013-04-04 08:37:42 -07002186 if (access(filename.string(), R_OK) == -1) {
2187 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002188 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002189 }
2190
Kenny Root655b9582013-04-04 08:37:42 -07002191 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002192 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002193 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002194 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002195 }
2196
2197 struct stat s;
2198 int ret = fstat(fd, &s);
2199 close(fd);
2200 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002201 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002202 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002203 }
2204
Kenny Root36a9e232013-02-04 14:24:15 -08002205 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002206 }
2207
Kenny Rootd53bc922013-03-21 14:10:15 -07002208 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2209 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002210 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002211 pid_t spid = IPCThreadState::self()->getCallingPid();
2212 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002213 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002214 return -1L;
2215 }
2216
Kenny Root655b9582013-04-04 08:37:42 -07002217 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002218 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002219 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002220 return state;
2221 }
2222
Kenny Rootd53bc922013-03-21 14:10:15 -07002223 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2224 srcUid = callingUid;
2225 } else if (!is_granted_to(callingUid, srcUid)) {
2226 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002227 return ::PERMISSION_DENIED;
2228 }
2229
Kenny Rootd53bc922013-03-21 14:10:15 -07002230 if (destUid == -1) {
2231 destUid = callingUid;
2232 }
2233
2234 if (srcUid != destUid) {
2235 if (static_cast<uid_t>(srcUid) != callingUid) {
2236 ALOGD("can only duplicate from caller to other or to same uid: "
2237 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2238 return ::PERMISSION_DENIED;
2239 }
2240
2241 if (!is_granted_to(callingUid, destUid)) {
2242 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2243 return ::PERMISSION_DENIED;
2244 }
2245 }
2246
2247 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002248 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002249
Kenny Rootd53bc922013-03-21 14:10:15 -07002250 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002251 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002252
Kenny Root655b9582013-04-04 08:37:42 -07002253 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2254 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002255 return ::SYSTEM_ERROR;
2256 }
2257
Kenny Rootd53bc922013-03-21 14:10:15 -07002258 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002259 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002260 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002261 if (responseCode != ::NO_ERROR) {
2262 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002263 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002264
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002265 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002266 }
2267
Kenny Root1b0e3932013-09-05 13:06:32 -07002268 int32_t is_hardware_backed(const String16& keyType) {
2269 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002270 }
2271
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002272 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002273 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002274 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002275 return ::PERMISSION_DENIED;
2276 }
2277
Robin Lee4b84fdc2014-09-24 11:56:57 +01002278 String8 prefix = String8::format("%u_", targetUid);
2279 Vector<String16> aliases;
2280 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002281 return ::SYSTEM_ERROR;
2282 }
2283
Robin Lee4b84fdc2014-09-24 11:56:57 +01002284 for (uint32_t i = 0; i < aliases.size(); i++) {
2285 String8 name8(aliases[i]);
2286 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2287 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002288 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002289 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002290 }
2291
Robin Lee4b84fdc2014-09-24 11:56:57 +01002292 int32_t reset_uid(int32_t targetUid) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002293 // TODO: Remove this method from the binder interface
Chad Brubaker9489b792015-04-14 11:01:45 -07002294 targetUid = getEffectiveUid(targetUid);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002295 return onUserPasswordChanged(get_user_id(targetUid), String16(""));
Robin Lee4e865752014-08-19 17:37:55 +01002296 }
2297
2298 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002299 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002300 return ::PERMISSION_DENIED;
2301 }
Chad Brubaker9489b792015-04-14 11:01:45 -07002302
Robin Lee4e865752014-08-19 17:37:55 +01002303 if (sourceUid == targetUid) {
2304 return ::SYSTEM_ERROR;
2305 }
2306
2307 // Initialise user keystore with existing master key held in-memory
2308 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2309 }
2310
2311 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002312 targetUid = getEffectiveUid(targetUid);
2313 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002314 return ::PERMISSION_DENIED;
2315 }
Robin Lee4e865752014-08-19 17:37:55 +01002316 const String8 password8(pw);
2317
2318 switch (mKeyStore->getState(targetUid)) {
2319 case ::STATE_UNINITIALIZED: {
2320 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2321 return mKeyStore->initializeUser(password8, targetUid);
2322 }
2323 case ::STATE_NO_ERROR: {
2324 // rewrite master key with new password.
2325 return mKeyStore->writeMasterKey(password8, targetUid);
2326 }
2327 case ::STATE_LOCKED: {
2328 // read master key, decrypt with password, initialize mMasterKey*.
2329 return mKeyStore->readMasterKey(password8, targetUid);
2330 }
2331 }
2332 return ::SYSTEM_ERROR;
2333 }
2334
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002335 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2336 const keymaster1_device_t* device = mKeyStore->getDevice();
2337 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2338 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2339 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2340 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2341 device->add_rng_entropy != NULL) {
2342 devResult = device->add_rng_entropy(device, data, dataLength);
2343 }
2344 if (fallback->add_rng_entropy) {
2345 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2346 }
2347 if (devResult) {
2348 return devResult;
2349 }
2350 if (fallbackResult) {
2351 return fallbackResult;
2352 }
2353 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002354 }
2355
Chad Brubaker17d68b92015-02-05 22:04:16 -08002356 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002357 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2358 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002359 uid = getEffectiveUid(uid);
2360 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2361 flags & KEYSTORE_FLAG_ENCRYPTED);
2362 if (rc != ::NO_ERROR) {
2363 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002364 }
2365
Chad Brubaker9489b792015-04-14 11:01:45 -07002366 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002367 bool isFallback = false;
2368 keymaster_key_blob_t blob;
2369 keymaster_key_characteristics_t *out = NULL;
2370
2371 const keymaster1_device_t* device = mKeyStore->getDevice();
2372 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2373 if (device == NULL) {
2374 return ::SYSTEM_ERROR;
2375 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002376 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002377 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2378 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002379 if (!entropy) {
2380 rc = KM_ERROR_OK;
2381 } else if (device->add_rng_entropy) {
2382 rc = device->add_rng_entropy(device, entropy, entropyLength);
2383 } else {
2384 rc = KM_ERROR_UNIMPLEMENTED;
2385 }
2386 if (rc == KM_ERROR_OK) {
2387 rc = device->generate_key(device, params.params.data(), params.params.size(),
2388 &blob, &out);
2389 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002390 }
2391 // If the HW device didn't support generate_key or generate_key failed
2392 // fall back to the software implementation.
2393 if (rc && fallback->generate_key != NULL) {
2394 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002395 if (!entropy) {
2396 rc = KM_ERROR_OK;
2397 } else if (fallback->add_rng_entropy) {
2398 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2399 } else {
2400 rc = KM_ERROR_UNIMPLEMENTED;
2401 }
2402 if (rc == KM_ERROR_OK) {
2403 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2404 &blob,
2405 &out);
2406 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002407 }
2408
2409 if (out) {
2410 if (outCharacteristics) {
2411 outCharacteristics->characteristics = *out;
2412 } else {
2413 keymaster_free_characteristics(out);
2414 }
2415 free(out);
2416 }
2417
2418 if (rc) {
2419 return rc;
2420 }
2421
2422 String8 name8(name);
2423 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2424
2425 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2426 keyBlob.setFallback(isFallback);
2427 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2428
2429 free(const_cast<uint8_t*>(blob.key_material));
2430
2431 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002432 }
2433
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002434 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002435 const keymaster_blob_t* clientId,
2436 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002437 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002438 if (!outCharacteristics) {
2439 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2440 }
2441
2442 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2443
2444 Blob keyBlob;
2445 String8 name8(name);
2446 int rc;
2447
2448 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2449 TYPE_KEYMASTER_10);
2450 if (responseCode != ::NO_ERROR) {
2451 return responseCode;
2452 }
2453 keymaster_key_blob_t key;
2454 key.key_material_size = keyBlob.getLength();
2455 key.key_material = keyBlob.getValue();
2456 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2457 keymaster_key_characteristics_t *out = NULL;
2458 if (!dev->get_key_characteristics) {
2459 ALOGW("device does not implement get_key_characteristics");
2460 return KM_ERROR_UNIMPLEMENTED;
2461 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002462 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002463 if (out) {
2464 outCharacteristics->characteristics = *out;
2465 free(out);
2466 }
2467 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002468 }
2469
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002470 int32_t importKey(const String16& name, const KeymasterArguments& params,
2471 keymaster_key_format_t format, const uint8_t *keyData,
2472 size_t keyLength, int uid, int flags,
2473 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002474 uid = getEffectiveUid(uid);
2475 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2476 flags & KEYSTORE_FLAG_ENCRYPTED);
2477 if (rc != ::NO_ERROR) {
2478 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002479 }
2480
Chad Brubaker9489b792015-04-14 11:01:45 -07002481 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002482 bool isFallback = false;
2483 keymaster_key_blob_t blob;
2484 keymaster_key_characteristics_t *out = NULL;
2485
2486 const keymaster1_device_t* device = mKeyStore->getDevice();
2487 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2488 if (device == NULL) {
2489 return ::SYSTEM_ERROR;
2490 }
2491 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2492 device->import_key != NULL) {
2493 rc = device->import_key(device, params.params.data(), params.params.size(),
2494 format, keyData, keyLength, &blob, &out);
2495 }
2496 if (rc && fallback->import_key != NULL) {
2497 isFallback = true;
2498 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2499 format, keyData, keyLength, &blob, &out);
2500 }
2501 if (out) {
2502 if (outCharacteristics) {
2503 outCharacteristics->characteristics = *out;
2504 } else {
2505 keymaster_free_characteristics(out);
2506 }
2507 free(out);
2508 }
2509 if (rc) {
2510 return rc;
2511 }
2512
2513 String8 name8(name);
2514 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2515
2516 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2517 keyBlob.setFallback(isFallback);
2518 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2519
2520 free((void*) blob.key_material);
2521
2522 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002523 }
2524
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002525 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002526 const keymaster_blob_t* clientId,
2527 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002528
2529 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2530
2531 Blob keyBlob;
2532 String8 name8(name);
2533 int rc;
2534
2535 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2536 TYPE_KEYMASTER_10);
2537 if (responseCode != ::NO_ERROR) {
2538 result->resultCode = responseCode;
2539 return;
2540 }
2541 keymaster_key_blob_t key;
2542 key.key_material_size = keyBlob.getLength();
2543 key.key_material = keyBlob.getValue();
2544 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2545 if (!dev->export_key) {
2546 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2547 return;
2548 }
2549 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002550 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002551 &ptr, &result->dataLength);
2552 result->exportData.reset(ptr);
2553 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002554 }
2555
Chad Brubakerad6514a2015-04-09 14:00:26 -07002556
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002557 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002558 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2559 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002560 if (!result || !outParams) {
2561 ALOGE("Unexpected null arguments to begin()");
2562 return;
2563 }
2564 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2565 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2566 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2567 result->resultCode = ::PERMISSION_DENIED;
2568 return;
2569 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002570 if (!checkAllowedOperationParams(params.params)) {
2571 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2572 return;
2573 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002574 Blob keyBlob;
2575 String8 name8(name);
2576 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2577 TYPE_KEYMASTER_10);
2578 if (responseCode != ::NO_ERROR) {
2579 result->resultCode = responseCode;
2580 return;
2581 }
2582 keymaster_key_blob_t key;
2583 key.key_material_size = keyBlob.getLength();
2584 key.key_material = keyBlob.getValue();
2585 keymaster_key_param_t* out;
2586 size_t outSize;
2587 keymaster_operation_handle_t handle;
2588 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002589 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002590 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002591 Unique_keymaster_key_characteristics characteristics;
2592 characteristics.reset(new keymaster_key_characteristics_t);
2593 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2594 if (err) {
2595 result->resultCode = err;
2596 return;
2597 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002598 const hw_auth_token_t* authToken = NULL;
2599 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002600 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002601 // If per-operation auth is needed we need to begin the operation and
2602 // the client will need to authorize that operation before calling
2603 // update. Any other auth issues stop here.
2604 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2605 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002606 return;
2607 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002608 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002609 // Add entropy to the device first.
2610 if (entropy) {
2611 if (dev->add_rng_entropy) {
2612 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2613 } else {
2614 err = KM_ERROR_UNIMPLEMENTED;
2615 }
2616 if (err) {
2617 result->resultCode = err;
2618 return;
2619 }
2620 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002621 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2622 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002623
2624 // If there are too many operations abort the oldest operation that was
2625 // started as pruneable and try again.
2626 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2627 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2628 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2629 if (abort(oldest) != ::NO_ERROR) {
2630 break;
2631 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002632 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002633 &handle);
2634 }
2635 if (err) {
2636 result->resultCode = err;
2637 return;
2638 }
2639 if (out) {
2640 outParams->params.assign(out, out + outSize);
2641 free(out);
2642 }
2643
Chad Brubakerad6514a2015-04-09 14:00:26 -07002644 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2645 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002646 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002647 if (authToken) {
2648 mOperationMap.setOperationAuthToken(operationToken, authToken);
2649 }
2650 // Return the authentication lookup result. If this is a per operation
2651 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2652 // application should get an auth token using the handle before the
2653 // first call to update, which will fail if keystore hasn't received the
2654 // auth token.
2655 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002656 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002657 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002658 }
2659
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002660 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2661 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002662 if (!checkAllowedOperationParams(params.params)) {
2663 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2664 return;
2665 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002666 const keymaster1_device_t* dev;
2667 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002668 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002669 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2670 return;
2671 }
2672 uint8_t* output_buf = NULL;
2673 size_t output_length = 0;
2674 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002675 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002676 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2677 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002678 result->resultCode = authResult;
2679 return;
2680 }
2681 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2682 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002683 result->data.reset(output_buf);
2684 result->dataLength = output_length;
2685 result->inputConsumed = consumed;
2686 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002687 }
2688
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002689 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2690 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002691 if (!checkAllowedOperationParams(params.params)) {
2692 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2693 return;
2694 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002695 const keymaster1_device_t* dev;
2696 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002697 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002698 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2699 return;
2700 }
2701 uint8_t* output_buf = NULL;
2702 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002703 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002704 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2705 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002706 result->resultCode = authResult;
2707 return;
2708 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002709
Chad Brubaker06801e02015-03-31 15:13:13 -07002710 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2711 signature, signatureLength, &output_buf,
2712 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002713 // Remove the operation regardless of the result
2714 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002715 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002716 result->data.reset(output_buf);
2717 result->dataLength = output_length;
2718 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002719 }
2720
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002721 int32_t abort(const sp<IBinder>& token) {
2722 const keymaster1_device_t* dev;
2723 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002724 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002725 return KM_ERROR_INVALID_OPERATION_HANDLE;
2726 }
2727 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002728 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002729 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002730 rc = KM_ERROR_UNIMPLEMENTED;
2731 } else {
2732 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002733 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002734 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002735 if (rc) {
2736 return rc;
2737 }
2738 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002739 }
2740
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002741 bool isOperationAuthorized(const sp<IBinder>& token) {
2742 const keymaster1_device_t* dev;
2743 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002744 const keymaster_key_characteristics_t* characteristics;
2745 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002746 return false;
2747 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002748 const hw_auth_token_t* authToken = NULL;
2749 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002750 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002751 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2752 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002753 }
2754
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002755 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002756 if (!checkBinderPermission(P_ADD_AUTH)) {
2757 ALOGW("addAuthToken: permission denied for %d",
2758 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002759 return ::PERMISSION_DENIED;
2760 }
2761 if (length != sizeof(hw_auth_token_t)) {
2762 return KM_ERROR_INVALID_ARGUMENT;
2763 }
2764 hw_auth_token_t* authToken = new hw_auth_token_t;
2765 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2766 // The table takes ownership of authToken.
2767 mAuthTokenTable.AddAuthenticationToken(authToken);
2768 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002769 }
2770
Kenny Root07438c82012-11-02 15:41:02 -07002771private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002772 static const int32_t UID_SELF = -1;
2773
2774 /**
2775 * Get the effective target uid for a binder operation that takes an
2776 * optional uid as the target.
2777 */
2778 inline uid_t getEffectiveUid(int32_t targetUid) {
2779 if (targetUid == UID_SELF) {
2780 return IPCThreadState::self()->getCallingUid();
2781 }
2782 return static_cast<uid_t>(targetUid);
2783 }
2784
2785 /**
2786 * Check if the caller of the current binder method has the required
2787 * permission and if acting on other uids the grants to do so.
2788 */
2789 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2790 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2791 pid_t spid = IPCThreadState::self()->getCallingPid();
2792 if (!has_permission(callingUid, permission, spid)) {
2793 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2794 return false;
2795 }
2796 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2797 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2798 return false;
2799 }
2800 return true;
2801 }
2802
2803 /**
2804 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002805 * permission and the target uid is the caller or the caller is system.
2806 */
2807 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2808 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2809 pid_t spid = IPCThreadState::self()->getCallingPid();
2810 if (!has_permission(callingUid, permission, spid)) {
2811 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2812 return false;
2813 }
2814 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2815 }
2816
2817 /**
2818 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002819 * permission or the target of the operation is the caller's uid. This is
2820 * for operation where the permission is only for cross-uid activity and all
2821 * uids are allowed to act on their own (ie: clearing all entries for a
2822 * given uid).
2823 */
2824 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2825 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2826 if (getEffectiveUid(targetUid) == callingUid) {
2827 return true;
2828 } else {
2829 return checkBinderPermission(permission, targetUid);
2830 }
2831 }
2832
2833 /**
2834 * Helper method to check that the caller has the required permission as
2835 * well as the keystore is in the unlocked state if checkUnlocked is true.
2836 *
2837 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2838 * otherwise the state of keystore when not unlocked and checkUnlocked is
2839 * true.
2840 */
2841 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2842 bool checkUnlocked = true) {
2843 if (!checkBinderPermission(permission, targetUid)) {
2844 return ::PERMISSION_DENIED;
2845 }
2846 State state = mKeyStore->getState(getEffectiveUid(targetUid));
2847 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2848 return state;
2849 }
2850
2851 return ::NO_ERROR;
2852
2853 }
2854
Kenny Root9d45d1c2013-02-14 10:32:30 -08002855 inline bool isKeystoreUnlocked(State state) {
2856 switch (state) {
2857 case ::STATE_NO_ERROR:
2858 return true;
2859 case ::STATE_UNINITIALIZED:
2860 case ::STATE_LOCKED:
2861 return false;
2862 }
2863 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002864 }
2865
Chad Brubaker67d2a502015-03-11 17:21:18 +00002866 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002867 const int32_t device_api = device->common.module->module_api_version;
2868 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2869 switch (keyType) {
2870 case TYPE_RSA:
2871 case TYPE_DSA:
2872 case TYPE_EC:
2873 return true;
2874 default:
2875 return false;
2876 }
2877 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2878 switch (keyType) {
2879 case TYPE_RSA:
2880 return true;
2881 case TYPE_DSA:
2882 return device->flags & KEYMASTER_SUPPORTS_DSA;
2883 case TYPE_EC:
2884 return device->flags & KEYMASTER_SUPPORTS_EC;
2885 default:
2886 return false;
2887 }
2888 } else {
2889 return keyType == TYPE_RSA;
2890 }
2891 }
2892
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002893 /**
2894 * Check that all keymaster_key_param_t's provided by the application are
2895 * allowed. Any parameter that keystore adds itself should be disallowed here.
2896 */
2897 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2898 for (auto param: params) {
2899 switch (param.tag) {
2900 case KM_TAG_AUTH_TOKEN:
2901 return false;
2902 default:
2903 break;
2904 }
2905 }
2906 return true;
2907 }
2908
2909 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2910 const keymaster1_device_t* dev,
2911 const std::vector<keymaster_key_param_t>& params,
2912 keymaster_key_characteristics_t* out) {
2913 UniquePtr<keymaster_blob_t> appId;
2914 UniquePtr<keymaster_blob_t> appData;
2915 for (auto param : params) {
2916 if (param.tag == KM_TAG_APPLICATION_ID) {
2917 appId.reset(new keymaster_blob_t);
2918 appId->data = param.blob.data;
2919 appId->data_length = param.blob.data_length;
2920 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2921 appData.reset(new keymaster_blob_t);
2922 appData->data = param.blob.data;
2923 appData->data_length = param.blob.data_length;
2924 }
2925 }
2926 keymaster_key_characteristics_t* result = NULL;
2927 if (!dev->get_key_characteristics) {
2928 return KM_ERROR_UNIMPLEMENTED;
2929 }
2930 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2931 appData.get(), &result);
2932 if (result) {
2933 *out = *result;
2934 free(result);
2935 }
2936 return error;
2937 }
2938
2939 /**
2940 * Get the auth token for this operation from the auth token table.
2941 *
2942 * Returns ::NO_ERROR if the auth token was set or none was required.
2943 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2944 * authorization token exists for that operation and
2945 * failOnTokenMissing is false.
2946 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2947 * token for the operation
2948 */
2949 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2950 keymaster_operation_handle_t handle,
2951 const hw_auth_token_t** authToken,
2952 bool failOnTokenMissing = true) {
2953
2954 std::vector<keymaster_key_param_t> allCharacteristics;
2955 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2956 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2957 }
2958 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2959 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2960 }
2961 keymaster::AuthTokenTable::Error err =
2962 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2963 allCharacteristics.size(), handle, authToken);
2964 switch (err) {
2965 case keymaster::AuthTokenTable::OK:
2966 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2967 return ::NO_ERROR;
2968 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2969 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2970 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2971 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2972 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2973 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2974 (int32_t) ::OP_AUTH_NEEDED;
2975 default:
2976 ALOGE("Unexpected FindAuthorization return value %d", err);
2977 return KM_ERROR_INVALID_ARGUMENT;
2978 }
2979 }
2980
2981 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2982 const hw_auth_token_t* token) {
2983 if (token) {
2984 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2985 reinterpret_cast<const uint8_t*>(token),
2986 sizeof(hw_auth_token_t)));
2987 }
2988 }
2989
2990 /**
2991 * Add the auth token for the operation to the param list if the operation
2992 * requires authorization. Uses the cached result in the OperationMap if available
2993 * otherwise gets the token from the AuthTokenTable and caches the result.
2994 *
2995 * Returns ::NO_ERROR if the auth token was added or not needed.
2996 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2997 * authenticated.
2998 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2999 * operation token.
3000 */
3001 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3002 std::vector<keymaster_key_param_t>* params) {
3003 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003004 mOperationMap.getOperationAuthToken(token, &authToken);
3005 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003006 const keymaster1_device_t* dev;
3007 keymaster_operation_handle_t handle;
3008 const keymaster_key_characteristics_t* characteristics = NULL;
3009 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3010 return KM_ERROR_INVALID_OPERATION_HANDLE;
3011 }
3012 int32_t result = getAuthToken(characteristics, handle, &authToken);
3013 if (result != ::NO_ERROR) {
3014 return result;
3015 }
3016 if (authToken) {
3017 mOperationMap.setOperationAuthToken(token, authToken);
3018 }
3019 }
3020 addAuthToParams(params, authToken);
3021 return ::NO_ERROR;
3022 }
3023
Kenny Root07438c82012-11-02 15:41:02 -07003024 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003025 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003026 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003027};
3028
3029}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003030
3031int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003032 if (argc < 2) {
3033 ALOGE("A directory must be specified!");
3034 return 1;
3035 }
3036 if (chdir(argv[1]) == -1) {
3037 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3038 return 1;
3039 }
3040
3041 Entropy entropy;
3042 if (!entropy.open()) {
3043 return 1;
3044 }
Kenny Root70e3a862012-02-15 17:20:23 -08003045
Shawn Willden80843db2015-02-24 09:31:25 -07003046 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003047 if (keymaster_device_initialize(&dev)) {
3048 ALOGE("keystore keymaster could not be initialized; exiting");
3049 return 1;
3050 }
3051
Chad Brubaker67d2a502015-03-11 17:21:18 +00003052 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003053 if (fallback_keymaster_device_initialize(&fallback)) {
3054 ALOGE("software keymaster could not be initialized; exiting");
3055 return 1;
3056 }
3057
Riley Spahneaabae92014-06-30 12:39:52 -07003058 ks_is_selinux_enabled = is_selinux_enabled();
3059 if (ks_is_selinux_enabled) {
3060 union selinux_callback cb;
3061 cb.func_log = selinux_log_callback;
3062 selinux_set_callback(SELINUX_CB_LOG, cb);
3063 if (getcon(&tctx) != 0) {
3064 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3065 return -1;
3066 }
3067 } else {
3068 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3069 }
3070
Chad Brubaker67d2a502015-03-11 17:21:18 +00003071 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003072 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003073 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3074 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3075 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3076 if (ret != android::OK) {
3077 ALOGE("Couldn't register binder service!");
3078 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003079 }
Kenny Root07438c82012-11-02 15:41:02 -07003080
3081 /*
3082 * We're the only thread in existence, so we're just going to process
3083 * Binder transaction as a single-threaded program.
3084 */
3085 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003086
3087 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003088 return 1;
3089}