• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 #include <stdio.h>
18 #include <stdint.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <signal.h>
22 #include <errno.h>
23 #include <dirent.h>
24 #include <fcntl.h>
25 #include <limits.h>
26 #include <assert.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31 #include <arpa/inet.h>
32 
33 #include <openssl/aes.h>
34 #include <openssl/bio.h>
35 #include <openssl/evp.h>
36 #include <openssl/md5.h>
37 #include <openssl/pem.h>
38 
39 #include <hardware/keymaster.h>
40 
41 #include <utils/UniquePtr.h>
42 
43 #include <cutils/list.h>
44 
45 //#define LOG_NDEBUG 0
46 #define LOG_TAG "keystore"
47 #include <cutils/log.h>
48 #include <cutils/sockets.h>
49 #include <private/android_filesystem_config.h>
50 
51 #include "keystore.h"
52 
53 /* KeyStore is a secured storage for key-value pairs. In this implementation,
54  * each file stores one key-value pair. Keys are encoded in file names, and
55  * values are encrypted with checksums. The encryption key is protected by a
56  * user-defined password. To keep things simple, buffers are always larger than
57  * the maximum space we needed, so boundary checks on buffers are omitted. */
58 
59 #define KEY_SIZE        ((NAME_MAX - 15) / 2)
60 #define VALUE_SIZE      32768
61 #define PASSWORD_SIZE   VALUE_SIZE
62 
63 
64 struct BIO_Delete {
operator ()BIO_Delete65     void operator()(BIO* p) const {
66         BIO_free(p);
67     }
68 };
69 typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
70 
71 struct EVP_PKEY_Delete {
operator ()EVP_PKEY_Delete72     void operator()(EVP_PKEY* p) const {
73         EVP_PKEY_free(p);
74     }
75 };
76 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
77 
78 struct PKCS8_PRIV_KEY_INFO_Delete {
operator ()PKCS8_PRIV_KEY_INFO_Delete79     void operator()(PKCS8_PRIV_KEY_INFO* p) const {
80         PKCS8_PRIV_KEY_INFO_free(p);
81     }
82 };
83 typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
84 
85 
86 struct Value {
ValueValue87     Value(const uint8_t* orig, int origLen) {
88         assert(origLen <= VALUE_SIZE);
89         memcpy(value, orig, origLen);
90         length = origLen;
91     }
92 
ValueValue93     Value() {
94     }
95 
96     int length;
97     uint8_t value[VALUE_SIZE];
98 };
99 
100 class ValueString {
101 public:
ValueString(const Value * orig)102     ValueString(const Value* orig) {
103         assert(length <= VALUE_SIZE);
104         length = orig->length;
105         value = new char[length + 1];
106         memcpy(value, orig->value, length);
107         value[length] = '\0';
108     }
109 
~ValueString()110     ~ValueString() {
111         delete[] value;
112     }
113 
c_str() const114     const char* c_str() const {
115         return value;
116     }
117 
release()118     char* release() {
119         char* ret = value;
120         value = NULL;
121         return ret;
122     }
123 
124 private:
125     char* value;
126     size_t length;
127 };
128 
keymaster_device_initialize(keymaster_device_t ** dev)129 static int keymaster_device_initialize(keymaster_device_t** dev) {
130     int rc;
131 
132     const hw_module_t* mod;
133     rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
134     if (rc) {
135         ALOGE("could not find any keystore module");
136         goto out;
137     }
138 
139     rc = keymaster_open(mod, dev);
140     if (rc) {
141         ALOGE("could not open keymaster device in %s (%s)",
142             KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
143         goto out;
144     }
145 
146     return 0;
147 
148 out:
149     *dev = NULL;
150     return rc;
151 }
152 
keymaster_device_release(keymaster_device_t * dev)153 static void keymaster_device_release(keymaster_device_t* dev) {
154     keymaster_close(dev);
155 }
156 
157 /* Here is the encoding of keys. This is necessary in order to allow arbitrary
158  * characters in keys. Characters in [0-~] are not encoded. Others are encoded
159  * into two bytes. The first byte is one of [+-.] which represents the first
160  * two bits of the character. The second byte encodes the rest of the bits into
161  * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
162  * that Base64 cannot be used here due to the need of prefix match on keys. */
163 
encode_key(char * out,const Value * key)164 static int encode_key(char* out, const Value* key) {
165     const uint8_t* in = key->value;
166     int length = key->length;
167     for (int i = length; i > 0; --i, ++in, ++out) {
168         if (*in >= '0' && *in <= '~') {
169             *out = *in;
170         } else {
171             *out = '+' + (*in >> 6);
172             *++out = '0' + (*in & 0x3F);
173             ++length;
174         }
175     }
176     *out = '\0';
177     return length;
178 }
179 
encode_key_for_uid(char * out,uid_t uid,const Value * key)180 static int encode_key_for_uid(char* out, uid_t uid, const Value* key) {
181     int n = snprintf(out, NAME_MAX, "%u_", uid);
182     out += n;
183 
184     return n + encode_key(out, key);
185 }
186 
decode_key(uint8_t * out,const char * in,int length)187 static int decode_key(uint8_t* out, const char* in, int length) {
188     for (int i = 0; i < length; ++i, ++in, ++out) {
189         if (*in >= '0' && *in <= '~') {
190             *out = *in;
191         } else {
192             *out = (*in - '+') << 6;
193             *out |= (*++in - '0') & 0x3F;
194             --length;
195         }
196     }
197     *out = '\0';
198     return length;
199 }
200 
readFully(int fd,uint8_t * data,size_t size)201 static size_t readFully(int fd, uint8_t* data, size_t size) {
202     size_t remaining = size;
203     while (remaining > 0) {
204         ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, size));
205         if (n == -1 || n == 0) {
206             return size-remaining;
207         }
208         data += n;
209         remaining -= n;
210     }
211     return size;
212 }
213 
writeFully(int fd,uint8_t * data,size_t size)214 static size_t writeFully(int fd, uint8_t* data, size_t size) {
215     size_t remaining = size;
216     while (remaining > 0) {
217         ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, size));
218         if (n == -1 || n == 0) {
219             return size-remaining;
220         }
221         data += n;
222         remaining -= n;
223     }
224     return size;
225 }
226 
227 class Entropy {
228 public:
Entropy()229     Entropy() : mRandom(-1) {}
~Entropy()230     ~Entropy() {
231         if (mRandom != -1) {
232             close(mRandom);
233         }
234     }
235 
open()236     bool open() {
237         const char* randomDevice = "/dev/urandom";
238         mRandom = ::open(randomDevice, O_RDONLY);
239         if (mRandom == -1) {
240             ALOGE("open: %s: %s", randomDevice, strerror(errno));
241             return false;
242         }
243         return true;
244     }
245 
generate_random_data(uint8_t * data,size_t size) const246     bool generate_random_data(uint8_t* data, size_t size) const {
247         return (readFully(mRandom, data, size) == size);
248     }
249 
250 private:
251     int mRandom;
252 };
253 
254 /* Here is the file format. There are two parts in blob.value, the secret and
255  * the description. The secret is stored in ciphertext, and its original size
256  * can be found in blob.length. The description is stored after the secret in
257  * plaintext, and its size is specified in blob.info. The total size of the two
258  * parts must be no more than VALUE_SIZE bytes. The first field is the version,
259  * the second is the blob's type, and the third byte is reserved. Fields other
260  * than blob.info, blob.length, and blob.value are modified by encryptBlob()
261  * and decryptBlob(). Thus they should not be accessed from outside. */
262 
263 /* ** Note to future implementors of encryption: **
264  * Currently this is the construction:
265  *   metadata || Enc(MD5(data) || data)
266  *
267  * This should be the construction used for encrypting if re-implementing:
268  *
269  *   Derive independent keys for encryption and MAC:
270  *     Kenc = AES_encrypt(masterKey, "Encrypt")
271  *     Kmac = AES_encrypt(masterKey, "MAC")
272  *
273  *   Store this:
274  *     metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
275  *             HMAC(Kmac, metadata || Enc(data))
276  */
277 struct __attribute__((packed)) blob {
278     uint8_t version;
279     uint8_t type;
280     uint8_t reserved;
281     uint8_t info;
282     uint8_t vector[AES_BLOCK_SIZE];
283     uint8_t encrypted[0]; // Marks offset to encrypted data.
284     uint8_t digest[MD5_DIGEST_LENGTH];
285     uint8_t digested[0]; // Marks offset to digested data.
286     int32_t length; // in network byte order when encrypted
287     uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
288 };
289 
290 typedef enum {
291     TYPE_GENERIC = 1,
292     TYPE_MASTER_KEY = 2,
293     TYPE_KEY_PAIR = 3,
294 } BlobType;
295 
296 static const uint8_t CurrentBlobVersion = 1;
297 
298 class Blob {
299 public:
Blob(uint8_t * value,int32_t valueLength,uint8_t * info,uint8_t infoLength,BlobType type)300     Blob(uint8_t* value, int32_t valueLength, uint8_t* info, uint8_t infoLength, BlobType type) {
301         mBlob.length = valueLength;
302         memcpy(mBlob.value, value, valueLength);
303 
304         mBlob.info = infoLength;
305         memcpy(mBlob.value + valueLength, info, infoLength);
306 
307         mBlob.version = CurrentBlobVersion;
308         mBlob.type = uint8_t(type);
309     }
310 
Blob(blob b)311     Blob(blob b) {
312         mBlob = b;
313     }
314 
Blob()315     Blob() {}
316 
getValue() const317     const uint8_t* getValue() const {
318         return mBlob.value;
319     }
320 
getLength() const321     int32_t getLength() const {
322         return mBlob.length;
323     }
324 
getInfo() const325     const uint8_t* getInfo() const {
326         return mBlob.value + mBlob.length;
327     }
328 
getInfoLength() const329     uint8_t getInfoLength() const {
330         return mBlob.info;
331     }
332 
getVersion() const333     uint8_t getVersion() const {
334         return mBlob.version;
335     }
336 
setVersion(uint8_t version)337     void setVersion(uint8_t version) {
338         mBlob.version = version;
339     }
340 
getType() const341     BlobType getType() const {
342         return BlobType(mBlob.type);
343     }
344 
setType(BlobType type)345     void setType(BlobType type) {
346         mBlob.type = uint8_t(type);
347     }
348 
encryptBlob(const char * filename,AES_KEY * aes_key,Entropy * entropy)349     ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
350         if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
351             return SYSTEM_ERROR;
352         }
353 
354         // data includes the value and the value's length
355         size_t dataLength = mBlob.length + sizeof(mBlob.length);
356         // pad data to the AES_BLOCK_SIZE
357         size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
358                                  / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
359         // encrypted data includes the digest value
360         size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
361         // move info after space for padding
362         memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
363         // zero padding area
364         memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
365 
366         mBlob.length = htonl(mBlob.length);
367         MD5(mBlob.digested, digestedLength, mBlob.digest);
368 
369         uint8_t vector[AES_BLOCK_SIZE];
370         memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
371         AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
372                         aes_key, vector, AES_ENCRYPT);
373 
374         mBlob.reserved = 0;
375         size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
376         size_t fileLength = encryptedLength + headerLength + mBlob.info;
377 
378         const char* tmpFileName = ".tmp";
379         int out = open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
380         if (out == -1) {
381             return SYSTEM_ERROR;
382         }
383         size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
384         if (close(out) != 0) {
385             return SYSTEM_ERROR;
386         }
387         if (writtenBytes != fileLength) {
388             unlink(tmpFileName);
389             return SYSTEM_ERROR;
390         }
391         return (rename(tmpFileName, filename) == 0) ? NO_ERROR : SYSTEM_ERROR;
392     }
393 
decryptBlob(const char * filename,AES_KEY * aes_key)394     ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
395         int in = open(filename, O_RDONLY);
396         if (in == -1) {
397             return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
398         }
399         // fileLength may be less than sizeof(mBlob) since the in
400         // memory version has extra padding to tolerate rounding up to
401         // the AES_BLOCK_SIZE
402         size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
403         if (close(in) != 0) {
404             return SYSTEM_ERROR;
405         }
406         size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
407         if (fileLength < headerLength) {
408             return VALUE_CORRUPTED;
409         }
410 
411         ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
412         if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
413             return VALUE_CORRUPTED;
414         }
415         AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
416                         mBlob.vector, AES_DECRYPT);
417         size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
418         uint8_t computedDigest[MD5_DIGEST_LENGTH];
419         MD5(mBlob.digested, digestedLength, computedDigest);
420         if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
421             return VALUE_CORRUPTED;
422         }
423 
424         ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
425         mBlob.length = ntohl(mBlob.length);
426         if (mBlob.length < 0 || mBlob.length > maxValueLength) {
427             return VALUE_CORRUPTED;
428         }
429         if (mBlob.info != 0) {
430             // move info from after padding to after data
431             memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
432         }
433         return NO_ERROR;
434     }
435 
436 private:
437     struct blob mBlob;
438 };
439 
440 typedef struct {
441     uint32_t uid;
442     const uint8_t* keyName;
443 
444     struct listnode plist;
445 } grant_t;
446 
447 class KeyStore {
448 public:
KeyStore(Entropy * entropy,keymaster_device_t * device)449     KeyStore(Entropy* entropy, keymaster_device_t* device)
450         : mEntropy(entropy)
451         , mDevice(device)
452         , mRetry(MAX_RETRY)
453     {
454         if (access(MASTER_KEY_FILE, R_OK) == 0) {
455             setState(STATE_LOCKED);
456         } else {
457             setState(STATE_UNINITIALIZED);
458         }
459 
460         list_init(&mGrants);
461     }
462 
getState() const463     State getState() const {
464         return mState;
465     }
466 
getRetry() const467     int8_t getRetry() const {
468         return mRetry;
469     }
470 
getDevice() const471     keymaster_device_t* getDevice() const {
472         return mDevice;
473     }
474 
initialize(Value * pw)475     ResponseCode initialize(Value* pw) {
476         if (!generateMasterKey()) {
477             return SYSTEM_ERROR;
478         }
479         ResponseCode response = writeMasterKey(pw);
480         if (response != NO_ERROR) {
481             return response;
482         }
483         setupMasterKeys();
484         return NO_ERROR;
485     }
486 
writeMasterKey(Value * pw)487     ResponseCode writeMasterKey(Value* pw) {
488         uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
489         generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
490         AES_KEY passwordAesKey;
491         AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
492         Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
493         return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
494     }
495 
readMasterKey(Value * pw)496     ResponseCode readMasterKey(Value* pw) {
497         int in = open(MASTER_KEY_FILE, O_RDONLY);
498         if (in == -1) {
499             return SYSTEM_ERROR;
500         }
501 
502         // we read the raw blob to just to get the salt to generate
503         // the AES key, then we create the Blob to use with decryptBlob
504         blob rawBlob;
505         size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
506         if (close(in) != 0) {
507             return SYSTEM_ERROR;
508         }
509         // find salt at EOF if present, otherwise we have an old file
510         uint8_t* salt;
511         if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
512             salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
513         } else {
514             salt = NULL;
515         }
516         uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
517         generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
518         AES_KEY passwordAesKey;
519         AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
520         Blob masterKeyBlob(rawBlob);
521         ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
522         if (response == SYSTEM_ERROR) {
523             return SYSTEM_ERROR;
524         }
525         if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
526             // if salt was missing, generate one and write a new master key file with the salt.
527             if (salt == NULL) {
528                 if (!generateSalt()) {
529                     return SYSTEM_ERROR;
530                 }
531                 response = writeMasterKey(pw);
532             }
533             if (response == NO_ERROR) {
534                 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
535                 setupMasterKeys();
536             }
537             return response;
538         }
539         if (mRetry <= 0) {
540             reset();
541             return UNINITIALIZED;
542         }
543         --mRetry;
544         switch (mRetry) {
545             case 0: return WRONG_PASSWORD_0;
546             case 1: return WRONG_PASSWORD_1;
547             case 2: return WRONG_PASSWORD_2;
548             case 3: return WRONG_PASSWORD_3;
549             default: return WRONG_PASSWORD_3;
550         }
551     }
552 
reset()553     bool reset() {
554         clearMasterKeys();
555         setState(STATE_UNINITIALIZED);
556 
557         DIR* dir = opendir(".");
558         struct dirent* file;
559 
560         if (!dir) {
561             return false;
562         }
563         while ((file = readdir(dir)) != NULL) {
564             unlink(file->d_name);
565         }
566         closedir(dir);
567         return true;
568     }
569 
isEmpty() const570     bool isEmpty() const {
571         DIR* dir = opendir(".");
572         struct dirent* file;
573         if (!dir) {
574             return true;
575         }
576         bool result = true;
577         while ((file = readdir(dir)) != NULL) {
578             if (isKeyFile(file->d_name)) {
579                 result = false;
580                 break;
581             }
582         }
583         closedir(dir);
584         return result;
585     }
586 
lock()587     void lock() {
588         clearMasterKeys();
589         setState(STATE_LOCKED);
590     }
591 
get(const char * filename,Blob * keyBlob,const BlobType type)592     ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
593         ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
594         if (rc != NO_ERROR) {
595             return rc;
596         }
597 
598         const uint8_t version = keyBlob->getVersion();
599         if (version < CurrentBlobVersion) {
600             upgrade(filename, keyBlob, version, type);
601         }
602 
603         if (keyBlob->getType() != type) {
604             ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
605             return KEY_NOT_FOUND;
606         }
607 
608         return rc;
609     }
610 
put(const char * filename,Blob * keyBlob)611     ResponseCode put(const char* filename, Blob* keyBlob) {
612         return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
613     }
614 
addGrant(const char * filename,const Value * uidValue)615     void addGrant(const char* filename, const Value* uidValue) {
616         uid_t uid;
617         if (!convertToUid(uidValue, &uid)) {
618             return;
619         }
620 
621         grant_t *grant = getGrant(filename, uid);
622         if (grant == NULL) {
623             grant = new grant_t;
624             grant->uid = uid;
625             grant->keyName = reinterpret_cast<const uint8_t*>(strdup(filename));
626             list_add_tail(&mGrants, &grant->plist);
627         }
628     }
629 
removeGrant(const Value * keyValue,const Value * uidValue)630     bool removeGrant(const Value* keyValue, const Value* uidValue) {
631         uid_t uid;
632         if (!convertToUid(uidValue, &uid)) {
633             return false;
634         }
635 
636         ValueString keyString(keyValue);
637 
638         grant_t *grant = getGrant(keyString.c_str(), uid);
639         if (grant != NULL) {
640             list_remove(&grant->plist);
641             delete grant;
642             return true;
643         }
644 
645         return false;
646     }
647 
hasGrant(const Value * keyValue,const uid_t uid) const648     bool hasGrant(const Value* keyValue, const uid_t uid) const {
649         ValueString keyString(keyValue);
650         return getGrant(keyString.c_str(), uid) != NULL;
651     }
652 
importKey(const Value * key,const char * filename)653     ResponseCode importKey(const Value* key, const char* filename) {
654         uint8_t* data;
655         size_t dataLength;
656         int rc;
657 
658         if (mDevice->import_keypair == NULL) {
659             ALOGE("Keymaster doesn't support import!");
660             return SYSTEM_ERROR;
661         }
662 
663         rc = mDevice->import_keypair(mDevice, key->value, key->length, &data, &dataLength);
664         if (rc) {
665             ALOGE("Error while importing keypair: %d", rc);
666             return SYSTEM_ERROR;
667         }
668 
669         Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
670         free(data);
671 
672         return put(filename, &keyBlob);
673     }
674 
675 private:
676     static const char* MASTER_KEY_FILE;
677     static const int MASTER_KEY_SIZE_BYTES = 16;
678     static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
679 
680     static const int MAX_RETRY = 4;
681     static const size_t SALT_SIZE = 16;
682 
683     Entropy* mEntropy;
684 
685     keymaster_device_t* mDevice;
686 
687     State mState;
688     int8_t mRetry;
689 
690     uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
691     uint8_t mSalt[SALT_SIZE];
692 
693     AES_KEY mMasterKeyEncryption;
694     AES_KEY mMasterKeyDecryption;
695 
696     struct listnode mGrants;
697 
setState(State state)698     void setState(State state) {
699         mState = state;
700         if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
701             mRetry = MAX_RETRY;
702         }
703     }
704 
generateSalt()705     bool generateSalt() {
706         return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
707     }
708 
generateMasterKey()709     bool generateMasterKey() {
710         if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
711             return false;
712         }
713         if (!generateSalt()) {
714             return false;
715         }
716         return true;
717     }
718 
setupMasterKeys()719     void setupMasterKeys() {
720         AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
721         AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
722         setState(STATE_NO_ERROR);
723     }
724 
clearMasterKeys()725     void clearMasterKeys() {
726         memset(mMasterKey, 0, sizeof(mMasterKey));
727         memset(mSalt, 0, sizeof(mSalt));
728         memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
729         memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
730     }
731 
generateKeyFromPassword(uint8_t * key,ssize_t keySize,Value * pw,uint8_t * salt)732     static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, Value* pw, uint8_t* salt) {
733         size_t saltSize;
734         if (salt != NULL) {
735             saltSize = SALT_SIZE;
736         } else {
737             // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
738             salt = (uint8_t*) "keystore";
739             // sizeof = 9, not strlen = 8
740             saltSize = sizeof("keystore");
741         }
742         PKCS5_PBKDF2_HMAC_SHA1((char*) pw->value, pw->length, salt, saltSize, 8192, keySize, key);
743     }
744 
isKeyFile(const char * filename)745     static bool isKeyFile(const char* filename) {
746         return ((strcmp(filename, MASTER_KEY_FILE) != 0)
747                 && (strcmp(filename, ".") != 0)
748                 && (strcmp(filename, "..") != 0));
749     }
750 
getGrant(const char * keyName,uid_t uid) const751     grant_t* getGrant(const char* keyName, uid_t uid) const {
752         struct listnode *node;
753         grant_t *grant;
754 
755         list_for_each(node, &mGrants) {
756             grant = node_to_item(node, grant_t, plist);
757             if (grant->uid == uid
758                     && !strcmp(reinterpret_cast<const char*>(grant->keyName),
759                                keyName)) {
760                 return grant;
761             }
762         }
763 
764         return NULL;
765     }
766 
convertToUid(const Value * uidValue,uid_t * uid) const767     bool convertToUid(const Value* uidValue, uid_t* uid) const {
768         ValueString uidString(uidValue);
769         char* end = NULL;
770         *uid = strtol(uidString.c_str(), &end, 10);
771         return *end == '\0';
772     }
773 
774     /**
775      * Upgrade code. This will upgrade the key from the current version
776      * to whatever is newest.
777      */
upgrade(const char * filename,Blob * blob,const uint8_t oldVersion,const BlobType type)778     void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
779         bool updated = false;
780         uint8_t version = oldVersion;
781 
782         /* From V0 -> V1: All old types were unknown */
783         if (version == 0) {
784             ALOGV("upgrading to version 1 and setting type %d", type);
785 
786             blob->setType(type);
787             if (type == TYPE_KEY_PAIR) {
788                 importBlobAsKey(blob, filename);
789             }
790             version = 1;
791             updated = true;
792         }
793 
794         /*
795          * If we've updated, set the key blob to the right version
796          * and write it.
797          * */
798         if (updated) {
799             ALOGV("updated and writing file %s", filename);
800             blob->setVersion(version);
801             this->put(filename, blob);
802         }
803     }
804 
805     /**
806      * Takes a blob that is an PEM-encoded RSA key as a byte array and
807      * converts it to a DER-encoded PKCS#8 for import into a keymaster.
808      * Then it overwrites the original blob with the new blob
809      * format that is returned from the keymaster.
810      */
importBlobAsKey(Blob * blob,const char * filename)811     ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
812         // We won't even write to the blob directly with this BIO, so const_cast is okay.
813         Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
814         if (b.get() == NULL) {
815             ALOGE("Problem instantiating BIO");
816             return SYSTEM_ERROR;
817         }
818 
819         Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
820         if (pkey.get() == NULL) {
821             ALOGE("Couldn't read old PEM file");
822             return SYSTEM_ERROR;
823         }
824 
825         Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
826         int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
827         if (len < 0) {
828             ALOGE("Couldn't measure PKCS#8 length");
829             return SYSTEM_ERROR;
830         }
831 
832         Value pkcs8key;
833         pkcs8key.length = len;
834         uint8_t* tmp = pkcs8key.value;
835         if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
836             ALOGE("Couldn't convert to PKCS#8");
837             return SYSTEM_ERROR;
838         }
839 
840         ResponseCode rc = importKey(&pkcs8key, filename);
841         if (rc != NO_ERROR) {
842             return rc;
843         }
844 
845         return get(filename, blob, TYPE_KEY_PAIR);
846     }
847 };
848 
849 const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
850 
851 /* Here is the protocol used in both requests and responses:
852  *     code [length_1 message_1 ... length_n message_n] end-of-file
853  * where code is one byte long and lengths are unsigned 16-bit integers in
854  * network order. Thus the maximum length of a message is 65535 bytes. */
855 
recv_code(int sock,int8_t * code)856 static int recv_code(int sock, int8_t* code) {
857     return recv(sock, code, 1, 0) == 1;
858 }
859 
recv_message(int sock,uint8_t * message,int length)860 static int recv_message(int sock, uint8_t* message, int length) {
861     uint8_t bytes[2];
862     if (recv(sock, &bytes[0], 1, 0) != 1 ||
863         recv(sock, &bytes[1], 1, 0) != 1) {
864         return -1;
865     } else {
866         int offset = bytes[0] << 8 | bytes[1];
867         if (length < offset) {
868             return -1;
869         }
870         length = offset;
871         offset = 0;
872         while (offset < length) {
873             int n = recv(sock, &message[offset], length - offset, 0);
874             if (n <= 0) {
875                 return -1;
876             }
877             offset += n;
878         }
879     }
880     return length;
881 }
882 
recv_end_of_file(int sock)883 static int recv_end_of_file(int sock) {
884     uint8_t byte;
885     return recv(sock, &byte, 1, 0) == 0;
886 }
887 
send_code(int sock,int8_t code)888 static void send_code(int sock, int8_t code) {
889     send(sock, &code, 1, 0);
890 }
891 
send_message(int sock,const uint8_t * message,int length)892 static void send_message(int sock, const uint8_t* message, int length) {
893     uint16_t bytes = htons(length);
894     send(sock, &bytes, 2, 0);
895     send(sock, message, length, 0);
896 }
897 
get_key_for_name(KeyStore * keyStore,Blob * keyBlob,const Value * keyName,const uid_t uid,const BlobType type)898 static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob, const Value* keyName,
899         const uid_t uid, const BlobType type) {
900     char filename[NAME_MAX];
901 
902     encode_key_for_uid(filename, uid, keyName);
903     ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
904     if (responseCode == NO_ERROR) {
905         return responseCode;
906     }
907 
908     // If this is the Wifi or VPN user, they actually want system
909     // UID keys.
910     if (uid == AID_WIFI || uid == AID_VPN) {
911         encode_key_for_uid(filename, AID_SYSTEM, keyName);
912         responseCode = keyStore->get(filename, keyBlob, type);
913         if (responseCode == NO_ERROR) {
914             return responseCode;
915         }
916     }
917 
918     // They might be using a granted key.
919     if (!keyStore->hasGrant(keyName, uid)) {
920         return responseCode;
921     }
922 
923     // It is a granted key. Try to load it.
924     encode_key(filename, keyName);
925     return keyStore->get(filename, keyBlob, type);
926 }
927 
928 /* Here are the actions. Each of them is a function without arguments. All
929  * information is defined in global variables, which are set properly before
930  * performing an action. The number of parameters required by each action is
931  * fixed and defined in a table. If the return value of an action is positive,
932  * it will be treated as a response code and transmitted to the client. Note
933  * that the lengths of parameters are checked when they are received, so
934  * boundary checks on parameters are omitted. */
935 
936 static const ResponseCode NO_ERROR_RESPONSE_CODE_SENT = (ResponseCode) 0;
937 
test(KeyStore * keyStore,int,uid_t,Value *,Value *,Value *)938 static ResponseCode test(KeyStore* keyStore, int, uid_t, Value*, Value*, Value*) {
939     return (ResponseCode) keyStore->getState();
940 }
941 
get(KeyStore * keyStore,int sock,uid_t uid,Value * keyName,Value *,Value *)942 static ResponseCode get(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*, Value*) {
943     char filename[NAME_MAX];
944     encode_key_for_uid(filename, uid, keyName);
945     Blob keyBlob;
946     ResponseCode responseCode = keyStore->get(filename, &keyBlob, TYPE_GENERIC);
947     if (responseCode != NO_ERROR) {
948         return responseCode;
949     }
950     send_code(sock, NO_ERROR);
951     send_message(sock, keyBlob.getValue(), keyBlob.getLength());
952     return NO_ERROR_RESPONSE_CODE_SENT;
953 }
954 
insert(KeyStore * keyStore,int,uid_t uid,Value * keyName,Value * val,Value *)955 static ResponseCode insert(KeyStore* keyStore, int, uid_t uid, Value* keyName, Value* val,
956         Value*) {
957     char filename[NAME_MAX];
958     encode_key_for_uid(filename, uid, keyName);
959     Blob keyBlob(val->value, val->length, NULL, 0, TYPE_GENERIC);
960     return keyStore->put(filename, &keyBlob);
961 }
962 
del(KeyStore * keyStore,int,uid_t uid,Value * keyName,Value *,Value *)963 static ResponseCode del(KeyStore* keyStore, int, uid_t uid, Value* keyName, Value*, Value*) {
964     char filename[NAME_MAX];
965     encode_key_for_uid(filename, uid, keyName);
966     Blob keyBlob;
967     ResponseCode responseCode = keyStore->get(filename, &keyBlob, TYPE_GENERIC);
968     if (responseCode != NO_ERROR) {
969         return responseCode;
970     }
971     return (unlink(filename) && errno != ENOENT) ? SYSTEM_ERROR : NO_ERROR;
972 }
973 
exist(KeyStore *,int,uid_t uid,Value * keyName,Value *,Value *)974 static ResponseCode exist(KeyStore*, int, uid_t uid, Value* keyName, Value*, Value*) {
975     char filename[NAME_MAX];
976     encode_key_for_uid(filename, uid, keyName);
977     if (access(filename, R_OK) == -1) {
978         return (errno != ENOENT) ? SYSTEM_ERROR : KEY_NOT_FOUND;
979     }
980     return NO_ERROR;
981 }
982 
saw(KeyStore *,int sock,uid_t uid,Value * keyPrefix,Value *,Value *)983 static ResponseCode saw(KeyStore*, int sock, uid_t uid, Value* keyPrefix, Value*, Value*) {
984     DIR* dir = opendir(".");
985     if (!dir) {
986         return SYSTEM_ERROR;
987     }
988     char filename[NAME_MAX];
989     int n = encode_key_for_uid(filename, uid, keyPrefix);
990     send_code(sock, NO_ERROR);
991 
992     struct dirent* file;
993     while ((file = readdir(dir)) != NULL) {
994         if (!strncmp(filename, file->d_name, n)) {
995             const char* p = &file->d_name[n];
996             keyPrefix->length = decode_key(keyPrefix->value, p, strlen(p));
997             send_message(sock, keyPrefix->value, keyPrefix->length);
998         }
999     }
1000     closedir(dir);
1001     return NO_ERROR_RESPONSE_CODE_SENT;
1002 }
1003 
reset(KeyStore * keyStore,int,uid_t,Value *,Value *,Value *)1004 static ResponseCode reset(KeyStore* keyStore, int, uid_t, Value*, Value*, Value*) {
1005     ResponseCode rc = keyStore->reset() ? NO_ERROR : SYSTEM_ERROR;
1006 
1007     const keymaster_device_t* device = keyStore->getDevice();
1008     if (device == NULL) {
1009         ALOGE("No keymaster device!");
1010         return SYSTEM_ERROR;
1011     }
1012 
1013     if (device->delete_all == NULL) {
1014         ALOGV("keymaster device doesn't implement delete_all");
1015         return rc;
1016     }
1017 
1018     if (device->delete_all(device)) {
1019         ALOGE("Problem calling keymaster's delete_all");
1020         return SYSTEM_ERROR;
1021     }
1022 
1023     return rc;
1024 }
1025 
1026 /* Here is the history. To improve the security, the parameters to generate the
1027  * master key has been changed. To make a seamless transition, we update the
1028  * file using the same password when the user unlock it for the first time. If
1029  * any thing goes wrong during the transition, the new file will not overwrite
1030  * the old one. This avoids permanent damages of the existing data. */
1031 
password(KeyStore * keyStore,int,uid_t,Value * pw,Value *,Value *)1032 static ResponseCode password(KeyStore* keyStore, int, uid_t, Value* pw, Value*, Value*) {
1033     switch (keyStore->getState()) {
1034         case STATE_UNINITIALIZED: {
1035             // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1036             return keyStore->initialize(pw);
1037         }
1038         case STATE_NO_ERROR: {
1039             // rewrite master key with new password.
1040             return keyStore->writeMasterKey(pw);
1041         }
1042         case STATE_LOCKED: {
1043             // read master key, decrypt with password, initialize mMasterKey*.
1044             return keyStore->readMasterKey(pw);
1045         }
1046     }
1047     return SYSTEM_ERROR;
1048 }
1049 
lock(KeyStore * keyStore,int,uid_t,Value *,Value *,Value *)1050 static ResponseCode lock(KeyStore* keyStore, int, uid_t, Value*, Value*, Value*) {
1051     keyStore->lock();
1052     return NO_ERROR;
1053 }
1054 
unlock(KeyStore * keyStore,int sock,uid_t uid,Value * pw,Value * unused,Value * unused2)1055 static ResponseCode unlock(KeyStore* keyStore, int sock, uid_t uid, Value* pw, Value* unused,
1056         Value* unused2) {
1057     return password(keyStore, sock, uid, pw, unused, unused2);
1058 }
1059 
zero(KeyStore * keyStore,int,uid_t,Value *,Value *,Value *)1060 static ResponseCode zero(KeyStore* keyStore, int, uid_t, Value*, Value*, Value*) {
1061     return keyStore->isEmpty() ? KEY_NOT_FOUND : NO_ERROR;
1062 }
1063 
generate(KeyStore * keyStore,int,uid_t uid,Value * keyName,Value *,Value *)1064 static ResponseCode generate(KeyStore* keyStore, int, uid_t uid, Value* keyName, Value*,
1065         Value*) {
1066     char filename[NAME_MAX];
1067     uint8_t* data;
1068     size_t dataLength;
1069     int rc;
1070 
1071     const keymaster_device_t* device = keyStore->getDevice();
1072     if (device == NULL) {
1073         return SYSTEM_ERROR;
1074     }
1075 
1076     if (device->generate_keypair == NULL) {
1077         return SYSTEM_ERROR;
1078     }
1079 
1080     keymaster_rsa_keygen_params_t rsa_params;
1081     rsa_params.modulus_size = 2048;
1082     rsa_params.public_exponent = 0x10001;
1083 
1084     rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1085     if (rc) {
1086         return SYSTEM_ERROR;
1087     }
1088 
1089     encode_key_for_uid(filename, uid, keyName);
1090 
1091     Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1092     free(data);
1093 
1094     return keyStore->put(filename, &keyBlob);
1095 }
1096 
import(KeyStore * keyStore,int,uid_t uid,Value * keyName,Value * key,Value *)1097 static ResponseCode import(KeyStore* keyStore, int, uid_t uid, Value* keyName, Value* key,
1098         Value*) {
1099     char filename[NAME_MAX];
1100 
1101     encode_key_for_uid(filename, uid, keyName);
1102 
1103     return keyStore->importKey(key, filename);
1104 }
1105 
1106 /*
1107  * TODO: The abstraction between things stored in hardware and regular blobs
1108  * of data stored on the filesystem should be moved down to keystore itself.
1109  * Unfortunately the Java code that calls this has naming conventions that it
1110  * knows about. Ideally keystore shouldn't be used to store random blobs of
1111  * data.
1112  *
1113  * Until that happens, it's necessary to have a separate "get_pubkey" and
1114  * "del_key" since the Java code doesn't really communicate what it's
1115  * intentions are.
1116  */
get_pubkey(KeyStore * keyStore,int sock,uid_t uid,Value * keyName,Value *,Value *)1117 static ResponseCode get_pubkey(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*, Value*) {
1118     Blob keyBlob;
1119     ALOGV("get_pubkey '%s' from uid %d", ValueString(keyName).c_str(), uid);
1120 
1121     ResponseCode responseCode = get_key_for_name(keyStore, &keyBlob, keyName, uid, TYPE_KEY_PAIR);
1122     if (responseCode != NO_ERROR) {
1123         return responseCode;
1124     }
1125 
1126     const keymaster_device_t* device = keyStore->getDevice();
1127     if (device == NULL) {
1128         return SYSTEM_ERROR;
1129     }
1130 
1131     if (device->get_keypair_public == NULL) {
1132         ALOGE("device has no get_keypair_public implementation!");
1133         return SYSTEM_ERROR;
1134     }
1135 
1136     uint8_t* data = NULL;
1137     size_t dataLength;
1138 
1139     int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), &data,
1140             &dataLength);
1141     if (rc) {
1142         return SYSTEM_ERROR;
1143     }
1144 
1145     send_code(sock, NO_ERROR);
1146     send_message(sock, data, dataLength);
1147     free(data);
1148 
1149     return NO_ERROR_RESPONSE_CODE_SENT;
1150 }
1151 
del_key(KeyStore * keyStore,int,uid_t uid,Value * keyName,Value *,Value *)1152 static ResponseCode del_key(KeyStore* keyStore, int, uid_t uid, Value* keyName, Value*,
1153         Value*) {
1154     char filename[NAME_MAX];
1155     encode_key_for_uid(filename, uid, keyName);
1156     Blob keyBlob;
1157     ResponseCode responseCode = keyStore->get(filename, &keyBlob, TYPE_KEY_PAIR);
1158     if (responseCode != NO_ERROR) {
1159         return responseCode;
1160     }
1161 
1162     const keymaster_device_t* device = keyStore->getDevice();
1163     if (device == NULL) {
1164         return SYSTEM_ERROR;
1165     }
1166 
1167     if (device->delete_keypair == NULL) {
1168         ALOGE("device has no delete_keypair implementation!");
1169         return SYSTEM_ERROR;
1170     }
1171 
1172     int rc = device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength());
1173 
1174     return rc ? SYSTEM_ERROR : NO_ERROR;
1175 }
1176 
sign(KeyStore * keyStore,int sock,uid_t uid,Value * keyName,Value * data,Value *)1177 static ResponseCode sign(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value* data,
1178         Value*) {
1179     ALOGV("sign %s from uid %d", ValueString(keyName).c_str(), uid);
1180     Blob keyBlob;
1181     int rc;
1182 
1183     ResponseCode responseCode = get_key_for_name(keyStore, &keyBlob, keyName, uid, TYPE_KEY_PAIR);
1184     if (responseCode != NO_ERROR) {
1185         return responseCode;
1186     }
1187 
1188     uint8_t* signedData;
1189     size_t signedDataLength;
1190 
1191     const keymaster_device_t* device = keyStore->getDevice();
1192     if (device == NULL) {
1193         ALOGE("no keymaster device; cannot sign");
1194         return SYSTEM_ERROR;
1195     }
1196 
1197     if (device->sign_data == NULL) {
1198         ALOGE("device doesn't implement signing");
1199         return SYSTEM_ERROR;
1200     }
1201 
1202     keymaster_rsa_sign_params_t params;
1203     params.digest_type = DIGEST_NONE;
1204     params.padding_type = PADDING_NONE;
1205 
1206     rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1207             data->value, data->length, &signedData, &signedDataLength);
1208     if (rc) {
1209         ALOGW("device couldn't sign data");
1210         return SYSTEM_ERROR;
1211     }
1212 
1213     send_code(sock, NO_ERROR);
1214     send_message(sock, signedData, signedDataLength);
1215     return NO_ERROR_RESPONSE_CODE_SENT;
1216 }
1217 
verify(KeyStore * keyStore,int,uid_t uid,Value * keyName,Value * data,Value * signature)1218 static ResponseCode verify(KeyStore* keyStore, int, uid_t uid, Value* keyName, Value* data,
1219         Value* signature) {
1220     Blob keyBlob;
1221     int rc;
1222 
1223     ResponseCode responseCode = get_key_for_name(keyStore, &keyBlob, keyName, uid, TYPE_KEY_PAIR);
1224     if (responseCode != NO_ERROR) {
1225         return responseCode;
1226     }
1227 
1228     const keymaster_device_t* device = keyStore->getDevice();
1229     if (device == NULL) {
1230         return SYSTEM_ERROR;
1231     }
1232 
1233     if (device->verify_data == NULL) {
1234         return SYSTEM_ERROR;
1235     }
1236 
1237     keymaster_rsa_sign_params_t params;
1238     params.digest_type = DIGEST_NONE;
1239     params.padding_type = PADDING_NONE;
1240 
1241     rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1242             data->value, data->length, signature->value, signature->length);
1243     if (rc) {
1244         return SYSTEM_ERROR;
1245     } else {
1246         return NO_ERROR;
1247     }
1248 }
1249 
grant(KeyStore * keyStore,int,uid_t uid,Value * keyName,Value * granteeData,Value *)1250 static ResponseCode grant(KeyStore* keyStore, int, uid_t uid, Value* keyName,
1251         Value* granteeData, Value*) {
1252     char filename[NAME_MAX];
1253     encode_key_for_uid(filename, uid, keyName);
1254     if (access(filename, R_OK) == -1) {
1255         return (errno != ENOENT) ? SYSTEM_ERROR : KEY_NOT_FOUND;
1256     }
1257 
1258     keyStore->addGrant(filename, granteeData);
1259     return NO_ERROR;
1260 }
1261 
ungrant(KeyStore * keyStore,int,uid_t uid,Value * keyName,Value * granteeData,Value *)1262 static ResponseCode ungrant(KeyStore* keyStore, int, uid_t uid, Value* keyName,
1263         Value* granteeData, Value*) {
1264     char filename[NAME_MAX];
1265     encode_key_for_uid(filename, uid, keyName);
1266     if (access(filename, R_OK) == -1) {
1267         return (errno != ENOENT) ? SYSTEM_ERROR : KEY_NOT_FOUND;
1268     }
1269 
1270     return keyStore->removeGrant(keyName, granteeData) ? NO_ERROR : KEY_NOT_FOUND;
1271 }
1272 
1273 /* Here are the permissions, actions, users, and the main function. */
1274 enum perm {
1275     P_TEST     = 1 << TEST,
1276     P_GET      = 1 << GET,
1277     P_INSERT   = 1 << INSERT,
1278     P_DELETE   = 1 << DELETE,
1279     P_EXIST    = 1 << EXIST,
1280     P_SAW      = 1 << SAW,
1281     P_RESET    = 1 << RESET,
1282     P_PASSWORD = 1 << PASSWORD,
1283     P_LOCK     = 1 << LOCK,
1284     P_UNLOCK   = 1 << UNLOCK,
1285     P_ZERO     = 1 << ZERO,
1286     P_SIGN     = 1 << SIGN,
1287     P_VERIFY   = 1 << VERIFY,
1288     P_GRANT    = 1 << GRANT,
1289 };
1290 
1291 static const int MAX_PARAM = 3;
1292 
1293 static const State STATE_ANY = (State) 0;
1294 
1295 static struct action {
1296     ResponseCode (*run)(KeyStore* keyStore, int sock, uid_t uid, Value* param1, Value* param2,
1297             Value* param3);
1298     int8_t code;
1299     State state;
1300     uint32_t perm;
1301     int lengths[MAX_PARAM];
1302 } actions[] = {
1303     {test,       CommandCodes[TEST],       STATE_ANY,      P_TEST,     {0, 0, 0}},
1304     {get,        CommandCodes[GET],        STATE_NO_ERROR, P_GET,      {KEY_SIZE, 0, 0}},
1305     {insert,     CommandCodes[INSERT],     STATE_NO_ERROR, P_INSERT,   {KEY_SIZE, VALUE_SIZE, 0}},
1306     {del,        CommandCodes[DELETE],     STATE_ANY,      P_DELETE,   {KEY_SIZE, 0, 0}},
1307     {exist,      CommandCodes[EXIST],      STATE_ANY,      P_EXIST,    {KEY_SIZE, 0, 0}},
1308     {saw,        CommandCodes[SAW],        STATE_ANY,      P_SAW,      {KEY_SIZE, 0, 0}},
1309     {reset,      CommandCodes[RESET],      STATE_ANY,      P_RESET,    {0, 0, 0}},
1310     {password,   CommandCodes[PASSWORD],   STATE_ANY,      P_PASSWORD, {PASSWORD_SIZE, 0, 0}},
1311     {lock,       CommandCodes[LOCK],       STATE_NO_ERROR, P_LOCK,     {0, 0, 0}},
1312     {unlock,     CommandCodes[UNLOCK],     STATE_LOCKED,   P_UNLOCK,   {PASSWORD_SIZE, 0, 0}},
1313     {zero,       CommandCodes[ZERO],       STATE_ANY,      P_ZERO,     {0, 0, 0}},
1314     {generate,   CommandCodes[GENERATE],   STATE_NO_ERROR, P_INSERT,   {KEY_SIZE, 0, 0}},
1315     {import,     CommandCodes[IMPORT],     STATE_NO_ERROR, P_INSERT,   {KEY_SIZE, VALUE_SIZE, 0}},
1316     {sign,       CommandCodes[SIGN],       STATE_NO_ERROR, P_SIGN,     {KEY_SIZE, VALUE_SIZE, 0}},
1317     {verify,     CommandCodes[VERIFY],     STATE_NO_ERROR, P_VERIFY,   {KEY_SIZE, VALUE_SIZE, VALUE_SIZE}},
1318     {get_pubkey, CommandCodes[GET_PUBKEY], STATE_NO_ERROR, P_GET,      {KEY_SIZE, 0, 0}},
1319     {del_key,    CommandCodes[DEL_KEY],    STATE_ANY,      P_DELETE,   {KEY_SIZE, 0, 0}},
1320     {grant,      CommandCodes[GRANT],      STATE_NO_ERROR, P_GRANT,    {KEY_SIZE, KEY_SIZE, 0}},
1321     {ungrant,    CommandCodes[UNGRANT],    STATE_NO_ERROR, P_GRANT,    {KEY_SIZE, KEY_SIZE, 0}},
1322     {NULL,       0,                        STATE_ANY,      0,          {0, 0, 0}},
1323 };
1324 
1325 static struct user {
1326     uid_t uid;
1327     uid_t euid;
1328     uint32_t perms;
1329 } users[] = {
1330     {AID_SYSTEM,   ~0,         ~0},
1331     {AID_VPN,      AID_SYSTEM, P_GET | P_SIGN | P_VERIFY },
1332     {AID_WIFI,     AID_SYSTEM, P_GET | P_SIGN | P_VERIFY },
1333     {AID_ROOT,     AID_SYSTEM, P_GET},
1334     {~0,           ~0,         P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW |
1335                                P_SIGN | P_VERIFY},
1336 };
1337 
process(KeyStore * keyStore,int sock,uid_t uid,int8_t code)1338 static ResponseCode process(KeyStore* keyStore, int sock, uid_t uid, int8_t code) {
1339     struct user* user = users;
1340     struct action* action = actions;
1341     int i;
1342 
1343     while (~user->uid && user->uid != (uid % AID_USER)) {
1344         ++user;
1345     }
1346     while (action->code && action->code != code) {
1347         ++action;
1348     }
1349     if (!action->code) {
1350         return UNDEFINED_ACTION;
1351     }
1352     if (!(action->perm & user->perms)) {
1353         return PERMISSION_DENIED;
1354     }
1355     if (action->state != STATE_ANY && action->state != keyStore->getState()) {
1356         return (ResponseCode) keyStore->getState();
1357     }
1358     if (~user->euid) {
1359         uid = user->euid;
1360     }
1361     Value params[MAX_PARAM];
1362     for (i = 0; i < MAX_PARAM && action->lengths[i] != 0; ++i) {
1363         params[i].length = recv_message(sock, params[i].value, action->lengths[i]);
1364         if (params[i].length < 0) {
1365             return PROTOCOL_ERROR;
1366         }
1367     }
1368     if (!recv_end_of_file(sock)) {
1369         return PROTOCOL_ERROR;
1370     }
1371     return action->run(keyStore, sock, uid, &params[0], &params[1], &params[2]);
1372 }
1373 
main(int argc,char * argv[])1374 int main(int argc, char* argv[]) {
1375     int controlSocket = android_get_control_socket("keystore");
1376     if (argc < 2) {
1377         ALOGE("A directory must be specified!");
1378         return 1;
1379     }
1380     if (chdir(argv[1]) == -1) {
1381         ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1382         return 1;
1383     }
1384 
1385     Entropy entropy;
1386     if (!entropy.open()) {
1387         return 1;
1388     }
1389 
1390     keymaster_device_t* dev;
1391     if (keymaster_device_initialize(&dev)) {
1392         ALOGE("keystore keymaster could not be initialized; exiting");
1393         return 1;
1394     }
1395 
1396     if (listen(controlSocket, 3) == -1) {
1397         ALOGE("listen: %s", strerror(errno));
1398         return 1;
1399     }
1400 
1401     signal(SIGPIPE, SIG_IGN);
1402 
1403     KeyStore keyStore(&entropy, dev);
1404     int sock;
1405     while ((sock = accept(controlSocket, NULL, 0)) != -1) {
1406         struct timeval tv;
1407         tv.tv_sec = 3;
1408         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
1409         setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
1410 
1411         struct ucred cred;
1412         socklen_t size = sizeof(cred);
1413         int credResult = getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &cred, &size);
1414         if (credResult != 0) {
1415             ALOGW("getsockopt: %s", strerror(errno));
1416         } else {
1417             int8_t request;
1418             if (recv_code(sock, &request)) {
1419                 State old_state = keyStore.getState();
1420                 ResponseCode response = process(&keyStore, sock, cred.uid, request);
1421                 if (response == NO_ERROR_RESPONSE_CODE_SENT) {
1422                     response = NO_ERROR;
1423                 } else {
1424                     send_code(sock, response);
1425                 }
1426                 ALOGI("uid: %d action: %c -> %d state: %d -> %d retry: %d",
1427                      cred.uid,
1428                      request, response,
1429                      old_state, keyStore.getState(),
1430                      keyStore.getRetry());
1431             }
1432         }
1433         close(sock);
1434     }
1435     ALOGE("accept: %s", strerror(errno));
1436 
1437     keymaster_device_release(dev);
1438 
1439     return 1;
1440 }
1441