blob: a413948624657f4a5c6bca7c4fb3a2a7b468f551 [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>
27#include <fcntl.h>
28#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070029#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080030#include <sys/types.h>
31#include <sys/socket.h>
32#include <sys/stat.h>
33#include <sys/time.h>
34#include <arpa/inet.h>
35
36#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070037#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080038#include <openssl/evp.h>
39#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070040#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080041
Kenny Root70e3a862012-02-15 17:20:23 -080042#include <hardware/keymaster.h>
43
Kenny Root822c3a92012-03-23 16:34:39 -070044#include <utils/UniquePtr.h>
45
Kenny Root70e3a862012-02-15 17:20:23 -080046#include <cutils/list.h>
47
Kenny Root07438c82012-11-02 15:41:02 -070048#include <keystore/IKeystoreService.h>
49#include <binder/IPCThreadState.h>
50#include <binder/IServiceManager.h>
51
Kenny Roota91203b2012-02-15 15:00:46 -080052#include <cutils/log.h>
53#include <cutils/sockets.h>
54#include <private/android_filesystem_config.h>
55
Kenny Root07438c82012-11-02 15:41:02 -070056#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080057
58/* KeyStore is a secured storage for key-value pairs. In this implementation,
59 * each file stores one key-value pair. Keys are encoded in file names, and
60 * values are encrypted with checksums. The encryption key is protected by a
61 * user-defined password. To keep things simple, buffers are always larger than
62 * the maximum space we needed, so boundary checks on buffers are omitted. */
63
64#define KEY_SIZE ((NAME_MAX - 15) / 2)
65#define VALUE_SIZE 32768
66#define PASSWORD_SIZE VALUE_SIZE
67
Kenny Root822c3a92012-03-23 16:34:39 -070068
69struct BIO_Delete {
70 void operator()(BIO* p) const {
71 BIO_free(p);
72 }
73};
74typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
75
76struct EVP_PKEY_Delete {
77 void operator()(EVP_PKEY* p) const {
78 EVP_PKEY_free(p);
79 }
80};
81typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
82
83struct PKCS8_PRIV_KEY_INFO_Delete {
84 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
85 PKCS8_PRIV_KEY_INFO_free(p);
86 }
87};
88typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
89
90
Kenny Root70e3a862012-02-15 17:20:23 -080091static int keymaster_device_initialize(keymaster_device_t** dev) {
92 int rc;
93
94 const hw_module_t* mod;
95 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
96 if (rc) {
97 ALOGE("could not find any keystore module");
98 goto out;
99 }
100
101 rc = keymaster_open(mod, dev);
102 if (rc) {
103 ALOGE("could not open keymaster device in %s (%s)",
104 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
105 goto out;
106 }
107
108 return 0;
109
110out:
111 *dev = NULL;
112 return rc;
113}
114
115static void keymaster_device_release(keymaster_device_t* dev) {
116 keymaster_close(dev);
117}
118
Kenny Root07438c82012-11-02 15:41:02 -0700119/***************
120 * PERMISSIONS *
121 ***************/
122
123/* Here are the permissions, actions, users, and the main function. */
124typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700125 P_TEST = 1 << 0,
126 P_GET = 1 << 1,
127 P_INSERT = 1 << 2,
128 P_DELETE = 1 << 3,
129 P_EXIST = 1 << 4,
130 P_SAW = 1 << 5,
131 P_RESET = 1 << 6,
132 P_PASSWORD = 1 << 7,
133 P_LOCK = 1 << 8,
134 P_UNLOCK = 1 << 9,
135 P_ZERO = 1 << 10,
136 P_SIGN = 1 << 11,
137 P_VERIFY = 1 << 12,
138 P_GRANT = 1 << 13,
139 P_DUPLICATE = 1 << 14,
Kenny Roota9bb5492013-04-01 16:29:11 -0700140 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700141} perm_t;
142
143static struct user_euid {
144 uid_t uid;
145 uid_t euid;
146} user_euids[] = {
147 {AID_VPN, AID_SYSTEM},
148 {AID_WIFI, AID_SYSTEM},
149 {AID_ROOT, AID_SYSTEM},
150};
151
152static struct user_perm {
153 uid_t uid;
154 perm_t perms;
155} user_perms[] = {
156 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
157 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
158 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
159 {AID_ROOT, static_cast<perm_t>(P_GET) },
160};
161
162static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
163 | P_VERIFY);
164
165static bool has_permission(uid_t uid, perm_t perm) {
166 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
167 struct user_perm user = user_perms[i];
168 if (user.uid == uid) {
169 return user.perms & perm;
170 }
171 }
172
173 return DEFAULT_PERMS & perm;
174}
175
Kenny Root49468902013-03-19 13:41:33 -0700176/**
177 * Returns the UID that the callingUid should act as. This is here for
178 * legacy support of the WiFi and VPN systems and should be removed
179 * when WiFi can operate in its own namespace.
180 */
Kenny Root07438c82012-11-02 15:41:02 -0700181static uid_t get_keystore_euid(uid_t uid) {
182 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
183 struct user_euid user = user_euids[i];
184 if (user.uid == uid) {
185 return user.euid;
186 }
187 }
188
189 return uid;
190}
191
Kenny Root49468902013-03-19 13:41:33 -0700192/**
193 * Returns true if the callingUid is allowed to interact in the targetUid's
194 * namespace.
195 */
196static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
197 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
198 struct user_euid user = user_euids[i];
199 if (user.euid == callingUid && user.uid == targetUid) {
200 return true;
201 }
202 }
203
204 return false;
205}
206
Kenny Roota91203b2012-02-15 15:00:46 -0800207/* Here is the encoding of keys. This is necessary in order to allow arbitrary
208 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
209 * into two bytes. The first byte is one of [+-.] which represents the first
210 * two bits of the character. The second byte encodes the rest of the bits into
211 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
212 * that Base64 cannot be used here due to the need of prefix match on keys. */
213
Kenny Root07438c82012-11-02 15:41:02 -0700214static int encode_key(char* out, const android::String8& keyName) {
215 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
216 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800217 for (int i = length; i > 0; --i, ++in, ++out) {
218 if (*in >= '0' && *in <= '~') {
219 *out = *in;
220 } else {
221 *out = '+' + (*in >> 6);
222 *++out = '0' + (*in & 0x3F);
223 ++length;
224 }
225 }
226 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800227 return length;
228}
229
Kenny Root07438c82012-11-02 15:41:02 -0700230static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800231 int n = snprintf(out, NAME_MAX, "%u_", uid);
232 out += n;
233
Kenny Root07438c82012-11-02 15:41:02 -0700234 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800235}
236
Kenny Root07438c82012-11-02 15:41:02 -0700237/*
238 * Converts from the "escaped" format on disk to actual name.
239 * This will be smaller than the input string.
240 *
241 * Characters that should combine with the next at the end will be truncated.
242 */
243static size_t decode_key_length(const char* in, size_t length) {
244 size_t outLength = 0;
245
246 for (const char* end = in + length; in < end; in++) {
247 /* This combines with the next character. */
248 if (*in < '0' || *in > '~') {
249 continue;
250 }
251
252 outLength++;
253 }
254 return outLength;
255}
256
257static void decode_key(char* out, const char* in, size_t length) {
258 for (const char* end = in + length; in < end; in++) {
259 if (*in < '0' || *in > '~') {
260 /* Truncate combining characters at the end. */
261 if (in + 1 >= end) {
262 break;
263 }
264
265 *out = (*in++ - '+') << 6;
266 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800267 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700268 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800269 }
270 }
271 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800272}
273
274static size_t readFully(int fd, uint8_t* data, size_t size) {
275 size_t remaining = size;
276 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800277 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800278 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800279 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800280 }
281 data += n;
282 remaining -= n;
283 }
284 return size;
285}
286
287static size_t writeFully(int fd, uint8_t* data, size_t size) {
288 size_t remaining = size;
289 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800290 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
291 if (n < 0) {
292 ALOGW("write failed: %s", strerror(errno));
293 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800294 }
295 data += n;
296 remaining -= n;
297 }
298 return size;
299}
300
301class Entropy {
302public:
303 Entropy() : mRandom(-1) {}
304 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800305 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800306 close(mRandom);
307 }
308 }
309
310 bool open() {
311 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800312 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
313 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800314 ALOGE("open: %s: %s", randomDevice, strerror(errno));
315 return false;
316 }
317 return true;
318 }
319
Kenny Root51878182012-03-13 12:53:19 -0700320 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800321 return (readFully(mRandom, data, size) == size);
322 }
323
324private:
325 int mRandom;
326};
327
328/* Here is the file format. There are two parts in blob.value, the secret and
329 * the description. The secret is stored in ciphertext, and its original size
330 * can be found in blob.length. The description is stored after the secret in
331 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700332 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
333 * the second is the blob's type, and the third byte is reserved. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800334 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
335 * and decryptBlob(). Thus they should not be accessed from outside. */
336
Kenny Root822c3a92012-03-23 16:34:39 -0700337/* ** Note to future implementors of encryption: **
338 * Currently this is the construction:
339 * metadata || Enc(MD5(data) || data)
340 *
341 * This should be the construction used for encrypting if re-implementing:
342 *
343 * Derive independent keys for encryption and MAC:
344 * Kenc = AES_encrypt(masterKey, "Encrypt")
345 * Kmac = AES_encrypt(masterKey, "MAC")
346 *
347 * Store this:
348 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
349 * HMAC(Kmac, metadata || Enc(data))
350 */
Kenny Roota91203b2012-02-15 15:00:46 -0800351struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700352 uint8_t version;
353 uint8_t type;
354 uint8_t reserved;
Kenny Roota91203b2012-02-15 15:00:46 -0800355 uint8_t info;
356 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700357 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800358 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700359 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800360 int32_t length; // in network byte order when encrypted
361 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
362};
363
Kenny Root822c3a92012-03-23 16:34:39 -0700364typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700365 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700366 TYPE_GENERIC = 1,
367 TYPE_MASTER_KEY = 2,
368 TYPE_KEY_PAIR = 3,
369} BlobType;
370
Kenny Root07438c82012-11-02 15:41:02 -0700371static const uint8_t CURRENT_BLOB_VERSION = 1;
Kenny Root822c3a92012-03-23 16:34:39 -0700372
Kenny Roota91203b2012-02-15 15:00:46 -0800373class Blob {
374public:
Kenny Root07438c82012-11-02 15:41:02 -0700375 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
376 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800377 mBlob.length = valueLength;
378 memcpy(mBlob.value, value, valueLength);
379
380 mBlob.info = infoLength;
381 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700382
Kenny Root07438c82012-11-02 15:41:02 -0700383 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700384 mBlob.type = uint8_t(type);
Kenny Roota91203b2012-02-15 15:00:46 -0800385 }
386
387 Blob(blob b) {
388 mBlob = b;
389 }
390
391 Blob() {}
392
Kenny Root51878182012-03-13 12:53:19 -0700393 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800394 return mBlob.value;
395 }
396
Kenny Root51878182012-03-13 12:53:19 -0700397 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800398 return mBlob.length;
399 }
400
Kenny Root51878182012-03-13 12:53:19 -0700401 const uint8_t* getInfo() const {
402 return mBlob.value + mBlob.length;
403 }
404
405 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800406 return mBlob.info;
407 }
408
Kenny Root822c3a92012-03-23 16:34:39 -0700409 uint8_t getVersion() const {
410 return mBlob.version;
411 }
412
413 void setVersion(uint8_t version) {
414 mBlob.version = version;
415 }
416
417 BlobType getType() const {
418 return BlobType(mBlob.type);
419 }
420
421 void setType(BlobType type) {
422 mBlob.type = uint8_t(type);
423 }
424
Kenny Roota91203b2012-02-15 15:00:46 -0800425 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
426 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
Kenny Root150ca932012-11-14 14:29:02 -0800427 ALOGW("Could not read random data for: %s", filename);
Kenny Roota91203b2012-02-15 15:00:46 -0800428 return SYSTEM_ERROR;
429 }
430
431 // data includes the value and the value's length
432 size_t dataLength = mBlob.length + sizeof(mBlob.length);
433 // pad data to the AES_BLOCK_SIZE
434 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
435 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
436 // encrypted data includes the digest value
437 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
438 // move info after space for padding
439 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
440 // zero padding area
441 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
442
443 mBlob.length = htonl(mBlob.length);
444 MD5(mBlob.digested, digestedLength, mBlob.digest);
445
446 uint8_t vector[AES_BLOCK_SIZE];
447 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
448 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
449 aes_key, vector, AES_ENCRYPT);
450
Kenny Root822c3a92012-03-23 16:34:39 -0700451 mBlob.reserved = 0;
Kenny Roota91203b2012-02-15 15:00:46 -0800452 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
453 size_t fileLength = encryptedLength + headerLength + mBlob.info;
454
455 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800456 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
457 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
458 if (out < 0) {
459 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800460 return SYSTEM_ERROR;
461 }
462 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
463 if (close(out) != 0) {
464 return SYSTEM_ERROR;
465 }
466 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800467 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800468 unlink(tmpFileName);
469 return SYSTEM_ERROR;
470 }
Kenny Root150ca932012-11-14 14:29:02 -0800471 if (rename(tmpFileName, filename) == -1) {
472 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
473 return SYSTEM_ERROR;
474 }
475 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800476 }
477
478 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
Kenny Root150ca932012-11-14 14:29:02 -0800479 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
480 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800481 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
482 }
483 // fileLength may be less than sizeof(mBlob) since the in
484 // memory version has extra padding to tolerate rounding up to
485 // the AES_BLOCK_SIZE
486 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
487 if (close(in) != 0) {
488 return SYSTEM_ERROR;
489 }
490 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
491 if (fileLength < headerLength) {
492 return VALUE_CORRUPTED;
493 }
494
495 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
496 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
497 return VALUE_CORRUPTED;
498 }
499 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
500 mBlob.vector, AES_DECRYPT);
501 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
502 uint8_t computedDigest[MD5_DIGEST_LENGTH];
503 MD5(mBlob.digested, digestedLength, computedDigest);
504 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
505 return VALUE_CORRUPTED;
506 }
507
508 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
509 mBlob.length = ntohl(mBlob.length);
510 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
511 return VALUE_CORRUPTED;
512 }
513 if (mBlob.info != 0) {
514 // move info from after padding to after data
515 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
516 }
Kenny Root07438c82012-11-02 15:41:02 -0700517 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800518 }
519
520private:
521 struct blob mBlob;
522};
523
Kenny Root70e3a862012-02-15 17:20:23 -0800524typedef struct {
525 uint32_t uid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700526 const uint8_t* filename;
Kenny Root70e3a862012-02-15 17:20:23 -0800527
528 struct listnode plist;
529} grant_t;
530
Kenny Roota91203b2012-02-15 15:00:46 -0800531class KeyStore {
532public:
Kenny Root70e3a862012-02-15 17:20:23 -0800533 KeyStore(Entropy* entropy, keymaster_device_t* device)
Kenny Root51878182012-03-13 12:53:19 -0700534 : mEntropy(entropy)
Kenny Root70e3a862012-02-15 17:20:23 -0800535 , mDevice(device)
Kenny Root51878182012-03-13 12:53:19 -0700536 , mRetry(MAX_RETRY)
537 {
Kenny Roota91203b2012-02-15 15:00:46 -0800538 if (access(MASTER_KEY_FILE, R_OK) == 0) {
539 setState(STATE_LOCKED);
540 } else {
541 setState(STATE_UNINITIALIZED);
542 }
Kenny Root70e3a862012-02-15 17:20:23 -0800543
544 list_init(&mGrants);
Kenny Roota91203b2012-02-15 15:00:46 -0800545 }
546
Kenny Root51878182012-03-13 12:53:19 -0700547 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800548 return mState;
549 }
550
Kenny Root51878182012-03-13 12:53:19 -0700551 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800552 return mRetry;
553 }
554
Kenny Root70e3a862012-02-15 17:20:23 -0800555 keymaster_device_t* getDevice() const {
556 return mDevice;
557 }
558
Kenny Root07438c82012-11-02 15:41:02 -0700559 ResponseCode initialize(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800560 if (!generateMasterKey()) {
561 return SYSTEM_ERROR;
562 }
563 ResponseCode response = writeMasterKey(pw);
564 if (response != NO_ERROR) {
565 return response;
566 }
567 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700568 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800569 }
570
Kenny Root07438c82012-11-02 15:41:02 -0700571 ResponseCode writeMasterKey(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800572 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
573 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
574 AES_KEY passwordAesKey;
575 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700576 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Roota91203b2012-02-15 15:00:46 -0800577 return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
578 }
579
Kenny Root07438c82012-11-02 15:41:02 -0700580 ResponseCode readMasterKey(const android::String8& pw) {
Kenny Root150ca932012-11-14 14:29:02 -0800581 int in = TEMP_FAILURE_RETRY(open(MASTER_KEY_FILE, O_RDONLY));
582 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800583 return SYSTEM_ERROR;
584 }
585
586 // we read the raw blob to just to get the salt to generate
587 // the AES key, then we create the Blob to use with decryptBlob
588 blob rawBlob;
589 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
590 if (close(in) != 0) {
591 return SYSTEM_ERROR;
592 }
593 // find salt at EOF if present, otherwise we have an old file
594 uint8_t* salt;
595 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
596 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
597 } else {
598 salt = NULL;
599 }
600 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
601 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
602 AES_KEY passwordAesKey;
603 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
604 Blob masterKeyBlob(rawBlob);
605 ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
606 if (response == SYSTEM_ERROR) {
607 return SYSTEM_ERROR;
608 }
609 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
610 // if salt was missing, generate one and write a new master key file with the salt.
611 if (salt == NULL) {
612 if (!generateSalt()) {
613 return SYSTEM_ERROR;
614 }
615 response = writeMasterKey(pw);
616 }
617 if (response == NO_ERROR) {
618 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
619 setupMasterKeys();
620 }
621 return response;
622 }
623 if (mRetry <= 0) {
624 reset();
625 return UNINITIALIZED;
626 }
627 --mRetry;
628 switch (mRetry) {
629 case 0: return WRONG_PASSWORD_0;
630 case 1: return WRONG_PASSWORD_1;
631 case 2: return WRONG_PASSWORD_2;
632 case 3: return WRONG_PASSWORD_3;
633 default: return WRONG_PASSWORD_3;
634 }
635 }
636
637 bool reset() {
638 clearMasterKeys();
639 setState(STATE_UNINITIALIZED);
640
641 DIR* dir = opendir(".");
642 struct dirent* file;
643
644 if (!dir) {
645 return false;
646 }
647 while ((file = readdir(dir)) != NULL) {
648 unlink(file->d_name);
649 }
650 closedir(dir);
651 return true;
652 }
653
Kenny Root51878182012-03-13 12:53:19 -0700654 bool isEmpty() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800655 DIR* dir = opendir(".");
656 struct dirent* file;
657 if (!dir) {
658 return true;
659 }
660 bool result = true;
661 while ((file = readdir(dir)) != NULL) {
662 if (isKeyFile(file->d_name)) {
663 result = false;
664 break;
665 }
666 }
667 closedir(dir);
668 return result;
669 }
670
671 void lock() {
672 clearMasterKeys();
673 setState(STATE_LOCKED);
674 }
675
Kenny Root822c3a92012-03-23 16:34:39 -0700676 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
677 ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
678 if (rc != NO_ERROR) {
679 return rc;
680 }
681
682 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700683 if (version < CURRENT_BLOB_VERSION) {
Kenny Root822c3a92012-03-23 16:34:39 -0700684 upgrade(filename, keyBlob, version, type);
685 }
686
Kenny Rootd53bc922013-03-21 14:10:15 -0700687 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -0700688 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
689 return KEY_NOT_FOUND;
690 }
691
692 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -0800693 }
694
695 ResponseCode put(const char* filename, Blob* keyBlob) {
696 return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
697 }
698
Kenny Root07438c82012-11-02 15:41:02 -0700699 void addGrant(const char* filename, uid_t granteeUid) {
700 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800701 if (grant == NULL) {
702 grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -0700703 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700704 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root70e3a862012-02-15 17:20:23 -0800705 list_add_tail(&mGrants, &grant->plist);
706 }
707 }
708
Kenny Root07438c82012-11-02 15:41:02 -0700709 bool removeGrant(const char* filename, uid_t granteeUid) {
710 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800711 if (grant != NULL) {
712 list_remove(&grant->plist);
713 delete grant;
714 return true;
715 }
716
717 return false;
718 }
719
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700720 bool hasGrant(const char* filename, const uid_t uid) const {
721 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800722 }
723
Kenny Root07438c82012-11-02 15:41:02 -0700724 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
Kenny Root822c3a92012-03-23 16:34:39 -0700725 uint8_t* data;
726 size_t dataLength;
727 int rc;
728
729 if (mDevice->import_keypair == NULL) {
730 ALOGE("Keymaster doesn't support import!");
731 return SYSTEM_ERROR;
732 }
733
Kenny Root07438c82012-11-02 15:41:02 -0700734 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700735 if (rc) {
736 ALOGE("Error while importing keypair: %d", rc);
737 return SYSTEM_ERROR;
738 }
739
740 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
741 free(data);
742
743 return put(filename, &keyBlob);
744 }
745
Kenny Root8ddf35a2013-03-29 11:15:50 -0700746 bool isHardwareBacked() const {
747 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) != 0;
748 }
749
Kenny Roota91203b2012-02-15 15:00:46 -0800750private:
751 static const char* MASTER_KEY_FILE;
752 static const int MASTER_KEY_SIZE_BYTES = 16;
753 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
754
755 static const int MAX_RETRY = 4;
756 static const size_t SALT_SIZE = 16;
757
758 Entropy* mEntropy;
759
Kenny Root70e3a862012-02-15 17:20:23 -0800760 keymaster_device_t* mDevice;
761
Kenny Roota91203b2012-02-15 15:00:46 -0800762 State mState;
763 int8_t mRetry;
764
765 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
766 uint8_t mSalt[SALT_SIZE];
767
768 AES_KEY mMasterKeyEncryption;
769 AES_KEY mMasterKeyDecryption;
770
Kenny Root70e3a862012-02-15 17:20:23 -0800771 struct listnode mGrants;
772
Kenny Roota91203b2012-02-15 15:00:46 -0800773 void setState(State state) {
774 mState = state;
775 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
776 mRetry = MAX_RETRY;
777 }
778 }
779
780 bool generateSalt() {
781 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
782 }
783
784 bool generateMasterKey() {
785 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
786 return false;
787 }
788 if (!generateSalt()) {
789 return false;
790 }
791 return true;
792 }
793
794 void setupMasterKeys() {
795 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
796 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
797 setState(STATE_NO_ERROR);
798 }
799
800 void clearMasterKeys() {
801 memset(mMasterKey, 0, sizeof(mMasterKey));
802 memset(mSalt, 0, sizeof(mSalt));
803 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
804 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
805 }
806
Kenny Root07438c82012-11-02 15:41:02 -0700807 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
808 uint8_t* salt) {
Kenny Roota91203b2012-02-15 15:00:46 -0800809 size_t saltSize;
810 if (salt != NULL) {
811 saltSize = SALT_SIZE;
812 } else {
813 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
814 salt = (uint8_t*) "keystore";
815 // sizeof = 9, not strlen = 8
816 saltSize = sizeof("keystore");
817 }
Kenny Root07438c82012-11-02 15:41:02 -0700818
819 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
820 saltSize, 8192, keySize, key);
Kenny Roota91203b2012-02-15 15:00:46 -0800821 }
822
823 static bool isKeyFile(const char* filename) {
824 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
825 && (strcmp(filename, ".") != 0)
826 && (strcmp(filename, "..") != 0));
827 }
Kenny Root70e3a862012-02-15 17:20:23 -0800828
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700829 grant_t* getGrant(const char* filename, uid_t uid) const {
Kenny Root70e3a862012-02-15 17:20:23 -0800830 struct listnode *node;
831 grant_t *grant;
832
833 list_for_each(node, &mGrants) {
834 grant = node_to_item(node, grant_t, plist);
835 if (grant->uid == uid
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700836 && !strcmp(reinterpret_cast<const char*>(grant->filename),
837 filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800838 return grant;
839 }
840 }
841
842 return NULL;
843 }
844
Kenny Root822c3a92012-03-23 16:34:39 -0700845 /**
846 * Upgrade code. This will upgrade the key from the current version
847 * to whatever is newest.
848 */
849 void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
850 bool updated = false;
851 uint8_t version = oldVersion;
852
853 /* From V0 -> V1: All old types were unknown */
854 if (version == 0) {
855 ALOGV("upgrading to version 1 and setting type %d", type);
856
857 blob->setType(type);
858 if (type == TYPE_KEY_PAIR) {
859 importBlobAsKey(blob, filename);
860 }
861 version = 1;
862 updated = true;
863 }
864
865 /*
866 * If we've updated, set the key blob to the right version
867 * and write it.
868 * */
869 if (updated) {
870 ALOGV("updated and writing file %s", filename);
871 blob->setVersion(version);
872 this->put(filename, blob);
873 }
874 }
875
876 /**
877 * Takes a blob that is an PEM-encoded RSA key as a byte array and
878 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
879 * Then it overwrites the original blob with the new blob
880 * format that is returned from the keymaster.
881 */
882 ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
883 // We won't even write to the blob directly with this BIO, so const_cast is okay.
884 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
885 if (b.get() == NULL) {
886 ALOGE("Problem instantiating BIO");
887 return SYSTEM_ERROR;
888 }
889
890 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
891 if (pkey.get() == NULL) {
892 ALOGE("Couldn't read old PEM file");
893 return SYSTEM_ERROR;
894 }
895
896 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
897 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
898 if (len < 0) {
899 ALOGE("Couldn't measure PKCS#8 length");
900 return SYSTEM_ERROR;
901 }
902
Kenny Root70c98892013-02-07 09:10:36 -0800903 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
904 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -0700905 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
906 ALOGE("Couldn't convert to PKCS#8");
907 return SYSTEM_ERROR;
908 }
909
Kenny Root70c98892013-02-07 09:10:36 -0800910 ResponseCode rc = importKey(pkcs8key.get(), len, filename);
Kenny Root822c3a92012-03-23 16:34:39 -0700911 if (rc != NO_ERROR) {
912 return rc;
913 }
914
915 return get(filename, blob, TYPE_KEY_PAIR);
916 }
Kenny Roota91203b2012-02-15 15:00:46 -0800917};
918
919const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
920
Kenny Root07438c82012-11-02 15:41:02 -0700921static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
922 const android::String8& keyName, const uid_t uid, const BlobType type) {
Kenny Root70e3a862012-02-15 17:20:23 -0800923 char filename[NAME_MAX];
924
925 encode_key_for_uid(filename, uid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700926 ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800927 if (responseCode == NO_ERROR) {
928 return responseCode;
929 }
930
Kenny Root49468902013-03-19 13:41:33 -0700931 // If this is one of the legacy UID->UID mappings, use it.
932 uid_t euid = get_keystore_euid(uid);
933 if (euid != uid) {
934 encode_key_for_uid(filename, euid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700935 responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800936 if (responseCode == NO_ERROR) {
937 return responseCode;
938 }
939 }
940
941 // They might be using a granted key.
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700942 encode_key(filename, keyName);
943 if (!keyStore->hasGrant(filename, uid)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800944 return responseCode;
945 }
946
947 // It is a granted key. Try to load it.
Kenny Root822c3a92012-03-23 16:34:39 -0700948 return keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800949}
950
Kenny Root07438c82012-11-02 15:41:02 -0700951namespace android {
952class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
953public:
954 KeyStoreProxy(KeyStore* keyStore)
955 : mKeyStore(keyStore)
956 {
Kenny Roota91203b2012-02-15 15:00:46 -0800957 }
Kenny Roota91203b2012-02-15 15:00:46 -0800958
Kenny Root07438c82012-11-02 15:41:02 -0700959 void binderDied(const wp<IBinder>&) {
960 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -0700961 }
Kenny Roota91203b2012-02-15 15:00:46 -0800962
Kenny Root07438c82012-11-02 15:41:02 -0700963 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800964 uid_t callingUid = IPCThreadState::self()->getCallingUid();
965 if (!has_permission(callingUid, P_TEST)) {
966 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700967 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800968 }
Kenny Roota91203b2012-02-15 15:00:46 -0800969
Kenny Root07438c82012-11-02 15:41:02 -0700970 return mKeyStore->getState();
Kenny Root298e7b12012-03-26 13:54:44 -0700971 }
972
Kenny Root07438c82012-11-02 15:41:02 -0700973 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800974 uid_t callingUid = IPCThreadState::self()->getCallingUid();
975 if (!has_permission(callingUid, P_GET)) {
976 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700977 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800978 }
Kenny Root07438c82012-11-02 15:41:02 -0700979
Kenny Root9d45d1c2013-02-14 10:32:30 -0800980 State state = mKeyStore->getState();
981 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -0700982 ALOGD("calling get in state: %d", state);
983 return state;
Kenny Roota91203b2012-02-15 15:00:46 -0800984 }
Kenny Root07438c82012-11-02 15:41:02 -0700985
986 String8 name8(name);
987 char filename[NAME_MAX];
Kenny Root07438c82012-11-02 15:41:02 -0700988 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -0700989
990 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
991 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -0700992 if (responseCode != ::NO_ERROR) {
Kenny Root150ca932012-11-14 14:29:02 -0800993 ALOGW("Could not read %s", filename);
Kenny Root07438c82012-11-02 15:41:02 -0700994 *item = NULL;
995 *itemLength = 0;
996 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -0800997 }
Kenny Roota91203b2012-02-15 15:00:46 -0800998
Kenny Root07438c82012-11-02 15:41:02 -0700999 *item = (uint8_t*) malloc(keyBlob.getLength());
1000 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1001 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001002
Kenny Root07438c82012-11-02 15:41:02 -07001003 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001004 }
1005
Kenny Root49468902013-03-19 13:41:33 -07001006 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001007 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1008 if (!has_permission(callingUid, P_INSERT)) {
1009 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001010 return ::PERMISSION_DENIED;
1011 }
Kenny Root07438c82012-11-02 15:41:02 -07001012
Kenny Root49468902013-03-19 13:41:33 -07001013 if (targetUid == -1) {
1014 targetUid = callingUid;
1015 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001016 return ::PERMISSION_DENIED;
1017 }
1018
Kenny Root9d45d1c2013-02-14 10:32:30 -08001019 State state = mKeyStore->getState();
1020 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001021 ALOGD("calling insert in state: %d", state);
1022 return state;
1023 }
1024
1025 String8 name8(name);
1026 char filename[NAME_MAX];
1027
Kenny Root49468902013-03-19 13:41:33 -07001028 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001029
1030 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1031 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001032 }
1033
Kenny Root49468902013-03-19 13:41:33 -07001034 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001035 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1036 if (!has_permission(callingUid, P_DELETE)) {
1037 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001038 return ::PERMISSION_DENIED;
1039 }
Kenny Root70e3a862012-02-15 17:20:23 -08001040
Kenny Root49468902013-03-19 13:41:33 -07001041 if (targetUid == -1) {
1042 targetUid = callingUid;
1043 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001044 return ::PERMISSION_DENIED;
1045 }
1046
Kenny Root07438c82012-11-02 15:41:02 -07001047 String8 name8(name);
1048 char filename[NAME_MAX];
1049
Kenny Root49468902013-03-19 13:41:33 -07001050 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001051
1052 Blob keyBlob;
1053 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1054 if (responseCode != ::NO_ERROR) {
1055 return responseCode;
1056 }
1057 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001058 }
1059
Kenny Root49468902013-03-19 13:41:33 -07001060 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001061 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1062 if (!has_permission(callingUid, P_EXIST)) {
1063 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001064 return ::PERMISSION_DENIED;
1065 }
Kenny Root70e3a862012-02-15 17:20:23 -08001066
Kenny Root49468902013-03-19 13:41:33 -07001067 if (targetUid == -1) {
1068 targetUid = callingUid;
1069 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001070 return ::PERMISSION_DENIED;
1071 }
1072
Kenny Root07438c82012-11-02 15:41:02 -07001073 String8 name8(name);
1074 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001075
Kenny Root49468902013-03-19 13:41:33 -07001076 encode_key_for_uid(filename, targetUid, name8);
Kenny Root70e3a862012-02-15 17:20:23 -08001077
Kenny Root07438c82012-11-02 15:41:02 -07001078 if (access(filename, R_OK) == -1) {
1079 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1080 }
1081 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001082 }
1083
Kenny Root49468902013-03-19 13:41:33 -07001084 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001085 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1086 if (!has_permission(callingUid, P_SAW)) {
1087 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001088 return ::PERMISSION_DENIED;
1089 }
Kenny Root70e3a862012-02-15 17:20:23 -08001090
Kenny Root49468902013-03-19 13:41:33 -07001091 if (targetUid == -1) {
1092 targetUid = callingUid;
1093 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001094 return ::PERMISSION_DENIED;
1095 }
1096
Kenny Root07438c82012-11-02 15:41:02 -07001097 DIR* dir = opendir(".");
1098 if (!dir) {
1099 return ::SYSTEM_ERROR;
1100 }
Kenny Root70e3a862012-02-15 17:20:23 -08001101
Kenny Root07438c82012-11-02 15:41:02 -07001102 const String8 prefix8(prefix);
1103 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001104
Kenny Root49468902013-03-19 13:41:33 -07001105 int n = encode_key_for_uid(filename, targetUid, prefix8);
Kenny Root70e3a862012-02-15 17:20:23 -08001106
Kenny Root07438c82012-11-02 15:41:02 -07001107 struct dirent* file;
1108 while ((file = readdir(dir)) != NULL) {
1109 if (!strncmp(filename, file->d_name, n)) {
1110 const char* p = &file->d_name[n];
1111 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001112
Kenny Root07438c82012-11-02 15:41:02 -07001113 size_t extra = decode_key_length(p, plen);
1114 char *match = (char*) malloc(extra + 1);
1115 if (match != NULL) {
1116 decode_key(match, p, plen);
1117 matches->push(String16(match, extra));
1118 free(match);
1119 } else {
1120 ALOGW("could not allocate match of size %zd", extra);
1121 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001122 }
1123 }
Kenny Root07438c82012-11-02 15:41:02 -07001124 closedir(dir);
1125
1126 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001127 }
1128
Kenny Root07438c82012-11-02 15:41:02 -07001129 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001130 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1131 if (!has_permission(callingUid, P_RESET)) {
1132 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001133 return ::PERMISSION_DENIED;
1134 }
1135
1136 ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1137
1138 const keymaster_device_t* device = mKeyStore->getDevice();
1139 if (device == NULL) {
1140 ALOGE("No keymaster device!");
1141 return ::SYSTEM_ERROR;
1142 }
1143
1144 if (device->delete_all == NULL) {
1145 ALOGV("keymaster device doesn't implement delete_all");
1146 return rc;
1147 }
1148
1149 if (device->delete_all(device)) {
1150 ALOGE("Problem calling keymaster's delete_all");
1151 return ::SYSTEM_ERROR;
1152 }
1153
Kenny Root9a53d3e2012-08-14 10:47:54 -07001154 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001155 }
1156
Kenny Root07438c82012-11-02 15:41:02 -07001157 /*
1158 * Here is the history. To improve the security, the parameters to generate the
1159 * master key has been changed. To make a seamless transition, we update the
1160 * file using the same password when the user unlock it for the first time. If
1161 * any thing goes wrong during the transition, the new file will not overwrite
1162 * the old one. This avoids permanent damages of the existing data.
1163 */
1164 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001165 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1166 if (!has_permission(callingUid, P_PASSWORD)) {
1167 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001168 return ::PERMISSION_DENIED;
1169 }
Kenny Root70e3a862012-02-15 17:20:23 -08001170
Kenny Root07438c82012-11-02 15:41:02 -07001171 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001172
Kenny Root07438c82012-11-02 15:41:02 -07001173 switch (mKeyStore->getState()) {
1174 case ::STATE_UNINITIALIZED: {
1175 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1176 return mKeyStore->initialize(password8);
1177 }
1178 case ::STATE_NO_ERROR: {
1179 // rewrite master key with new password.
1180 return mKeyStore->writeMasterKey(password8);
1181 }
1182 case ::STATE_LOCKED: {
1183 // read master key, decrypt with password, initialize mMasterKey*.
1184 return mKeyStore->readMasterKey(password8);
1185 }
1186 }
1187 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001188 }
1189
Kenny Root07438c82012-11-02 15:41:02 -07001190 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001191 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1192 if (!has_permission(callingUid, P_LOCK)) {
1193 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001194 return ::PERMISSION_DENIED;
1195 }
Kenny Root70e3a862012-02-15 17:20:23 -08001196
Kenny Root9d45d1c2013-02-14 10:32:30 -08001197 State state = mKeyStore->getState();
1198 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001199 ALOGD("calling lock in state: %d", state);
1200 return state;
1201 }
1202
1203 mKeyStore->lock();
1204 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001205 }
1206
Kenny Root07438c82012-11-02 15:41:02 -07001207 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001208 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1209 if (!has_permission(callingUid, P_UNLOCK)) {
1210 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001211 return ::PERMISSION_DENIED;
1212 }
1213
Kenny Root9d45d1c2013-02-14 10:32:30 -08001214 State state = mKeyStore->getState();
1215 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001216 ALOGD("calling unlock when not locked");
1217 return state;
1218 }
1219
1220 const String8 password8(pw);
1221 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001222 }
1223
Kenny Root07438c82012-11-02 15:41:02 -07001224 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001225 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1226 if (!has_permission(callingUid, P_ZERO)) {
1227 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001228 return -1;
1229 }
Kenny Root70e3a862012-02-15 17:20:23 -08001230
Kenny Root07438c82012-11-02 15:41:02 -07001231 return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001232 }
1233
Kenny Root49468902013-03-19 13:41:33 -07001234 int32_t generate(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001235 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1236 if (!has_permission(callingUid, P_INSERT)) {
1237 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001238 return ::PERMISSION_DENIED;
1239 }
Kenny Root70e3a862012-02-15 17:20:23 -08001240
Kenny Root49468902013-03-19 13:41:33 -07001241 if (targetUid == -1) {
1242 targetUid = callingUid;
1243 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001244 return ::PERMISSION_DENIED;
1245 }
1246
Kenny Root9d45d1c2013-02-14 10:32:30 -08001247 State state = mKeyStore->getState();
1248 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001249 ALOGD("calling generate in state: %d", state);
1250 return state;
1251 }
Kenny Root70e3a862012-02-15 17:20:23 -08001252
Kenny Root07438c82012-11-02 15:41:02 -07001253 String8 name8(name);
1254 char filename[NAME_MAX];
1255
1256 uint8_t* data;
1257 size_t dataLength;
1258 int rc;
1259
1260 const keymaster_device_t* device = mKeyStore->getDevice();
1261 if (device == NULL) {
1262 return ::SYSTEM_ERROR;
1263 }
1264
1265 if (device->generate_keypair == NULL) {
1266 return ::SYSTEM_ERROR;
1267 }
1268
1269 keymaster_rsa_keygen_params_t rsa_params;
1270 rsa_params.modulus_size = 2048;
1271 rsa_params.public_exponent = 0x10001;
1272
1273 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1274 if (rc) {
1275 return ::SYSTEM_ERROR;
1276 }
1277
Kenny Root49468902013-03-19 13:41:33 -07001278 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001279
1280 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1281 free(data);
1282
1283 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001284 }
1285
Kenny Root49468902013-03-19 13:41:33 -07001286 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001287 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1288 if (!has_permission(callingUid, P_INSERT)) {
1289 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001290 return ::PERMISSION_DENIED;
1291 }
Kenny Root07438c82012-11-02 15:41:02 -07001292
Kenny Root49468902013-03-19 13:41:33 -07001293 if (targetUid == -1) {
1294 targetUid = callingUid;
1295 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001296 return ::PERMISSION_DENIED;
1297 }
1298
Kenny Root9d45d1c2013-02-14 10:32:30 -08001299 State state = mKeyStore->getState();
1300 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001301 ALOGD("calling import in state: %d", state);
1302 return state;
1303 }
1304
1305 String8 name8(name);
1306 char filename[NAME_MAX];
1307
Kenny Root49468902013-03-19 13:41:33 -07001308 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001309
1310 return mKeyStore->importKey(data, length, filename);
Kenny Root70e3a862012-02-15 17:20:23 -08001311 }
1312
Kenny Root07438c82012-11-02 15:41:02 -07001313 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1314 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001315 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1316 if (!has_permission(callingUid, P_SIGN)) {
1317 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001318 return ::PERMISSION_DENIED;
1319 }
Kenny Root07438c82012-11-02 15:41:02 -07001320
Kenny Root9d45d1c2013-02-14 10:32:30 -08001321 State state = mKeyStore->getState();
1322 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001323 ALOGD("calling sign in state: %d", state);
1324 return state;
1325 }
1326
1327 Blob keyBlob;
1328 String8 name8(name);
1329
Kenny Rootd38a0b02013-02-13 12:59:14 -08001330 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001331 int rc;
1332
Kenny Rootd38a0b02013-02-13 12:59:14 -08001333 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1334 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001335 if (responseCode != ::NO_ERROR) {
1336 return responseCode;
1337 }
1338
1339 const keymaster_device_t* device = mKeyStore->getDevice();
1340 if (device == NULL) {
1341 ALOGE("no keymaster device; cannot sign");
1342 return ::SYSTEM_ERROR;
1343 }
1344
1345 if (device->sign_data == NULL) {
1346 ALOGE("device doesn't implement signing");
1347 return ::SYSTEM_ERROR;
1348 }
1349
1350 keymaster_rsa_sign_params_t params;
1351 params.digest_type = DIGEST_NONE;
1352 params.padding_type = PADDING_NONE;
1353
1354 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1355 data, length, out, outLength);
1356 if (rc) {
1357 ALOGW("device couldn't sign data");
1358 return ::SYSTEM_ERROR;
1359 }
1360
1361 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001362 }
1363
Kenny Root07438c82012-11-02 15:41:02 -07001364 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1365 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001366 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1367 if (!has_permission(callingUid, P_VERIFY)) {
1368 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001369 return ::PERMISSION_DENIED;
1370 }
Kenny Root70e3a862012-02-15 17:20:23 -08001371
Kenny Root9d45d1c2013-02-14 10:32:30 -08001372 State state = mKeyStore->getState();
1373 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001374 ALOGD("calling verify in state: %d", state);
1375 return state;
1376 }
Kenny Root70e3a862012-02-15 17:20:23 -08001377
Kenny Root07438c82012-11-02 15:41:02 -07001378 Blob keyBlob;
1379 String8 name8(name);
1380 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001381
Kenny Root49468902013-03-19 13:41:33 -07001382 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1383 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001384 if (responseCode != ::NO_ERROR) {
1385 return responseCode;
1386 }
Kenny Root70e3a862012-02-15 17:20:23 -08001387
Kenny Root07438c82012-11-02 15:41:02 -07001388 const keymaster_device_t* device = mKeyStore->getDevice();
1389 if (device == NULL) {
1390 return ::SYSTEM_ERROR;
1391 }
Kenny Root70e3a862012-02-15 17:20:23 -08001392
Kenny Root07438c82012-11-02 15:41:02 -07001393 if (device->verify_data == NULL) {
1394 return ::SYSTEM_ERROR;
1395 }
Kenny Root70e3a862012-02-15 17:20:23 -08001396
Kenny Root07438c82012-11-02 15:41:02 -07001397 keymaster_rsa_sign_params_t params;
1398 params.digest_type = DIGEST_NONE;
1399 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001400
Kenny Root07438c82012-11-02 15:41:02 -07001401 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1402 data, dataLength, signature, signatureLength);
1403 if (rc) {
1404 return ::SYSTEM_ERROR;
1405 } else {
1406 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001407 }
1408 }
Kenny Root07438c82012-11-02 15:41:02 -07001409
1410 /*
1411 * TODO: The abstraction between things stored in hardware and regular blobs
1412 * of data stored on the filesystem should be moved down to keystore itself.
1413 * Unfortunately the Java code that calls this has naming conventions that it
1414 * knows about. Ideally keystore shouldn't be used to store random blobs of
1415 * data.
1416 *
1417 * Until that happens, it's necessary to have a separate "get_pubkey" and
1418 * "del_key" since the Java code doesn't really communicate what it's
1419 * intentions are.
1420 */
1421 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001422 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1423 if (!has_permission(callingUid, P_GET)) {
1424 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001425 return ::PERMISSION_DENIED;
1426 }
Kenny Root07438c82012-11-02 15:41:02 -07001427
Kenny Root9d45d1c2013-02-14 10:32:30 -08001428 State state = mKeyStore->getState();
1429 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001430 ALOGD("calling get_pubkey in state: %d", state);
1431 return state;
1432 }
1433
1434 Blob keyBlob;
1435 String8 name8(name);
1436
Kenny Rootd38a0b02013-02-13 12:59:14 -08001437 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001438
Kenny Rootd38a0b02013-02-13 12:59:14 -08001439 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001440 TYPE_KEY_PAIR);
1441 if (responseCode != ::NO_ERROR) {
1442 return responseCode;
1443 }
1444
1445 const keymaster_device_t* device = mKeyStore->getDevice();
1446 if (device == NULL) {
1447 return ::SYSTEM_ERROR;
1448 }
1449
1450 if (device->get_keypair_public == NULL) {
1451 ALOGE("device has no get_keypair_public implementation!");
1452 return ::SYSTEM_ERROR;
1453 }
1454
1455 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1456 pubkeyLength);
1457 if (rc) {
1458 return ::SYSTEM_ERROR;
1459 }
1460
1461 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001462 }
Kenny Root07438c82012-11-02 15:41:02 -07001463
Kenny Root49468902013-03-19 13:41:33 -07001464 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001465 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1466 if (!has_permission(callingUid, P_DELETE)) {
1467 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001468 return ::PERMISSION_DENIED;
1469 }
Kenny Root07438c82012-11-02 15:41:02 -07001470
Kenny Root49468902013-03-19 13:41:33 -07001471 if (targetUid == -1) {
1472 targetUid = callingUid;
1473 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001474 return ::PERMISSION_DENIED;
1475 }
1476
Kenny Root07438c82012-11-02 15:41:02 -07001477 String8 name8(name);
1478 char filename[NAME_MAX];
1479
Kenny Root49468902013-03-19 13:41:33 -07001480 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001481
1482 Blob keyBlob;
1483 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1484 if (responseCode != ::NO_ERROR) {
1485 return responseCode;
1486 }
1487
1488 ResponseCode rc = ::NO_ERROR;
1489
1490 const keymaster_device_t* device = mKeyStore->getDevice();
1491 if (device == NULL) {
1492 rc = ::SYSTEM_ERROR;
1493 } else {
1494 // A device doesn't have to implement delete_keypair.
1495 if (device->delete_keypair != NULL) {
1496 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1497 rc = ::SYSTEM_ERROR;
1498 }
1499 }
1500 }
1501
1502 if (rc != ::NO_ERROR) {
1503 return rc;
1504 }
1505
1506 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1507 }
1508
1509 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001510 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1511 if (!has_permission(callingUid, P_GRANT)) {
1512 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001513 return ::PERMISSION_DENIED;
1514 }
Kenny Root07438c82012-11-02 15:41:02 -07001515
Kenny Root9d45d1c2013-02-14 10:32:30 -08001516 State state = mKeyStore->getState();
1517 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001518 ALOGD("calling grant in state: %d", state);
1519 return state;
1520 }
1521
1522 String8 name8(name);
1523 char filename[NAME_MAX];
1524
Kenny Rootd38a0b02013-02-13 12:59:14 -08001525 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001526
1527 if (access(filename, R_OK) == -1) {
1528 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1529 }
1530
1531 mKeyStore->addGrant(filename, granteeUid);
1532 return ::NO_ERROR;
1533 }
1534
1535 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001536 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1537 if (!has_permission(callingUid, P_GRANT)) {
1538 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001539 return ::PERMISSION_DENIED;
1540 }
Kenny Root07438c82012-11-02 15:41:02 -07001541
Kenny Root9d45d1c2013-02-14 10:32:30 -08001542 State state = mKeyStore->getState();
1543 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001544 ALOGD("calling ungrant in state: %d", state);
1545 return state;
1546 }
1547
1548 String8 name8(name);
1549 char filename[NAME_MAX];
1550
Kenny Rootd38a0b02013-02-13 12:59:14 -08001551 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001552
1553 if (access(filename, R_OK) == -1) {
1554 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1555 }
1556
1557 return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1558 }
1559
1560 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001561 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1562 if (!has_permission(callingUid, P_GET)) {
1563 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001564 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001565 }
Kenny Root07438c82012-11-02 15:41:02 -07001566
1567 String8 name8(name);
1568 char filename[NAME_MAX];
1569
Kenny Rootd38a0b02013-02-13 12:59:14 -08001570 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001571
1572 if (access(filename, R_OK) == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001573 ALOGW("could not access %s for getmtime", filename);
1574 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001575 }
1576
Kenny Root150ca932012-11-14 14:29:02 -08001577 int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001578 if (fd < 0) {
Kenny Root36a9e232013-02-04 14:24:15 -08001579 ALOGW("could not open %s for getmtime", filename);
1580 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001581 }
1582
1583 struct stat s;
1584 int ret = fstat(fd, &s);
1585 close(fd);
1586 if (ret == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001587 ALOGW("could not stat %s for getmtime", filename);
1588 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001589 }
1590
Kenny Root36a9e232013-02-04 14:24:15 -08001591 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001592 }
1593
Kenny Rootd53bc922013-03-21 14:10:15 -07001594 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1595 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07001596 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07001597 if (!has_permission(callingUid, P_DUPLICATE)) {
1598 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07001599 return -1L;
1600 }
1601
1602 State state = mKeyStore->getState();
1603 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07001604 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07001605 return state;
1606 }
1607
Kenny Rootd53bc922013-03-21 14:10:15 -07001608 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1609 srcUid = callingUid;
1610 } else if (!is_granted_to(callingUid, srcUid)) {
1611 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07001612 return ::PERMISSION_DENIED;
1613 }
1614
Kenny Rootd53bc922013-03-21 14:10:15 -07001615 if (destUid == -1) {
1616 destUid = callingUid;
1617 }
1618
1619 if (srcUid != destUid) {
1620 if (static_cast<uid_t>(srcUid) != callingUid) {
1621 ALOGD("can only duplicate from caller to other or to same uid: "
1622 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
1623 return ::PERMISSION_DENIED;
1624 }
1625
1626 if (!is_granted_to(callingUid, destUid)) {
1627 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
1628 return ::PERMISSION_DENIED;
1629 }
1630 }
1631
1632 String8 source8(srcKey);
Kenny Root02254072013-03-20 11:48:19 -07001633 char source[NAME_MAX];
1634
Kenny Rootd53bc922013-03-21 14:10:15 -07001635 encode_key_for_uid(source, srcUid, source8);
Kenny Root02254072013-03-20 11:48:19 -07001636
Kenny Rootd53bc922013-03-21 14:10:15 -07001637 String8 target8(destKey);
Kenny Root02254072013-03-20 11:48:19 -07001638 char target[NAME_MAX];
1639
Kenny Rootd53bc922013-03-21 14:10:15 -07001640 encode_key_for_uid(target, destUid, target8);
Kenny Root02254072013-03-20 11:48:19 -07001641
Kenny Rootd53bc922013-03-21 14:10:15 -07001642 if (access(target, W_OK) != -1 || errno != ENOENT) {
1643 ALOGD("destination already exists: %s", target);
Kenny Root02254072013-03-20 11:48:19 -07001644 return ::SYSTEM_ERROR;
1645 }
1646
Kenny Rootd53bc922013-03-21 14:10:15 -07001647 Blob keyBlob;
1648 ResponseCode responseCode = mKeyStore->get(source, &keyBlob, TYPE_ANY);
1649 if (responseCode != ::NO_ERROR) {
1650 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07001651 }
Kenny Rootd53bc922013-03-21 14:10:15 -07001652
1653 return mKeyStore->put(target, &keyBlob);
Kenny Root02254072013-03-20 11:48:19 -07001654 }
1655
Kenny Root8ddf35a2013-03-29 11:15:50 -07001656 int32_t is_hardware_backed() {
1657 return mKeyStore->isHardwareBacked() ? 1 : 0;
1658 }
1659
Kenny Roota9bb5492013-04-01 16:29:11 -07001660 int32_t clear_uid(int64_t targetUid) {
1661 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1662 if (!has_permission(callingUid, P_CLEAR_UID)) {
1663 ALOGW("permission denied for %d: clear_uid", callingUid);
1664 return ::PERMISSION_DENIED;
1665 }
1666
1667 State state = mKeyStore->getState();
1668 if (!isKeystoreUnlocked(state)) {
1669 ALOGD("calling clear_uid in state: %d", state);
1670 return state;
1671 }
1672
1673 const keymaster_device_t* device = mKeyStore->getDevice();
1674 if (device == NULL) {
1675 return ::SYSTEM_ERROR;
1676 }
1677
1678 DIR* dir = opendir(".");
1679 if (!dir) {
1680 return ::SYSTEM_ERROR;
1681 }
1682
1683 char filename[NAME_MAX];
1684 int n = snprintf(filename, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
1685 char *end = &filename[n];
1686
1687 ResponseCode rc = ::NO_ERROR;
1688
1689 struct dirent* file;
1690 while ((file = readdir(dir)) != NULL) {
1691 if (strncmp(filename, file->d_name, n)) {
1692 continue;
1693 }
1694
1695 String8 file8(&file->d_name[n]);
1696 encode_key(end, file8);
1697
1698 Blob keyBlob;
1699 if (mKeyStore->get(filename, &keyBlob, ::TYPE_ANY) != ::NO_ERROR) {
1700 ALOGW("couldn't open %s", filename);
1701 continue;
1702 }
1703
1704 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1705 // A device doesn't have to implement delete_keypair.
1706 if (device->delete_keypair != NULL) {
1707 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1708 rc = ::SYSTEM_ERROR;
1709 ALOGW("device couldn't remove %s", filename);
1710 }
1711 }
1712 }
1713
1714 if (unlink(filename) && errno != ENOENT) {
1715 rc = ::SYSTEM_ERROR;
1716 ALOGW("couldn't unlink %s", filename);
1717 }
1718 }
1719 closedir(dir);
1720
1721 return rc;
1722 }
1723
Kenny Root07438c82012-11-02 15:41:02 -07001724private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08001725 inline bool isKeystoreUnlocked(State state) {
1726 switch (state) {
1727 case ::STATE_NO_ERROR:
1728 return true;
1729 case ::STATE_UNINITIALIZED:
1730 case ::STATE_LOCKED:
1731 return false;
1732 }
1733 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001734 }
1735
1736 ::KeyStore* mKeyStore;
1737};
1738
1739}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08001740
1741int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08001742 if (argc < 2) {
1743 ALOGE("A directory must be specified!");
1744 return 1;
1745 }
1746 if (chdir(argv[1]) == -1) {
1747 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1748 return 1;
1749 }
1750
1751 Entropy entropy;
1752 if (!entropy.open()) {
1753 return 1;
1754 }
Kenny Root70e3a862012-02-15 17:20:23 -08001755
1756 keymaster_device_t* dev;
1757 if (keymaster_device_initialize(&dev)) {
1758 ALOGE("keystore keymaster could not be initialized; exiting");
1759 return 1;
1760 }
1761
Kenny Root70e3a862012-02-15 17:20:23 -08001762 KeyStore keyStore(&entropy, dev);
Kenny Root07438c82012-11-02 15:41:02 -07001763 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1764 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1765 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1766 if (ret != android::OK) {
1767 ALOGE("Couldn't register binder service!");
1768 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08001769 }
Kenny Root07438c82012-11-02 15:41:02 -07001770
1771 /*
1772 * We're the only thread in existence, so we're just going to process
1773 * Binder transaction as a single-threaded program.
1774 */
1775 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08001776
1777 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08001778 return 1;
1779}