blob: 12d3b44a62a2ddaae77dd704b31d0d1f553b5cc4 [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>
23#include <unistd.h>
24#include <signal.h>
25#include <errno.h>
26#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070027#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080028#include <fcntl.h>
29#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070030#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080031#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <arpa/inet.h>
36
37#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070038#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080039#include <openssl/evp.h>
40#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070041#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080042
Kenny Root70e3a862012-02-15 17:20:23 -080043#include <hardware/keymaster.h>
44
Kenny Root655b9582013-04-04 08:37:42 -070045#include <utils/String8.h>
Kenny Root822c3a92012-03-23 16:34:39 -070046#include <utils/UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070047#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080048
Kenny Root07438c82012-11-02 15:41:02 -070049#include <keystore/IKeystoreService.h>
50#include <binder/IPCThreadState.h>
51#include <binder/IServiceManager.h>
52
Kenny Roota91203b2012-02-15 15:00:46 -080053#include <cutils/log.h>
54#include <cutils/sockets.h>
55#include <private/android_filesystem_config.h>
56
Kenny Root07438c82012-11-02 15:41:02 -070057#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080058
Kenny Root96427ba2013-08-16 14:02:41 -070059#include "defaults.h"
60
Kenny Roota91203b2012-02-15 15:00:46 -080061/* KeyStore is a secured storage for key-value pairs. In this implementation,
62 * each file stores one key-value pair. Keys are encoded in file names, and
63 * values are encrypted with checksums. The encryption key is protected by a
64 * user-defined password. To keep things simple, buffers are always larger than
65 * the maximum space we needed, so boundary checks on buffers are omitted. */
66
67#define KEY_SIZE ((NAME_MAX - 15) / 2)
68#define VALUE_SIZE 32768
69#define PASSWORD_SIZE VALUE_SIZE
70
Kenny Root822c3a92012-03-23 16:34:39 -070071
Kenny Root96427ba2013-08-16 14:02:41 -070072struct BIGNUM_Delete {
73 void operator()(BIGNUM* p) const {
74 BN_free(p);
75 }
76};
77typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
78
Kenny Root822c3a92012-03-23 16:34:39 -070079struct BIO_Delete {
80 void operator()(BIO* p) const {
81 BIO_free(p);
82 }
83};
84typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
85
86struct EVP_PKEY_Delete {
87 void operator()(EVP_PKEY* p) const {
88 EVP_PKEY_free(p);
89 }
90};
91typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
92
93struct PKCS8_PRIV_KEY_INFO_Delete {
94 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
95 PKCS8_PRIV_KEY_INFO_free(p);
96 }
97};
98typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
99
100
Kenny Root70e3a862012-02-15 17:20:23 -0800101static int keymaster_device_initialize(keymaster_device_t** dev) {
102 int rc;
103
104 const hw_module_t* mod;
105 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
106 if (rc) {
107 ALOGE("could not find any keystore module");
108 goto out;
109 }
110
111 rc = keymaster_open(mod, dev);
112 if (rc) {
113 ALOGE("could not open keymaster device in %s (%s)",
114 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
115 goto out;
116 }
117
118 return 0;
119
120out:
121 *dev = NULL;
122 return rc;
123}
124
125static void keymaster_device_release(keymaster_device_t* dev) {
126 keymaster_close(dev);
127}
128
Kenny Root07438c82012-11-02 15:41:02 -0700129/***************
130 * PERMISSIONS *
131 ***************/
132
133/* Here are the permissions, actions, users, and the main function. */
134typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700135 P_TEST = 1 << 0,
136 P_GET = 1 << 1,
137 P_INSERT = 1 << 2,
138 P_DELETE = 1 << 3,
139 P_EXIST = 1 << 4,
140 P_SAW = 1 << 5,
141 P_RESET = 1 << 6,
142 P_PASSWORD = 1 << 7,
143 P_LOCK = 1 << 8,
144 P_UNLOCK = 1 << 9,
145 P_ZERO = 1 << 10,
146 P_SIGN = 1 << 11,
147 P_VERIFY = 1 << 12,
148 P_GRANT = 1 << 13,
149 P_DUPLICATE = 1 << 14,
Kenny Roota9bb5492013-04-01 16:29:11 -0700150 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700151} perm_t;
152
153static struct user_euid {
154 uid_t uid;
155 uid_t euid;
156} user_euids[] = {
157 {AID_VPN, AID_SYSTEM},
158 {AID_WIFI, AID_SYSTEM},
159 {AID_ROOT, AID_SYSTEM},
160};
161
162static struct user_perm {
163 uid_t uid;
164 perm_t perms;
165} user_perms[] = {
166 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
167 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
168 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
169 {AID_ROOT, static_cast<perm_t>(P_GET) },
170};
171
172static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
173 | P_VERIFY);
174
Kenny Root655b9582013-04-04 08:37:42 -0700175/**
176 * Returns the app ID (in the Android multi-user sense) for the current
177 * UNIX UID.
178 */
179static uid_t get_app_id(uid_t uid) {
180 return uid % AID_USER;
181}
182
183/**
184 * Returns the user ID (in the Android multi-user sense) for the current
185 * UNIX UID.
186 */
187static uid_t get_user_id(uid_t uid) {
188 return uid / AID_USER;
189}
190
191
Kenny Root07438c82012-11-02 15:41:02 -0700192static bool has_permission(uid_t uid, perm_t perm) {
Kenny Root655b9582013-04-04 08:37:42 -0700193 // All system users are equivalent for multi-user support.
194 if (get_app_id(uid) == AID_SYSTEM) {
195 uid = AID_SYSTEM;
196 }
197
Kenny Root07438c82012-11-02 15:41:02 -0700198 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
199 struct user_perm user = user_perms[i];
200 if (user.uid == uid) {
201 return user.perms & perm;
202 }
203 }
204
205 return DEFAULT_PERMS & perm;
206}
207
Kenny Root49468902013-03-19 13:41:33 -0700208/**
209 * Returns the UID that the callingUid should act as. This is here for
210 * legacy support of the WiFi and VPN systems and should be removed
211 * when WiFi can operate in its own namespace.
212 */
Kenny Root07438c82012-11-02 15:41:02 -0700213static uid_t get_keystore_euid(uid_t uid) {
214 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
215 struct user_euid user = user_euids[i];
216 if (user.uid == uid) {
217 return user.euid;
218 }
219 }
220
221 return uid;
222}
223
Kenny Root49468902013-03-19 13:41:33 -0700224/**
225 * Returns true if the callingUid is allowed to interact in the targetUid's
226 * namespace.
227 */
228static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
229 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
230 struct user_euid user = user_euids[i];
231 if (user.euid == callingUid && user.uid == targetUid) {
232 return true;
233 }
234 }
235
236 return false;
237}
238
Kenny Roota91203b2012-02-15 15:00:46 -0800239/* Here is the encoding of keys. This is necessary in order to allow arbitrary
240 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
241 * into two bytes. The first byte is one of [+-.] which represents the first
242 * two bits of the character. The second byte encodes the rest of the bits into
243 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
244 * that Base64 cannot be used here due to the need of prefix match on keys. */
245
Kenny Root655b9582013-04-04 08:37:42 -0700246static size_t encode_key_length(const android::String8& keyName) {
247 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
248 size_t length = keyName.length();
249 for (int i = length; i > 0; --i, ++in) {
250 if (*in < '0' || *in > '~') {
251 ++length;
252 }
253 }
254 return length;
255}
256
Kenny Root07438c82012-11-02 15:41:02 -0700257static int encode_key(char* out, const android::String8& keyName) {
258 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
259 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800260 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700261 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800262 *out = '+' + (*in >> 6);
263 *++out = '0' + (*in & 0x3F);
264 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700265 } else {
266 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800267 }
268 }
269 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800270 return length;
271}
272
Kenny Root07438c82012-11-02 15:41:02 -0700273static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800274 int n = snprintf(out, NAME_MAX, "%u_", uid);
275 out += n;
276
Kenny Root07438c82012-11-02 15:41:02 -0700277 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800278}
279
Kenny Root07438c82012-11-02 15:41:02 -0700280/*
281 * Converts from the "escaped" format on disk to actual name.
282 * This will be smaller than the input string.
283 *
284 * Characters that should combine with the next at the end will be truncated.
285 */
286static size_t decode_key_length(const char* in, size_t length) {
287 size_t outLength = 0;
288
289 for (const char* end = in + length; in < end; in++) {
290 /* This combines with the next character. */
291 if (*in < '0' || *in > '~') {
292 continue;
293 }
294
295 outLength++;
296 }
297 return outLength;
298}
299
300static void decode_key(char* out, const char* in, size_t length) {
301 for (const char* end = in + length; in < end; in++) {
302 if (*in < '0' || *in > '~') {
303 /* Truncate combining characters at the end. */
304 if (in + 1 >= end) {
305 break;
306 }
307
308 *out = (*in++ - '+') << 6;
309 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800310 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700311 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800312 }
313 }
314 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800315}
316
317static size_t readFully(int fd, uint8_t* data, size_t size) {
318 size_t remaining = size;
319 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800320 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800321 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800322 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800323 }
324 data += n;
325 remaining -= n;
326 }
327 return size;
328}
329
330static size_t writeFully(int fd, uint8_t* data, size_t size) {
331 size_t remaining = size;
332 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800333 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
334 if (n < 0) {
335 ALOGW("write failed: %s", strerror(errno));
336 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800337 }
338 data += n;
339 remaining -= n;
340 }
341 return size;
342}
343
344class Entropy {
345public:
346 Entropy() : mRandom(-1) {}
347 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800348 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800349 close(mRandom);
350 }
351 }
352
353 bool open() {
354 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800355 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
356 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800357 ALOGE("open: %s: %s", randomDevice, strerror(errno));
358 return false;
359 }
360 return true;
361 }
362
Kenny Root51878182012-03-13 12:53:19 -0700363 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800364 return (readFully(mRandom, data, size) == size);
365 }
366
367private:
368 int mRandom;
369};
370
371/* Here is the file format. There are two parts in blob.value, the secret and
372 * the description. The secret is stored in ciphertext, and its original size
373 * can be found in blob.length. The description is stored after the secret in
374 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700375 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700376 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800377 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
378 * and decryptBlob(). Thus they should not be accessed from outside. */
379
Kenny Root822c3a92012-03-23 16:34:39 -0700380/* ** Note to future implementors of encryption: **
381 * Currently this is the construction:
382 * metadata || Enc(MD5(data) || data)
383 *
384 * This should be the construction used for encrypting if re-implementing:
385 *
386 * Derive independent keys for encryption and MAC:
387 * Kenc = AES_encrypt(masterKey, "Encrypt")
388 * Kmac = AES_encrypt(masterKey, "MAC")
389 *
390 * Store this:
391 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
392 * HMAC(Kmac, metadata || Enc(data))
393 */
Kenny Roota91203b2012-02-15 15:00:46 -0800394struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700395 uint8_t version;
396 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700397 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800398 uint8_t info;
399 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700400 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800401 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700402 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800403 int32_t length; // in network byte order when encrypted
404 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
405};
406
Kenny Root822c3a92012-03-23 16:34:39 -0700407typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700408 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700409 TYPE_GENERIC = 1,
410 TYPE_MASTER_KEY = 2,
411 TYPE_KEY_PAIR = 3,
412} BlobType;
413
Kenny Rootf9119d62013-04-03 09:22:15 -0700414static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700415
Kenny Roota91203b2012-02-15 15:00:46 -0800416class Blob {
417public:
Kenny Root07438c82012-11-02 15:41:02 -0700418 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
419 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800420 mBlob.length = valueLength;
421 memcpy(mBlob.value, value, valueLength);
422
423 mBlob.info = infoLength;
424 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700425
Kenny Root07438c82012-11-02 15:41:02 -0700426 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700427 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700428
429 mBlob.flags = KEYSTORE_FLAG_NONE;
Kenny Roota91203b2012-02-15 15:00:46 -0800430 }
431
432 Blob(blob b) {
433 mBlob = b;
434 }
435
436 Blob() {}
437
Kenny Root51878182012-03-13 12:53:19 -0700438 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800439 return mBlob.value;
440 }
441
Kenny Root51878182012-03-13 12:53:19 -0700442 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800443 return mBlob.length;
444 }
445
Kenny Root51878182012-03-13 12:53:19 -0700446 const uint8_t* getInfo() const {
447 return mBlob.value + mBlob.length;
448 }
449
450 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800451 return mBlob.info;
452 }
453
Kenny Root822c3a92012-03-23 16:34:39 -0700454 uint8_t getVersion() const {
455 return mBlob.version;
456 }
457
Kenny Rootf9119d62013-04-03 09:22:15 -0700458 bool isEncrypted() const {
459 if (mBlob.version < 2) {
460 return true;
461 }
462
463 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
464 }
465
466 void setEncrypted(bool encrypted) {
467 if (encrypted) {
468 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
469 } else {
470 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
471 }
472 }
473
Kenny Root822c3a92012-03-23 16:34:39 -0700474 void setVersion(uint8_t version) {
475 mBlob.version = version;
476 }
477
478 BlobType getType() const {
479 return BlobType(mBlob.type);
480 }
481
482 void setType(BlobType type) {
483 mBlob.type = uint8_t(type);
484 }
485
Kenny Rootf9119d62013-04-03 09:22:15 -0700486 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
487 ALOGV("writing blob %s", filename);
488 if (isEncrypted()) {
489 if (state != STATE_NO_ERROR) {
490 ALOGD("couldn't insert encrypted blob while not unlocked");
491 return LOCKED;
492 }
493
494 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
495 ALOGW("Could not read random data for: %s", filename);
496 return SYSTEM_ERROR;
497 }
Kenny Roota91203b2012-02-15 15:00:46 -0800498 }
499
500 // data includes the value and the value's length
501 size_t dataLength = mBlob.length + sizeof(mBlob.length);
502 // pad data to the AES_BLOCK_SIZE
503 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
504 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
505 // encrypted data includes the digest value
506 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
507 // move info after space for padding
508 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
509 // zero padding area
510 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
511
512 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800513
Kenny Rootf9119d62013-04-03 09:22:15 -0700514 if (isEncrypted()) {
515 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800516
Kenny Rootf9119d62013-04-03 09:22:15 -0700517 uint8_t vector[AES_BLOCK_SIZE];
518 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
519 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
520 aes_key, vector, AES_ENCRYPT);
521 }
522
Kenny Roota91203b2012-02-15 15:00:46 -0800523 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
524 size_t fileLength = encryptedLength + headerLength + mBlob.info;
525
526 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800527 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
528 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
529 if (out < 0) {
530 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800531 return SYSTEM_ERROR;
532 }
533 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
534 if (close(out) != 0) {
535 return SYSTEM_ERROR;
536 }
537 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800538 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800539 unlink(tmpFileName);
540 return SYSTEM_ERROR;
541 }
Kenny Root150ca932012-11-14 14:29:02 -0800542 if (rename(tmpFileName, filename) == -1) {
543 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
544 return SYSTEM_ERROR;
545 }
546 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800547 }
548
Kenny Rootf9119d62013-04-03 09:22:15 -0700549 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
550 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800551 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
552 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800553 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
554 }
555 // fileLength may be less than sizeof(mBlob) since the in
556 // memory version has extra padding to tolerate rounding up to
557 // the AES_BLOCK_SIZE
558 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
559 if (close(in) != 0) {
560 return SYSTEM_ERROR;
561 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700562
563 if (isEncrypted() && (state != STATE_NO_ERROR)) {
564 return LOCKED;
565 }
566
Kenny Roota91203b2012-02-15 15:00:46 -0800567 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
568 if (fileLength < headerLength) {
569 return VALUE_CORRUPTED;
570 }
571
572 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700573 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800574 return VALUE_CORRUPTED;
575 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700576
577 ssize_t digestedLength;
578 if (isEncrypted()) {
579 if (encryptedLength % AES_BLOCK_SIZE != 0) {
580 return VALUE_CORRUPTED;
581 }
582
583 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
584 mBlob.vector, AES_DECRYPT);
585 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
586 uint8_t computedDigest[MD5_DIGEST_LENGTH];
587 MD5(mBlob.digested, digestedLength, computedDigest);
588 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
589 return VALUE_CORRUPTED;
590 }
591 } else {
592 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800593 }
594
595 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
596 mBlob.length = ntohl(mBlob.length);
597 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
598 return VALUE_CORRUPTED;
599 }
600 if (mBlob.info != 0) {
601 // move info from after padding to after data
602 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
603 }
Kenny Root07438c82012-11-02 15:41:02 -0700604 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800605 }
606
607private:
608 struct blob mBlob;
609};
610
Kenny Root655b9582013-04-04 08:37:42 -0700611class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800612public:
Kenny Root655b9582013-04-04 08:37:42 -0700613 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
614 asprintf(&mUserDir, "user_%u", mUserId);
615 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
616 }
617
618 ~UserState() {
619 free(mUserDir);
620 free(mMasterKeyFile);
621 }
622
623 bool initialize() {
624 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
625 ALOGE("Could not create directory '%s'", mUserDir);
626 return false;
627 }
628
629 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800630 setState(STATE_LOCKED);
631 } else {
632 setState(STATE_UNINITIALIZED);
633 }
Kenny Root70e3a862012-02-15 17:20:23 -0800634
Kenny Root655b9582013-04-04 08:37:42 -0700635 return true;
636 }
637
638 uid_t getUserId() const {
639 return mUserId;
640 }
641
642 const char* getUserDirName() const {
643 return mUserDir;
644 }
645
646 const char* getMasterKeyFileName() const {
647 return mMasterKeyFile;
648 }
649
650 void setState(State state) {
651 mState = state;
652 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
653 mRetry = MAX_RETRY;
654 }
Kenny Roota91203b2012-02-15 15:00:46 -0800655 }
656
Kenny Root51878182012-03-13 12:53:19 -0700657 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800658 return mState;
659 }
660
Kenny Root51878182012-03-13 12:53:19 -0700661 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800662 return mRetry;
663 }
664
Kenny Root655b9582013-04-04 08:37:42 -0700665 void zeroizeMasterKeysInMemory() {
666 memset(mMasterKey, 0, sizeof(mMasterKey));
667 memset(mSalt, 0, sizeof(mSalt));
668 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
669 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800670 }
671
Kenny Root655b9582013-04-04 08:37:42 -0700672 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
673 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800674 return SYSTEM_ERROR;
675 }
Kenny Root655b9582013-04-04 08:37:42 -0700676 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800677 if (response != NO_ERROR) {
678 return response;
679 }
680 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700681 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800682 }
683
Kenny Root655b9582013-04-04 08:37:42 -0700684 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800685 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
686 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
687 AES_KEY passwordAesKey;
688 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700689 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700690 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800691 }
692
Kenny Root655b9582013-04-04 08:37:42 -0700693 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
694 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800695 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800696 return SYSTEM_ERROR;
697 }
698
699 // we read the raw blob to just to get the salt to generate
700 // the AES key, then we create the Blob to use with decryptBlob
701 blob rawBlob;
702 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
703 if (close(in) != 0) {
704 return SYSTEM_ERROR;
705 }
706 // find salt at EOF if present, otherwise we have an old file
707 uint8_t* salt;
708 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
709 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
710 } else {
711 salt = NULL;
712 }
713 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
714 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
715 AES_KEY passwordAesKey;
716 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
717 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700718 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
719 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800720 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700721 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800722 }
723 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
724 // if salt was missing, generate one and write a new master key file with the salt.
725 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700726 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800727 return SYSTEM_ERROR;
728 }
Kenny Root655b9582013-04-04 08:37:42 -0700729 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800730 }
731 if (response == NO_ERROR) {
732 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
733 setupMasterKeys();
734 }
735 return response;
736 }
737 if (mRetry <= 0) {
738 reset();
739 return UNINITIALIZED;
740 }
741 --mRetry;
742 switch (mRetry) {
743 case 0: return WRONG_PASSWORD_0;
744 case 1: return WRONG_PASSWORD_1;
745 case 2: return WRONG_PASSWORD_2;
746 case 3: return WRONG_PASSWORD_3;
747 default: return WRONG_PASSWORD_3;
748 }
749 }
750
Kenny Root655b9582013-04-04 08:37:42 -0700751 AES_KEY* getEncryptionKey() {
752 return &mMasterKeyEncryption;
753 }
754
755 AES_KEY* getDecryptionKey() {
756 return &mMasterKeyDecryption;
757 }
758
Kenny Roota91203b2012-02-15 15:00:46 -0800759 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700760 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800761 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700762 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800763 return false;
764 }
Kenny Root655b9582013-04-04 08:37:42 -0700765
766 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800767 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700768 // We only care about files.
769 if (file->d_type != DT_REG) {
770 continue;
771 }
772
773 // Skip anything that starts with a "."
774 if (file->d_name[0] == '.') {
775 continue;
776 }
777
778 // Find the current file's UID.
779 char* end;
780 unsigned long thisUid = strtoul(file->d_name, &end, 10);
781 if (end[0] != '_' || end[1] == 0) {
782 continue;
783 }
784
785 // Skip if this is not our user.
786 if (get_user_id(thisUid) != mUserId) {
787 continue;
788 }
789
790 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800791 }
792 closedir(dir);
793 return true;
794 }
795
Kenny Root655b9582013-04-04 08:37:42 -0700796private:
797 static const int MASTER_KEY_SIZE_BYTES = 16;
798 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
799
800 static const int MAX_RETRY = 4;
801 static const size_t SALT_SIZE = 16;
802
803 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
804 uint8_t* salt) {
805 size_t saltSize;
806 if (salt != NULL) {
807 saltSize = SALT_SIZE;
808 } else {
809 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
810 salt = (uint8_t*) "keystore";
811 // sizeof = 9, not strlen = 8
812 saltSize = sizeof("keystore");
813 }
814
815 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
816 saltSize, 8192, keySize, key);
817 }
818
819 bool generateSalt(Entropy* entropy) {
820 return entropy->generate_random_data(mSalt, sizeof(mSalt));
821 }
822
823 bool generateMasterKey(Entropy* entropy) {
824 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
825 return false;
826 }
827 if (!generateSalt(entropy)) {
828 return false;
829 }
830 return true;
831 }
832
833 void setupMasterKeys() {
834 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
835 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
836 setState(STATE_NO_ERROR);
837 }
838
839 uid_t mUserId;
840
841 char* mUserDir;
842 char* mMasterKeyFile;
843
844 State mState;
845 int8_t mRetry;
846
847 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
848 uint8_t mSalt[SALT_SIZE];
849
850 AES_KEY mMasterKeyEncryption;
851 AES_KEY mMasterKeyDecryption;
852};
853
854typedef struct {
855 uint32_t uid;
856 const uint8_t* filename;
857} grant_t;
858
859class KeyStore {
860public:
861 KeyStore(Entropy* entropy, keymaster_device_t* device)
862 : mEntropy(entropy)
863 , mDevice(device)
864 {
865 memset(&mMetaData, '\0', sizeof(mMetaData));
866 }
867
868 ~KeyStore() {
869 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
870 it != mGrants.end(); it++) {
871 delete *it;
872 mGrants.erase(it);
873 }
874
875 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
876 it != mMasterKeys.end(); it++) {
877 delete *it;
878 mMasterKeys.erase(it);
879 }
880 }
881
882 keymaster_device_t* getDevice() const {
883 return mDevice;
884 }
885
886 ResponseCode initialize() {
887 readMetaData();
888 if (upgradeKeystore()) {
889 writeMetaData();
890 }
891
892 return ::NO_ERROR;
893 }
894
895 State getState(uid_t uid) {
896 return getUserState(uid)->getState();
897 }
898
899 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
900 UserState* userState = getUserState(uid);
901 return userState->initialize(pw, mEntropy);
902 }
903
904 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
905 uid_t user_id = get_user_id(uid);
906 UserState* userState = getUserState(user_id);
907 return userState->writeMasterKey(pw, mEntropy);
908 }
909
910 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
911 uid_t user_id = get_user_id(uid);
912 UserState* userState = getUserState(user_id);
913 return userState->readMasterKey(pw, mEntropy);
914 }
915
916 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700917 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700918 encode_key(encoded, keyName);
919 return android::String8(encoded);
920 }
921
922 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700923 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700924 encode_key(encoded, keyName);
925 return android::String8::format("%u_%s", uid, encoded);
926 }
927
928 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700929 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700930 encode_key(encoded, keyName);
931 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
932 encoded);
933 }
934
935 bool reset(uid_t uid) {
936 UserState* userState = getUserState(uid);
937 userState->zeroizeMasterKeysInMemory();
938 userState->setState(STATE_UNINITIALIZED);
939 return userState->reset();
940 }
941
942 bool isEmpty(uid_t uid) const {
943 const UserState* userState = getUserState(uid);
944 if (userState == NULL) {
945 return true;
946 }
947
948 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800949 struct dirent* file;
950 if (!dir) {
951 return true;
952 }
953 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -0700954
955 char filename[NAME_MAX];
956 int n = snprintf(filename, sizeof(filename), "%u_", uid);
957
Kenny Roota91203b2012-02-15 15:00:46 -0800958 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700959 // We only care about files.
960 if (file->d_type != DT_REG) {
961 continue;
962 }
963
964 // Skip anything that starts with a "."
965 if (file->d_name[0] == '.') {
966 continue;
967 }
968
969 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800970 result = false;
971 break;
972 }
973 }
974 closedir(dir);
975 return result;
976 }
977
Kenny Root655b9582013-04-04 08:37:42 -0700978 void lock(uid_t uid) {
979 UserState* userState = getUserState(uid);
980 userState->zeroizeMasterKeysInMemory();
981 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -0800982 }
983
Kenny Root655b9582013-04-04 08:37:42 -0700984 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
985 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -0700986 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
987 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -0700988 if (rc != NO_ERROR) {
989 return rc;
990 }
991
992 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700993 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -0700994 /* If we upgrade the key, we need to write it to disk again. Then
995 * it must be read it again since the blob is encrypted each time
996 * it's written.
997 */
Kenny Root655b9582013-04-04 08:37:42 -0700998 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
999 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001000 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1001 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001002 return rc;
1003 }
1004 }
Kenny Root822c3a92012-03-23 16:34:39 -07001005 }
1006
Kenny Rootd53bc922013-03-21 14:10:15 -07001007 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001008 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1009 return KEY_NOT_FOUND;
1010 }
1011
1012 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001013 }
1014
Kenny Root655b9582013-04-04 08:37:42 -07001015 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1016 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001017 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1018 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001019 }
1020
Kenny Root07438c82012-11-02 15:41:02 -07001021 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001022 const grant_t* existing = getGrant(filename, granteeUid);
1023 if (existing == NULL) {
1024 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001025 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001026 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001027 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001028 }
1029 }
1030
Kenny Root07438c82012-11-02 15:41:02 -07001031 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001032 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1033 it != mGrants.end(); it++) {
1034 grant_t* grant = *it;
1035 if (grant->uid == granteeUid
1036 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1037 mGrants.erase(it);
1038 return true;
1039 }
Kenny Root70e3a862012-02-15 17:20:23 -08001040 }
Kenny Root70e3a862012-02-15 17:20:23 -08001041 return false;
1042 }
1043
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001044 bool hasGrant(const char* filename, const uid_t uid) const {
1045 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001046 }
1047
Kenny Rootf9119d62013-04-03 09:22:15 -07001048 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1049 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001050 uint8_t* data;
1051 size_t dataLength;
1052 int rc;
1053
1054 if (mDevice->import_keypair == NULL) {
1055 ALOGE("Keymaster doesn't support import!");
1056 return SYSTEM_ERROR;
1057 }
1058
Kenny Root07438c82012-11-02 15:41:02 -07001059 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001060 if (rc) {
1061 ALOGE("Error while importing keypair: %d", rc);
1062 return SYSTEM_ERROR;
1063 }
1064
1065 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1066 free(data);
1067
Kenny Rootf9119d62013-04-03 09:22:15 -07001068 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1069
Kenny Root655b9582013-04-04 08:37:42 -07001070 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001071 }
1072
Kenny Root8ddf35a2013-03-29 11:15:50 -07001073 bool isHardwareBacked() const {
Kenny Root483407e2013-04-04 17:12:25 -07001074 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07001075 }
1076
Kenny Root655b9582013-04-04 08:37:42 -07001077 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1078 const BlobType type) {
1079 char filename[NAME_MAX];
1080 encode_key_for_uid(filename, uid, keyName);
1081
1082 UserState* userState = getUserState(uid);
1083 android::String8 filepath8;
1084
1085 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1086 if (filepath8.string() == NULL) {
1087 ALOGW("can't create filepath for key %s", filename);
1088 return SYSTEM_ERROR;
1089 }
1090
1091 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1092 if (responseCode == NO_ERROR) {
1093 return responseCode;
1094 }
1095
1096 // If this is one of the legacy UID->UID mappings, use it.
1097 uid_t euid = get_keystore_euid(uid);
1098 if (euid != uid) {
1099 encode_key_for_uid(filename, euid, keyName);
1100 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1101 responseCode = get(filepath8.string(), keyBlob, type, uid);
1102 if (responseCode == NO_ERROR) {
1103 return responseCode;
1104 }
1105 }
1106
1107 // They might be using a granted key.
1108 encode_key(filename, keyName);
1109 char* end;
1110 strtoul(filename, &end, 10);
1111 if (end[0] != '_' || end[1] == 0) {
1112 return KEY_NOT_FOUND;
1113 }
1114 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1115 if (!hasGrant(filepath8.string(), uid)) {
1116 return responseCode;
1117 }
1118
1119 // It is a granted key. Try to load it.
1120 return get(filepath8.string(), keyBlob, type, uid);
1121 }
1122
1123 /**
1124 * Returns any existing UserState or creates it if it doesn't exist.
1125 */
1126 UserState* getUserState(uid_t uid) {
1127 uid_t userId = get_user_id(uid);
1128
1129 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1130 it != mMasterKeys.end(); it++) {
1131 UserState* state = *it;
1132 if (state->getUserId() == userId) {
1133 return state;
1134 }
1135 }
1136
1137 UserState* userState = new UserState(userId);
1138 if (!userState->initialize()) {
1139 /* There's not much we can do if initialization fails. Trying to
1140 * unlock the keystore for that user will fail as well, so any
1141 * subsequent request for this user will just return SYSTEM_ERROR.
1142 */
1143 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1144 }
1145 mMasterKeys.add(userState);
1146 return userState;
1147 }
1148
1149 /**
1150 * Returns NULL if the UserState doesn't already exist.
1151 */
1152 const UserState* getUserState(uid_t uid) const {
1153 uid_t userId = get_user_id(uid);
1154
1155 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1156 it != mMasterKeys.end(); it++) {
1157 UserState* state = *it;
1158 if (state->getUserId() == userId) {
1159 return state;
1160 }
1161 }
1162
1163 return NULL;
1164 }
1165
Kenny Roota91203b2012-02-15 15:00:46 -08001166private:
Kenny Root655b9582013-04-04 08:37:42 -07001167 static const char* sOldMasterKey;
1168 static const char* sMetaDataFile;
Kenny Roota91203b2012-02-15 15:00:46 -08001169 Entropy* mEntropy;
1170
Kenny Root70e3a862012-02-15 17:20:23 -08001171 keymaster_device_t* mDevice;
1172
Kenny Root655b9582013-04-04 08:37:42 -07001173 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001174
Kenny Root655b9582013-04-04 08:37:42 -07001175 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001176
Kenny Root655b9582013-04-04 08:37:42 -07001177 typedef struct {
1178 uint32_t version;
1179 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001180
Kenny Root655b9582013-04-04 08:37:42 -07001181 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001182
Kenny Root655b9582013-04-04 08:37:42 -07001183 const grant_t* getGrant(const char* filename, uid_t uid) const {
1184 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1185 it != mGrants.end(); it++) {
1186 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001187 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001188 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001189 return grant;
1190 }
1191 }
Kenny Root70e3a862012-02-15 17:20:23 -08001192 return NULL;
1193 }
1194
Kenny Root822c3a92012-03-23 16:34:39 -07001195 /**
1196 * Upgrade code. This will upgrade the key from the current version
1197 * to whatever is newest.
1198 */
Kenny Root655b9582013-04-04 08:37:42 -07001199 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1200 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001201 bool updated = false;
1202 uint8_t version = oldVersion;
1203
1204 /* From V0 -> V1: All old types were unknown */
1205 if (version == 0) {
1206 ALOGV("upgrading to version 1 and setting type %d", type);
1207
1208 blob->setType(type);
1209 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001210 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001211 }
1212 version = 1;
1213 updated = true;
1214 }
1215
Kenny Rootf9119d62013-04-03 09:22:15 -07001216 /* From V1 -> V2: All old keys were encrypted */
1217 if (version == 1) {
1218 ALOGV("upgrading to version 2");
1219
1220 blob->setEncrypted(true);
1221 version = 2;
1222 updated = true;
1223 }
1224
Kenny Root822c3a92012-03-23 16:34:39 -07001225 /*
1226 * If we've updated, set the key blob to the right version
1227 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001228 */
Kenny Root822c3a92012-03-23 16:34:39 -07001229 if (updated) {
1230 ALOGV("updated and writing file %s", filename);
1231 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001232 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001233
1234 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001235 }
1236
1237 /**
1238 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1239 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1240 * Then it overwrites the original blob with the new blob
1241 * format that is returned from the keymaster.
1242 */
Kenny Root655b9582013-04-04 08:37:42 -07001243 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001244 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1245 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1246 if (b.get() == NULL) {
1247 ALOGE("Problem instantiating BIO");
1248 return SYSTEM_ERROR;
1249 }
1250
1251 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1252 if (pkey.get() == NULL) {
1253 ALOGE("Couldn't read old PEM file");
1254 return SYSTEM_ERROR;
1255 }
1256
1257 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1258 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1259 if (len < 0) {
1260 ALOGE("Couldn't measure PKCS#8 length");
1261 return SYSTEM_ERROR;
1262 }
1263
Kenny Root70c98892013-02-07 09:10:36 -08001264 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1265 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001266 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1267 ALOGE("Couldn't convert to PKCS#8");
1268 return SYSTEM_ERROR;
1269 }
1270
Kenny Rootf9119d62013-04-03 09:22:15 -07001271 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1272 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001273 if (rc != NO_ERROR) {
1274 return rc;
1275 }
1276
Kenny Root655b9582013-04-04 08:37:42 -07001277 return get(filename, blob, TYPE_KEY_PAIR, uid);
1278 }
1279
1280 void readMetaData() {
1281 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1282 if (in < 0) {
1283 return;
1284 }
1285 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1286 if (fileLength != sizeof(mMetaData)) {
1287 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1288 sizeof(mMetaData));
1289 }
1290 close(in);
1291 }
1292
1293 void writeMetaData() {
1294 const char* tmpFileName = ".metadata.tmp";
1295 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1296 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1297 if (out < 0) {
1298 ALOGE("couldn't write metadata file: %s", strerror(errno));
1299 return;
1300 }
1301 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1302 if (fileLength != sizeof(mMetaData)) {
1303 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1304 sizeof(mMetaData));
1305 }
1306 close(out);
1307 rename(tmpFileName, sMetaDataFile);
1308 }
1309
1310 bool upgradeKeystore() {
1311 bool upgraded = false;
1312
1313 if (mMetaData.version == 0) {
1314 UserState* userState = getUserState(0);
1315
1316 // Initialize first so the directory is made.
1317 userState->initialize();
1318
1319 // Migrate the old .masterkey file to user 0.
1320 if (access(sOldMasterKey, R_OK) == 0) {
1321 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1322 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1323 return false;
1324 }
1325 }
1326
1327 // Initialize again in case we had a key.
1328 userState->initialize();
1329
1330 // Try to migrate existing keys.
1331 DIR* dir = opendir(".");
1332 if (!dir) {
1333 // Give up now; maybe we can upgrade later.
1334 ALOGE("couldn't open keystore's directory; something is wrong");
1335 return false;
1336 }
1337
1338 struct dirent* file;
1339 while ((file = readdir(dir)) != NULL) {
1340 // We only care about files.
1341 if (file->d_type != DT_REG) {
1342 continue;
1343 }
1344
1345 // Skip anything that starts with a "."
1346 if (file->d_name[0] == '.') {
1347 continue;
1348 }
1349
1350 // Find the current file's user.
1351 char* end;
1352 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1353 if (end[0] != '_' || end[1] == 0) {
1354 continue;
1355 }
1356 UserState* otherUser = getUserState(thisUid);
1357 if (otherUser->getUserId() != 0) {
1358 unlinkat(dirfd(dir), file->d_name, 0);
1359 }
1360
1361 // Rename the file into user directory.
1362 DIR* otherdir = opendir(otherUser->getUserDirName());
1363 if (otherdir == NULL) {
1364 ALOGW("couldn't open user directory for rename");
1365 continue;
1366 }
1367 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1368 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1369 }
1370 closedir(otherdir);
1371 }
1372 closedir(dir);
1373
1374 mMetaData.version = 1;
1375 upgraded = true;
1376 }
1377
1378 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001379 }
Kenny Roota91203b2012-02-15 15:00:46 -08001380};
1381
Kenny Root655b9582013-04-04 08:37:42 -07001382const char* KeyStore::sOldMasterKey = ".masterkey";
1383const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001384
Kenny Root07438c82012-11-02 15:41:02 -07001385namespace android {
1386class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1387public:
1388 KeyStoreProxy(KeyStore* keyStore)
1389 : mKeyStore(keyStore)
1390 {
Kenny Roota91203b2012-02-15 15:00:46 -08001391 }
Kenny Roota91203b2012-02-15 15:00:46 -08001392
Kenny Root07438c82012-11-02 15:41:02 -07001393 void binderDied(const wp<IBinder>&) {
1394 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001395 }
Kenny Roota91203b2012-02-15 15:00:46 -08001396
Kenny Root07438c82012-11-02 15:41:02 -07001397 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001398 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1399 if (!has_permission(callingUid, P_TEST)) {
1400 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001401 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001402 }
Kenny Roota91203b2012-02-15 15:00:46 -08001403
Kenny Root655b9582013-04-04 08:37:42 -07001404 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001405 }
1406
Kenny Root07438c82012-11-02 15:41:02 -07001407 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001408 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1409 if (!has_permission(callingUid, P_GET)) {
1410 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001411 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001412 }
Kenny Root07438c82012-11-02 15:41:02 -07001413
Kenny Root07438c82012-11-02 15:41:02 -07001414 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001415 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001416
Kenny Root655b9582013-04-04 08:37:42 -07001417 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001418 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001419 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001420 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001421 *item = NULL;
1422 *itemLength = 0;
1423 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001424 }
Kenny Roota91203b2012-02-15 15:00:46 -08001425
Kenny Root07438c82012-11-02 15:41:02 -07001426 *item = (uint8_t*) malloc(keyBlob.getLength());
1427 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1428 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001429
Kenny Root07438c82012-11-02 15:41:02 -07001430 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001431 }
1432
Kenny Rootf9119d62013-04-03 09:22:15 -07001433 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1434 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001435 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1436 if (!has_permission(callingUid, P_INSERT)) {
1437 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001438 return ::PERMISSION_DENIED;
1439 }
Kenny Root07438c82012-11-02 15:41:02 -07001440
Kenny Rootf9119d62013-04-03 09:22:15 -07001441 State state = mKeyStore->getState(callingUid);
1442 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1443 ALOGD("calling get in state: %d", state);
1444 return state;
1445 }
1446
Kenny Root49468902013-03-19 13:41:33 -07001447 if (targetUid == -1) {
1448 targetUid = callingUid;
1449 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001450 return ::PERMISSION_DENIED;
1451 }
1452
Kenny Root07438c82012-11-02 15:41:02 -07001453 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001454 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001455
1456 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Root655b9582013-04-04 08:37:42 -07001457 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001458 }
1459
Kenny Root49468902013-03-19 13:41:33 -07001460 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001461 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1462 if (!has_permission(callingUid, P_DELETE)) {
1463 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001464 return ::PERMISSION_DENIED;
1465 }
Kenny Root70e3a862012-02-15 17:20:23 -08001466
Kenny Root49468902013-03-19 13:41:33 -07001467 if (targetUid == -1) {
1468 targetUid = callingUid;
1469 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001470 return ::PERMISSION_DENIED;
1471 }
1472
Kenny Root07438c82012-11-02 15:41:02 -07001473 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001474 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001475
1476 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001477 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1478 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001479 if (responseCode != ::NO_ERROR) {
1480 return responseCode;
1481 }
1482 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001483 }
1484
Kenny Root49468902013-03-19 13:41:33 -07001485 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001486 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1487 if (!has_permission(callingUid, P_EXIST)) {
1488 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001489 return ::PERMISSION_DENIED;
1490 }
Kenny Root70e3a862012-02-15 17:20:23 -08001491
Kenny Root49468902013-03-19 13:41:33 -07001492 if (targetUid == -1) {
1493 targetUid = callingUid;
1494 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001495 return ::PERMISSION_DENIED;
1496 }
1497
Kenny Root07438c82012-11-02 15:41:02 -07001498 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001499 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001500
Kenny Root655b9582013-04-04 08:37:42 -07001501 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001502 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1503 }
1504 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001505 }
1506
Kenny Root49468902013-03-19 13:41:33 -07001507 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001508 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1509 if (!has_permission(callingUid, P_SAW)) {
1510 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001511 return ::PERMISSION_DENIED;
1512 }
Kenny Root70e3a862012-02-15 17:20:23 -08001513
Kenny Root49468902013-03-19 13:41:33 -07001514 if (targetUid == -1) {
1515 targetUid = callingUid;
1516 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001517 return ::PERMISSION_DENIED;
1518 }
1519
Kenny Root655b9582013-04-04 08:37:42 -07001520 UserState* userState = mKeyStore->getUserState(targetUid);
1521 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001522 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001523 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001524 return ::SYSTEM_ERROR;
1525 }
Kenny Root70e3a862012-02-15 17:20:23 -08001526
Kenny Root07438c82012-11-02 15:41:02 -07001527 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001528 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1529 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001530
Kenny Root07438c82012-11-02 15:41:02 -07001531 struct dirent* file;
1532 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001533 // We only care about files.
1534 if (file->d_type != DT_REG) {
1535 continue;
1536 }
1537
1538 // Skip anything that starts with a "."
1539 if (file->d_name[0] == '.') {
1540 continue;
1541 }
1542
1543 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001544 const char* p = &file->d_name[n];
1545 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001546
Kenny Root07438c82012-11-02 15:41:02 -07001547 size_t extra = decode_key_length(p, plen);
1548 char *match = (char*) malloc(extra + 1);
1549 if (match != NULL) {
1550 decode_key(match, p, plen);
1551 matches->push(String16(match, extra));
1552 free(match);
1553 } else {
1554 ALOGW("could not allocate match of size %zd", extra);
1555 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001556 }
1557 }
Kenny Root07438c82012-11-02 15:41:02 -07001558 closedir(dir);
1559
1560 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001561 }
1562
Kenny Root07438c82012-11-02 15:41:02 -07001563 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001564 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1565 if (!has_permission(callingUid, P_RESET)) {
1566 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001567 return ::PERMISSION_DENIED;
1568 }
1569
Kenny Root655b9582013-04-04 08:37:42 -07001570 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001571
1572 const keymaster_device_t* device = mKeyStore->getDevice();
1573 if (device == NULL) {
1574 ALOGE("No keymaster device!");
1575 return ::SYSTEM_ERROR;
1576 }
1577
1578 if (device->delete_all == NULL) {
1579 ALOGV("keymaster device doesn't implement delete_all");
1580 return rc;
1581 }
1582
1583 if (device->delete_all(device)) {
1584 ALOGE("Problem calling keymaster's delete_all");
1585 return ::SYSTEM_ERROR;
1586 }
1587
Kenny Root9a53d3e2012-08-14 10:47:54 -07001588 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001589 }
1590
Kenny Root07438c82012-11-02 15:41:02 -07001591 /*
1592 * Here is the history. To improve the security, the parameters to generate the
1593 * master key has been changed. To make a seamless transition, we update the
1594 * file using the same password when the user unlock it for the first time. If
1595 * any thing goes wrong during the transition, the new file will not overwrite
1596 * the old one. This avoids permanent damages of the existing data.
1597 */
1598 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001599 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1600 if (!has_permission(callingUid, P_PASSWORD)) {
1601 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001602 return ::PERMISSION_DENIED;
1603 }
Kenny Root70e3a862012-02-15 17:20:23 -08001604
Kenny Root07438c82012-11-02 15:41:02 -07001605 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001606
Kenny Root655b9582013-04-04 08:37:42 -07001607 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001608 case ::STATE_UNINITIALIZED: {
1609 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001610 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001611 }
1612 case ::STATE_NO_ERROR: {
1613 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001614 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001615 }
1616 case ::STATE_LOCKED: {
1617 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001618 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001619 }
1620 }
1621 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001622 }
1623
Kenny Root07438c82012-11-02 15:41:02 -07001624 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001625 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1626 if (!has_permission(callingUid, P_LOCK)) {
1627 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001628 return ::PERMISSION_DENIED;
1629 }
Kenny Root70e3a862012-02-15 17:20:23 -08001630
Kenny Root655b9582013-04-04 08:37:42 -07001631 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001632 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001633 ALOGD("calling lock in state: %d", state);
1634 return state;
1635 }
1636
Kenny Root655b9582013-04-04 08:37:42 -07001637 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001638 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001639 }
1640
Kenny Root07438c82012-11-02 15:41:02 -07001641 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001642 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1643 if (!has_permission(callingUid, P_UNLOCK)) {
1644 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001645 return ::PERMISSION_DENIED;
1646 }
1647
Kenny Root655b9582013-04-04 08:37:42 -07001648 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001649 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001650 ALOGD("calling unlock when not locked");
1651 return state;
1652 }
1653
1654 const String8 password8(pw);
1655 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001656 }
1657
Kenny Root07438c82012-11-02 15:41:02 -07001658 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001659 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1660 if (!has_permission(callingUid, P_ZERO)) {
1661 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001662 return -1;
1663 }
Kenny Root70e3a862012-02-15 17:20:23 -08001664
Kenny Root655b9582013-04-04 08:37:42 -07001665 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001666 }
1667
Kenny Root96427ba2013-08-16 14:02:41 -07001668 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1669 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001670 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1671 if (!has_permission(callingUid, P_INSERT)) {
1672 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001673 return ::PERMISSION_DENIED;
1674 }
Kenny Root70e3a862012-02-15 17:20:23 -08001675
Kenny Root49468902013-03-19 13:41:33 -07001676 if (targetUid == -1) {
1677 targetUid = callingUid;
1678 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001679 return ::PERMISSION_DENIED;
1680 }
1681
Kenny Root655b9582013-04-04 08:37:42 -07001682 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001683 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1684 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001685 return state;
1686 }
Kenny Root70e3a862012-02-15 17:20:23 -08001687
Kenny Root07438c82012-11-02 15:41:02 -07001688 uint8_t* data;
1689 size_t dataLength;
1690 int rc;
1691
1692 const keymaster_device_t* device = mKeyStore->getDevice();
1693 if (device == NULL) {
1694 return ::SYSTEM_ERROR;
1695 }
1696
1697 if (device->generate_keypair == NULL) {
1698 return ::SYSTEM_ERROR;
1699 }
1700
Kenny Root96427ba2013-08-16 14:02:41 -07001701 if (keyType == EVP_PKEY_DSA && device->client_version >= 2) {
1702 keymaster_dsa_keygen_params_t dsa_params;
1703 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001704
Kenny Root96427ba2013-08-16 14:02:41 -07001705 if (keySize == -1) {
1706 keySize = DSA_DEFAULT_KEY_SIZE;
1707 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1708 || keySize > DSA_MAX_KEY_SIZE) {
1709 ALOGI("invalid key size %d", keySize);
1710 return ::SYSTEM_ERROR;
1711 }
1712 dsa_params.key_size = keySize;
1713
1714 if (args->size() == 3) {
1715 sp<KeystoreArg> gArg = args->itemAt(0);
1716 sp<KeystoreArg> pArg = args->itemAt(1);
1717 sp<KeystoreArg> qArg = args->itemAt(2);
1718
1719 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1720 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1721 dsa_params.generator_len = gArg->size();
1722
1723 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1724 dsa_params.prime_p_len = pArg->size();
1725
1726 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1727 dsa_params.prime_q_len = qArg->size();
1728 } else {
1729 ALOGI("not all DSA parameters were read");
1730 return ::SYSTEM_ERROR;
1731 }
1732 } else if (args->size() != 0) {
1733 ALOGI("DSA args must be 3");
1734 return ::SYSTEM_ERROR;
1735 }
1736
1737 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1738 } else if (keyType == EVP_PKEY_EC && device->client_version >= 2) {
1739 keymaster_ec_keygen_params_t ec_params;
1740 memset(&ec_params, '\0', sizeof(ec_params));
1741
1742 if (keySize == -1) {
1743 keySize = EC_DEFAULT_KEY_SIZE;
1744 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1745 ALOGI("invalid key size %d", keySize);
1746 return ::SYSTEM_ERROR;
1747 }
1748 ec_params.field_size = keySize;
1749
1750 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1751 } else if (keyType == EVP_PKEY_RSA) {
1752 keymaster_rsa_keygen_params_t rsa_params;
1753 memset(&rsa_params, '\0', sizeof(rsa_params));
1754 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1755
1756 if (keySize == -1) {
1757 keySize = RSA_DEFAULT_KEY_SIZE;
1758 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1759 ALOGI("invalid key size %d", keySize);
1760 return ::SYSTEM_ERROR;
1761 }
1762 rsa_params.modulus_size = keySize;
1763
1764 if (args->size() > 1) {
1765 ALOGI("invalid number of arguments: %d", args->size());
1766 return ::SYSTEM_ERROR;
1767 } else if (args->size() == 1) {
1768 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1769 if (pubExpBlob != NULL) {
1770 Unique_BIGNUM pubExpBn(
1771 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1772 pubExpBlob->size(), NULL));
1773 if (pubExpBn.get() == NULL) {
1774 ALOGI("Could not convert public exponent to BN");
1775 return ::SYSTEM_ERROR;
1776 }
1777 unsigned long pubExp = BN_get_word(pubExpBn.get());
1778 if (pubExp == 0xFFFFFFFFL) {
1779 ALOGI("cannot represent public exponent as a long value");
1780 return ::SYSTEM_ERROR;
1781 }
1782 rsa_params.public_exponent = pubExp;
1783 }
1784 }
1785
1786 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1787 } else {
1788 ALOGW("Unsupported key type %d", keyType);
1789 rc = -1;
1790 }
1791
Kenny Root07438c82012-11-02 15:41:02 -07001792 if (rc) {
1793 return ::SYSTEM_ERROR;
1794 }
1795
Kenny Root655b9582013-04-04 08:37:42 -07001796 String8 name8(name);
1797 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001798
1799 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1800 free(data);
1801
Kenny Root655b9582013-04-04 08:37:42 -07001802 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001803 }
1804
Kenny Rootf9119d62013-04-03 09:22:15 -07001805 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1806 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001807 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1808 if (!has_permission(callingUid, P_INSERT)) {
1809 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001810 return ::PERMISSION_DENIED;
1811 }
Kenny Root07438c82012-11-02 15:41:02 -07001812
Kenny Root49468902013-03-19 13:41:33 -07001813 if (targetUid == -1) {
1814 targetUid = callingUid;
1815 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001816 return ::PERMISSION_DENIED;
1817 }
1818
Kenny Root655b9582013-04-04 08:37:42 -07001819 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001820 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001821 ALOGD("calling import in state: %d", state);
1822 return state;
1823 }
1824
1825 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001826 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001827
Kenny Rootf9119d62013-04-03 09:22:15 -07001828 return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001829 }
1830
Kenny Root07438c82012-11-02 15:41:02 -07001831 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1832 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001833 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1834 if (!has_permission(callingUid, P_SIGN)) {
1835 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001836 return ::PERMISSION_DENIED;
1837 }
Kenny Root07438c82012-11-02 15:41:02 -07001838
Kenny Root07438c82012-11-02 15:41:02 -07001839 Blob keyBlob;
1840 String8 name8(name);
1841
Kenny Rootd38a0b02013-02-13 12:59:14 -08001842 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001843 int rc;
1844
Kenny Root655b9582013-04-04 08:37:42 -07001845 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001846 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001847 if (responseCode != ::NO_ERROR) {
1848 return responseCode;
1849 }
1850
1851 const keymaster_device_t* device = mKeyStore->getDevice();
1852 if (device == NULL) {
1853 ALOGE("no keymaster device; cannot sign");
1854 return ::SYSTEM_ERROR;
1855 }
1856
1857 if (device->sign_data == NULL) {
1858 ALOGE("device doesn't implement signing");
1859 return ::SYSTEM_ERROR;
1860 }
1861
1862 keymaster_rsa_sign_params_t params;
1863 params.digest_type = DIGEST_NONE;
1864 params.padding_type = PADDING_NONE;
1865
1866 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1867 data, length, out, outLength);
1868 if (rc) {
1869 ALOGW("device couldn't sign data");
1870 return ::SYSTEM_ERROR;
1871 }
1872
1873 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001874 }
1875
Kenny Root07438c82012-11-02 15:41:02 -07001876 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1877 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001878 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1879 if (!has_permission(callingUid, P_VERIFY)) {
1880 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001881 return ::PERMISSION_DENIED;
1882 }
Kenny Root70e3a862012-02-15 17:20:23 -08001883
Kenny Root655b9582013-04-04 08:37:42 -07001884 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001885 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001886 ALOGD("calling verify in state: %d", state);
1887 return state;
1888 }
Kenny Root70e3a862012-02-15 17:20:23 -08001889
Kenny Root07438c82012-11-02 15:41:02 -07001890 Blob keyBlob;
1891 String8 name8(name);
1892 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001893
Kenny Root655b9582013-04-04 08:37:42 -07001894 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001895 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001896 if (responseCode != ::NO_ERROR) {
1897 return responseCode;
1898 }
Kenny Root70e3a862012-02-15 17:20:23 -08001899
Kenny Root07438c82012-11-02 15:41:02 -07001900 const keymaster_device_t* device = mKeyStore->getDevice();
1901 if (device == NULL) {
1902 return ::SYSTEM_ERROR;
1903 }
Kenny Root70e3a862012-02-15 17:20:23 -08001904
Kenny Root07438c82012-11-02 15:41:02 -07001905 if (device->verify_data == NULL) {
1906 return ::SYSTEM_ERROR;
1907 }
Kenny Root70e3a862012-02-15 17:20:23 -08001908
Kenny Root07438c82012-11-02 15:41:02 -07001909 keymaster_rsa_sign_params_t params;
1910 params.digest_type = DIGEST_NONE;
1911 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001912
Kenny Root07438c82012-11-02 15:41:02 -07001913 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1914 data, dataLength, signature, signatureLength);
1915 if (rc) {
1916 return ::SYSTEM_ERROR;
1917 } else {
1918 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001919 }
1920 }
Kenny Root07438c82012-11-02 15:41:02 -07001921
1922 /*
1923 * TODO: The abstraction between things stored in hardware and regular blobs
1924 * of data stored on the filesystem should be moved down to keystore itself.
1925 * Unfortunately the Java code that calls this has naming conventions that it
1926 * knows about. Ideally keystore shouldn't be used to store random blobs of
1927 * data.
1928 *
1929 * Until that happens, it's necessary to have a separate "get_pubkey" and
1930 * "del_key" since the Java code doesn't really communicate what it's
1931 * intentions are.
1932 */
1933 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001934 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1935 if (!has_permission(callingUid, P_GET)) {
1936 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001937 return ::PERMISSION_DENIED;
1938 }
Kenny Root07438c82012-11-02 15:41:02 -07001939
Kenny Root07438c82012-11-02 15:41:02 -07001940 Blob keyBlob;
1941 String8 name8(name);
1942
Kenny Rootd38a0b02013-02-13 12:59:14 -08001943 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001944
Kenny Root655b9582013-04-04 08:37:42 -07001945 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001946 TYPE_KEY_PAIR);
1947 if (responseCode != ::NO_ERROR) {
1948 return responseCode;
1949 }
1950
1951 const keymaster_device_t* device = mKeyStore->getDevice();
1952 if (device == NULL) {
1953 return ::SYSTEM_ERROR;
1954 }
1955
1956 if (device->get_keypair_public == NULL) {
1957 ALOGE("device has no get_keypair_public implementation!");
1958 return ::SYSTEM_ERROR;
1959 }
1960
1961 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1962 pubkeyLength);
1963 if (rc) {
1964 return ::SYSTEM_ERROR;
1965 }
1966
1967 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001968 }
Kenny Root07438c82012-11-02 15:41:02 -07001969
Kenny Root49468902013-03-19 13:41:33 -07001970 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001971 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1972 if (!has_permission(callingUid, P_DELETE)) {
1973 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001974 return ::PERMISSION_DENIED;
1975 }
Kenny Root07438c82012-11-02 15:41:02 -07001976
Kenny Root49468902013-03-19 13:41:33 -07001977 if (targetUid == -1) {
1978 targetUid = callingUid;
1979 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001980 return ::PERMISSION_DENIED;
1981 }
1982
Kenny Root07438c82012-11-02 15:41:02 -07001983 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001984 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001985
1986 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001987 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
1988 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001989 if (responseCode != ::NO_ERROR) {
1990 return responseCode;
1991 }
1992
1993 ResponseCode rc = ::NO_ERROR;
1994
1995 const keymaster_device_t* device = mKeyStore->getDevice();
1996 if (device == NULL) {
1997 rc = ::SYSTEM_ERROR;
1998 } else {
1999 // A device doesn't have to implement delete_keypair.
2000 if (device->delete_keypair != NULL) {
2001 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2002 rc = ::SYSTEM_ERROR;
2003 }
2004 }
2005 }
2006
2007 if (rc != ::NO_ERROR) {
2008 return rc;
2009 }
2010
2011 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2012 }
2013
2014 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002015 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2016 if (!has_permission(callingUid, P_GRANT)) {
2017 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002018 return ::PERMISSION_DENIED;
2019 }
Kenny Root07438c82012-11-02 15:41:02 -07002020
Kenny Root655b9582013-04-04 08:37:42 -07002021 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002022 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002023 ALOGD("calling grant in state: %d", state);
2024 return state;
2025 }
2026
2027 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002028 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002029
Kenny Root655b9582013-04-04 08:37:42 -07002030 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002031 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2032 }
2033
Kenny Root655b9582013-04-04 08:37:42 -07002034 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002035 return ::NO_ERROR;
2036 }
2037
2038 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002039 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2040 if (!has_permission(callingUid, P_GRANT)) {
2041 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002042 return ::PERMISSION_DENIED;
2043 }
Kenny Root07438c82012-11-02 15:41:02 -07002044
Kenny Root655b9582013-04-04 08:37:42 -07002045 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002046 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002047 ALOGD("calling ungrant in state: %d", state);
2048 return state;
2049 }
2050
2051 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002052 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002053
Kenny Root655b9582013-04-04 08:37:42 -07002054 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002055 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2056 }
2057
Kenny Root655b9582013-04-04 08:37:42 -07002058 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002059 }
2060
2061 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002062 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2063 if (!has_permission(callingUid, P_GET)) {
2064 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002065 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002066 }
Kenny Root07438c82012-11-02 15:41:02 -07002067
2068 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002069 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002070
Kenny Root655b9582013-04-04 08:37:42 -07002071 if (access(filename.string(), R_OK) == -1) {
2072 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002073 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002074 }
2075
Kenny Root655b9582013-04-04 08:37:42 -07002076 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002077 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002078 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002079 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002080 }
2081
2082 struct stat s;
2083 int ret = fstat(fd, &s);
2084 close(fd);
2085 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002086 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002087 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002088 }
2089
Kenny Root36a9e232013-02-04 14:24:15 -08002090 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002091 }
2092
Kenny Rootd53bc922013-03-21 14:10:15 -07002093 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2094 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002095 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07002096 if (!has_permission(callingUid, P_DUPLICATE)) {
2097 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002098 return -1L;
2099 }
2100
Kenny Root655b9582013-04-04 08:37:42 -07002101 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002102 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002103 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002104 return state;
2105 }
2106
Kenny Rootd53bc922013-03-21 14:10:15 -07002107 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2108 srcUid = callingUid;
2109 } else if (!is_granted_to(callingUid, srcUid)) {
2110 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002111 return ::PERMISSION_DENIED;
2112 }
2113
Kenny Rootd53bc922013-03-21 14:10:15 -07002114 if (destUid == -1) {
2115 destUid = callingUid;
2116 }
2117
2118 if (srcUid != destUid) {
2119 if (static_cast<uid_t>(srcUid) != callingUid) {
2120 ALOGD("can only duplicate from caller to other or to same uid: "
2121 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2122 return ::PERMISSION_DENIED;
2123 }
2124
2125 if (!is_granted_to(callingUid, destUid)) {
2126 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2127 return ::PERMISSION_DENIED;
2128 }
2129 }
2130
2131 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002132 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002133
Kenny Rootd53bc922013-03-21 14:10:15 -07002134 String8 target8(destKey);
Kenny Root655b9582013-04-04 08:37:42 -07002135 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002136
Kenny Root655b9582013-04-04 08:37:42 -07002137 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2138 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002139 return ::SYSTEM_ERROR;
2140 }
2141
Kenny Rootd53bc922013-03-21 14:10:15 -07002142 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002143 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2144 callingUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002145 if (responseCode != ::NO_ERROR) {
2146 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002147 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002148
Kenny Root655b9582013-04-04 08:37:42 -07002149 return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002150 }
2151
Kenny Root8ddf35a2013-03-29 11:15:50 -07002152 int32_t is_hardware_backed() {
2153 return mKeyStore->isHardwareBacked() ? 1 : 0;
2154 }
2155
Kenny Roota9bb5492013-04-01 16:29:11 -07002156 int32_t clear_uid(int64_t targetUid) {
2157 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2158 if (!has_permission(callingUid, P_CLEAR_UID)) {
2159 ALOGW("permission denied for %d: clear_uid", callingUid);
2160 return ::PERMISSION_DENIED;
2161 }
2162
Kenny Root655b9582013-04-04 08:37:42 -07002163 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002164 if (!isKeystoreUnlocked(state)) {
2165 ALOGD("calling clear_uid in state: %d", state);
2166 return state;
2167 }
2168
2169 const keymaster_device_t* device = mKeyStore->getDevice();
2170 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002171 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002172 return ::SYSTEM_ERROR;
2173 }
2174
Kenny Root655b9582013-04-04 08:37:42 -07002175 UserState* userState = mKeyStore->getUserState(callingUid);
2176 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002177 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002178 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002179 return ::SYSTEM_ERROR;
2180 }
2181
Kenny Root655b9582013-04-04 08:37:42 -07002182 char prefix[NAME_MAX];
2183 int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002184
2185 ResponseCode rc = ::NO_ERROR;
2186
2187 struct dirent* file;
2188 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002189 // We only care about files.
2190 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002191 continue;
2192 }
2193
Kenny Root655b9582013-04-04 08:37:42 -07002194 // Skip anything that starts with a "."
2195 if (file->d_name[0] == '.') {
2196 continue;
2197 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002198
Kenny Root655b9582013-04-04 08:37:42 -07002199 if (strncmp(prefix, file->d_name, n)) {
2200 continue;
2201 }
2202
2203 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002204 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002205 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2206 != ::NO_ERROR) {
2207 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002208 continue;
2209 }
2210
2211 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2212 // A device doesn't have to implement delete_keypair.
2213 if (device->delete_keypair != NULL) {
2214 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2215 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002216 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002217 }
2218 }
2219 }
2220
Kenny Root5f531242013-04-12 11:31:50 -07002221 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002222 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002223 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002224 }
2225 }
2226 closedir(dir);
2227
2228 return rc;
2229 }
2230
Kenny Root07438c82012-11-02 15:41:02 -07002231private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002232 inline bool isKeystoreUnlocked(State state) {
2233 switch (state) {
2234 case ::STATE_NO_ERROR:
2235 return true;
2236 case ::STATE_UNINITIALIZED:
2237 case ::STATE_LOCKED:
2238 return false;
2239 }
2240 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002241 }
2242
2243 ::KeyStore* mKeyStore;
2244};
2245
2246}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002247
2248int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002249 if (argc < 2) {
2250 ALOGE("A directory must be specified!");
2251 return 1;
2252 }
2253 if (chdir(argv[1]) == -1) {
2254 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2255 return 1;
2256 }
2257
2258 Entropy entropy;
2259 if (!entropy.open()) {
2260 return 1;
2261 }
Kenny Root70e3a862012-02-15 17:20:23 -08002262
2263 keymaster_device_t* dev;
2264 if (keymaster_device_initialize(&dev)) {
2265 ALOGE("keystore keymaster could not be initialized; exiting");
2266 return 1;
2267 }
2268
Kenny Root70e3a862012-02-15 17:20:23 -08002269 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002270 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002271 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2272 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2273 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2274 if (ret != android::OK) {
2275 ALOGE("Couldn't register binder service!");
2276 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002277 }
Kenny Root07438c82012-11-02 15:41:02 -07002278
2279 /*
2280 * We're the only thread in existence, so we're just going to process
2281 * Binder transaction as a single-threaded program.
2282 */
2283 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002284
2285 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002286 return 1;
2287}