blob: 31db9fdc1c8f7a980c66d7c7948368da826393be [file] [log] [blame]
Brian Carlstrom01373772011-05-31 01:00:15 -07001/*
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 <sys/types.h>
27#include <sys/socket.h>
28#include <sys/stat.h>
29#include <sys/time.h>
30#include <arpa/inet.h>
31
32#include <openssl/aes.h>
33#include <openssl/evp.h>
34#include <openssl/md5.h>
35
36#define LOG_TAG "keystore"
37#include <cutils/log.h>
38#include <cutils/sockets.h>
39#include <private/android_filesystem_config.h>
40
41#include "keystore.h"
42
43/* KeyStore is a secured storage for key-value pairs. In this implementation,
44 * each file stores one key-value pair. Keys are encoded in file names, and
45 * values are encrypted with checksums. The encryption key is protected by a
46 * user-defined password. To keep things simple, buffers are always larger than
47 * the maximum space we needed, so boundary checks on buffers are omitted. */
48
49#define KEY_SIZE ((NAME_MAX - 15) / 2)
50#define VALUE_SIZE 32768
51#define PASSWORD_SIZE VALUE_SIZE
52
53struct Value {
54 int length;
55 uint8_t value[VALUE_SIZE];
56};
57
58/* Here is the encoding of keys. This is necessary in order to allow arbitrary
59 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
60 * into two bytes. The first byte is one of [+-.] which represents the first
61 * two bits of the character. The second byte encodes the rest of the bits into
62 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
63 * that Base64 cannot be used here due to the need of prefix match on keys. */
64
65static int encode_key(char* out, uid_t uid, const Value* key) {
66 int n = snprintf(out, NAME_MAX, "%u_", uid);
67 out += n;
68 const uint8_t* in = key->value;
69 int length = key->length;
70 for (int i = length; i > 0; --i, ++in, ++out) {
71 if (*in >= '0' && *in <= '~') {
72 *out = *in;
73 } else {
74 *out = '+' + (*in >> 6);
75 *++out = '0' + (*in & 0x3F);
76 ++length;
77 }
78 }
79 *out = '\0';
80 return n + length;
81}
82
83static int decode_key(uint8_t* out, char* in, int length) {
84 for (int i = 0; i < length; ++i, ++in, ++out) {
85 if (*in >= '0' && *in <= '~') {
86 *out = *in;
87 } else {
88 *out = (*in - '+') << 6;
89 *out |= (*++in - '0') & 0x3F;
90 --length;
91 }
92 }
93 *out = '\0';
94 return length;
95}
96
97static size_t readFully(int fd, uint8_t* data, size_t size) {
98 size_t remaining = size;
99 while (remaining > 0) {
100 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, size));
101 if (n == -1 || n == 0) {
102 return size-remaining;
103 }
104 data += n;
105 remaining -= n;
106 }
107 return size;
108}
109
110static size_t writeFully(int fd, uint8_t* data, size_t size) {
111 size_t remaining = size;
112 while (remaining > 0) {
113 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, size));
114 if (n == -1 || n == 0) {
115 return size-remaining;
116 }
117 data += n;
118 remaining -= n;
119 }
120 return size;
121}
122
123class Entropy {
124public:
125 Entropy() : mRandom(-1) {}
126 ~Entropy() {
127 if (mRandom != -1) {
128 close(mRandom);
129 }
130 }
131
132 bool open() {
133 const char* randomDevice = "/dev/urandom";
134 mRandom = ::open(randomDevice, O_RDONLY);
135 if (mRandom == -1) {
136 LOGE("open: %s: %s", randomDevice, strerror(errno));
137 return false;
138 }
139 return true;
140 }
141
142 bool generate_random_data(uint8_t* data, size_t size) {
143 return (readFully(mRandom, data, size) == size);
144 }
145
146private:
147 int mRandom;
148};
149
150/* Here is the file format. There are two parts in blob.value, the secret and
151 * the description. The secret is stored in ciphertext, and its original size
152 * can be found in blob.length. The description is stored after the secret in
153 * plaintext, and its size is specified in blob.info. The total size of the two
154 * parts must be no more than VALUE_SIZE bytes. The first three bytes of the
155 * file are reserved for future use and are always set to zero. Fields other
156 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
157 * and decryptBlob(). Thus they should not be accessed from outside. */
158
159struct __attribute__((packed)) blob {
160 uint8_t reserved[3];
161 uint8_t info;
162 uint8_t vector[AES_BLOCK_SIZE];
163 uint8_t encrypted[0];
164 uint8_t digest[MD5_DIGEST_LENGTH];
165 uint8_t digested[0];
166 int32_t length; // in network byte order when encrypted
167 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
168};
169
170class Blob {
171public:
172 Blob(uint8_t* value, int32_t valueLength, uint8_t* info, uint8_t infoLength) {
173 mBlob.length = valueLength;
174 memcpy(mBlob.value, value, valueLength);
175
176 mBlob.info = infoLength;
177 memcpy(mBlob.value + valueLength, info, infoLength);
178 }
179
180 Blob(blob b) {
181 mBlob = b;
182 }
183
184 Blob() {}
185
186 uint8_t* getValue() {
187 return mBlob.value;
188 }
189
190 int32_t getLength() {
191 return mBlob.length;
192 }
193
194 uint8_t getInfo() {
195 return mBlob.info;
196 }
197
198 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
199 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
200 return SYSTEM_ERROR;
201 }
202
203 // data includes the value and the value's length
204 size_t dataLength = mBlob.length + sizeof(mBlob.length);
205 // pad data to the AES_BLOCK_SIZE
206 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
207 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
208 // encrypted data includes the digest value
209 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
210 // move info after space for padding
211 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
212 // zero padding area
213 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
214
215 mBlob.length = htonl(mBlob.length);
216 MD5(mBlob.digested, digestedLength, mBlob.digest);
217
218 uint8_t vector[AES_BLOCK_SIZE];
219 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
220 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
221 aes_key, vector, AES_ENCRYPT);
222
223 memset(mBlob.reserved, 0, sizeof(mBlob.reserved));
224 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
225 size_t fileLength = encryptedLength + headerLength + mBlob.info;
226
227 const char* tmpFileName = ".tmp";
228 int out = open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
229 if (out == -1) {
230 return SYSTEM_ERROR;
231 }
232 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
233 if (close(out) != 0) {
234 return SYSTEM_ERROR;
235 }
236 if (writtenBytes != fileLength) {
237 unlink(tmpFileName);
238 return SYSTEM_ERROR;
239 }
240 return (rename(tmpFileName, filename) == 0) ? NO_ERROR : SYSTEM_ERROR;
241 }
242
243 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
244 int in = open(filename, O_RDONLY);
245 if (in == -1) {
246 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
247 }
248 // fileLength may be less than sizeof(mBlob) since the in
249 // memory version has extra padding to tolerate rounding up to
250 // the AES_BLOCK_SIZE
251 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
252 if (close(in) != 0) {
253 return SYSTEM_ERROR;
254 }
255 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
256 if (fileLength < headerLength) {
257 return VALUE_CORRUPTED;
258 }
259
260 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
261 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
262 return VALUE_CORRUPTED;
263 }
264 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
265 mBlob.vector, AES_DECRYPT);
266 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
267 uint8_t computedDigest[MD5_DIGEST_LENGTH];
268 MD5(mBlob.digested, digestedLength, computedDigest);
269 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
270 return VALUE_CORRUPTED;
271 }
272
273 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
274 mBlob.length = ntohl(mBlob.length);
275 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
276 return VALUE_CORRUPTED;
277 }
278 if (mBlob.info != 0) {
279 // move info from after padding to after data
280 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
281 }
282 return NO_ERROR;
283 }
284
285private:
286 struct blob mBlob;
287};
288
289class KeyStore {
290public:
291 KeyStore(Entropy* entropy) : mEntropy(entropy), mRetry(MAX_RETRY) {
292 if (access(MASTER_KEY_FILE, R_OK) == 0) {
293 setState(STATE_LOCKED);
294 } else {
295 setState(STATE_UNINITIALIZED);
296 }
297 }
298
299 State getState() {
300 return mState;
301 }
302
303 int8_t getRetry() {
304 return mRetry;
305 }
306
307 ResponseCode initialize(Value* pw) {
308 if (!generateMasterKey()) {
309 return SYSTEM_ERROR;
310 }
311 ResponseCode response = writeMasterKey(pw);
312 if (response != NO_ERROR) {
313 return response;
314 }
315 setupMasterKeys();
316 return NO_ERROR;
317 }
318
319 ResponseCode writeMasterKey(Value* pw) {
320 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
321 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
322 AES_KEY passwordAesKey;
323 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
324 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt));
325 return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
326 }
327
328 ResponseCode readMasterKey(Value* pw) {
329 int in = open(MASTER_KEY_FILE, O_RDONLY);
330 if (in == -1) {
331 return SYSTEM_ERROR;
332 }
333
334 // we read the raw blob to just to get the salt to generate
335 // the AES key, then we create the Blob to use with decryptBlob
336 blob rawBlob;
337 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
338 if (close(in) != 0) {
339 return SYSTEM_ERROR;
340 }
341 // find salt at EOF if present, otherwise we have an old file
342 uint8_t* salt;
343 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
344 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
345 } else {
346 salt = NULL;
347 }
348 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
349 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
350 AES_KEY passwordAesKey;
351 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
352 Blob masterKeyBlob(rawBlob);
353 ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
354 if (response == SYSTEM_ERROR) {
355 return SYSTEM_ERROR;
356 }
357 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
358 // if salt was missing, generate one and write a new master key file with the salt.
359 if (salt == NULL) {
360 if (!generateSalt()) {
361 return SYSTEM_ERROR;
362 }
363 response = writeMasterKey(pw);
364 }
365 if (response == NO_ERROR) {
366 setupMasterKeys();
367 }
368 return response;
369 }
370 if (mRetry <= 0) {
371 reset();
372 return UNINITIALIZED;
373 }
374 --mRetry;
375 switch (mRetry) {
376 case 0: return WRONG_PASSWORD_0;
377 case 1: return WRONG_PASSWORD_1;
378 case 2: return WRONG_PASSWORD_2;
379 case 3: return WRONG_PASSWORD_3;
380 default: return WRONG_PASSWORD_3;
381 }
382 }
383
384 bool reset() {
385 clearMasterKeys();
386 setState(STATE_UNINITIALIZED);
387
388 DIR* dir = opendir(".");
389 struct dirent* file;
390
391 if (!dir) {
392 return false;
393 }
394 while ((file = readdir(dir)) != NULL) {
395 if (isKeyFile(file->d_name)) {
396 unlink(file->d_name);
397 }
398 }
399 closedir(dir);
400 return true;
401 }
402
403 bool isEmpty() {
404 DIR* dir = opendir(".");
405 struct dirent* file;
406 if (!dir) {
407 return true;
408 }
409 bool result = true;
410 while ((file = readdir(dir)) != NULL) {
411 if (isKeyFile(file->d_name)) {
412 result = false;
413 break;
414 }
415 }
416 closedir(dir);
417 return result;
418 }
419
420 void lock() {
421 clearMasterKeys();
422 setState(STATE_LOCKED);
423 }
424
425 ResponseCode get(const char* filename, Blob* keyBlob) {
426 return keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
427 }
428
429 ResponseCode put(const char* filename, Blob* keyBlob) {
430 return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
431 }
432
433private:
434 static const char* MASTER_KEY_FILE;
435 static const int MASTER_KEY_SIZE_BYTES = 16;
436 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
437
438 static const int MAX_RETRY = 4;
439 static const size_t SALT_SIZE = 16;
440
441 Entropy* mEntropy;
442
443 State mState;
444 int8_t mRetry;
445
446 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
447 uint8_t mSalt[SALT_SIZE];
448
449 AES_KEY mMasterKeyEncryption;
450 AES_KEY mMasterKeyDecryption;
451
452 void setState(State state) {
453 mState = state;
454 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
455 mRetry = MAX_RETRY;
456 }
457 }
458
459 bool generateSalt() {
460 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
461 }
462
463 bool generateMasterKey() {
464 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
465 return false;
466 }
467 if (!generateSalt()) {
468 return false;
469 }
470 return true;
471 }
472
473 void setupMasterKeys() {
474 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
475 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
476 setState(STATE_NO_ERROR);
477 }
478
479 void clearMasterKeys() {
480 memset(mMasterKey, 0, sizeof(mMasterKey));
481 memset(mSalt, 0, sizeof(mSalt));
482 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
483 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
484 }
485
486 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, Value* pw, uint8_t* salt) {
487 size_t saltSize;
488 if (salt != NULL) {
489 saltSize = SALT_SIZE;
490 } else {
491 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
492 salt = (uint8_t*) "keystore";
493 // sizeof = 9, not strlen = 8
494 saltSize = sizeof("keystore");
495 }
496 PKCS5_PBKDF2_HMAC_SHA1((char*) pw->value, pw->length, salt, saltSize, 8192, keySize, key);
497 }
498
499 static bool isKeyFile(const char* filename) {
500 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
501 && (strcmp(filename, ".") != 0)
502 && (strcmp(filename, "..") != 0));
503 }
504};
505
506const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
507
508/* Here is the protocol used in both requests and responses:
509 * code [length_1 message_1 ... length_n message_n] end-of-file
510 * where code is one byte long and lengths are unsigned 16-bit integers in
511 * network order. Thus the maximum length of a message is 65535 bytes. */
512
513static int recv_code(int sock, int8_t* code) {
514 return recv(sock, code, 1, 0) == 1;
515}
516
517static int recv_message(int sock, uint8_t* message, int length) {
518 uint8_t bytes[2];
519 if (recv(sock, &bytes[0], 1, 0) != 1 ||
520 recv(sock, &bytes[1], 1, 0) != 1) {
521 return -1;
522 } else {
523 int offset = bytes[0] << 8 | bytes[1];
524 if (length < offset) {
525 return -1;
526 }
527 length = offset;
528 offset = 0;
529 while (offset < length) {
530 int n = recv(sock, &message[offset], length - offset, 0);
531 if (n <= 0) {
532 return -1;
533 }
534 offset += n;
535 }
536 }
537 return length;
538}
539
540static int recv_end_of_file(int sock) {
541 uint8_t byte;
542 return recv(sock, &byte, 1, 0) == 0;
543}
544
545static void send_code(int sock, int8_t code) {
546 send(sock, &code, 1, 0);
547}
548
549static void send_message(int sock, uint8_t* message, int length) {
550 uint16_t bytes = htons(length);
551 send(sock, &bytes, 2, 0);
552 send(sock, message, length, 0);
553}
554
555/* Here are the actions. Each of them is a function without arguments. All
556 * information is defined in global variables, which are set properly before
557 * performing an action. The number of parameters required by each action is
558 * fixed and defined in a table. If the return value of an action is positive,
559 * it will be treated as a response code and transmitted to the client. Note
560 * that the lengths of parameters are checked when they are received, so
561 * boundary checks on parameters are omitted. */
562
563static const ResponseCode NO_ERROR_RESPONSE_CODE_SENT = (ResponseCode) 0;
564
565static ResponseCode test(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*) {
566 return (ResponseCode) keyStore->getState();
567}
568
569static ResponseCode get(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*) {
570 char filename[NAME_MAX];
571 encode_key(filename, uid, keyName);
572 Blob keyBlob;
573 ResponseCode responseCode = keyStore->get(filename, &keyBlob);
574 if (responseCode != NO_ERROR) {
575 return responseCode;
576 }
577 send_code(sock, NO_ERROR);
578 send_message(sock, keyBlob.getValue(), keyBlob.getLength());
579 return NO_ERROR_RESPONSE_CODE_SENT;
580}
581
582static ResponseCode insert(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value* val) {
583 char filename[NAME_MAX];
584 encode_key(filename, uid, keyName);
585 Blob keyBlob(val->value, val->length, 0, NULL);
586 return keyStore->put(filename, &keyBlob);
587}
588
589static ResponseCode del(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*) {
590 char filename[NAME_MAX];
591 encode_key(filename, uid, keyName);
592 return (unlink(filename) && errno != ENOENT) ? SYSTEM_ERROR : NO_ERROR;
593}
594
595static ResponseCode exist(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*) {
596 char filename[NAME_MAX];
597 encode_key(filename, uid, keyName);
598 if (access(filename, R_OK) == -1) {
599 return (errno != ENOENT) ? SYSTEM_ERROR : KEY_NOT_FOUND;
600 }
601 return NO_ERROR;
602}
603
604static ResponseCode saw(KeyStore* keyStore, int sock, uid_t uid, Value* keyPrefix, Value*) {
605 DIR* dir = opendir(".");
606 if (!dir) {
607 return SYSTEM_ERROR;
608 }
609 char filename[NAME_MAX];
610 int n = encode_key(filename, uid, keyPrefix);
611 send_code(sock, NO_ERROR);
612
613 struct dirent* file;
614 while ((file = readdir(dir)) != NULL) {
615 if (!strncmp(filename, file->d_name, n)) {
616 char* p = &file->d_name[n];
617 keyPrefix->length = decode_key(keyPrefix->value, p, strlen(p));
618 send_message(sock, keyPrefix->value, keyPrefix->length);
619 }
620 }
621 closedir(dir);
622 return NO_ERROR_RESPONSE_CODE_SENT;
623}
624
625static ResponseCode reset(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*) {
626 return keyStore->reset() ? NO_ERROR : SYSTEM_ERROR;
627}
628
629/* Here is the history. To improve the security, the parameters to generate the
630 * master key has been changed. To make a seamless transition, we update the
631 * file using the same password when the user unlock it for the first time. If
632 * any thing goes wrong during the transition, the new file will not overwrite
633 * the old one. This avoids permanent damages of the existing data. */
634
635static ResponseCode password(KeyStore* keyStore, int sock, uid_t uid, Value* pw, Value*) {
636 switch (keyStore->getState()) {
637 case STATE_UNINITIALIZED: {
638 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
639 return keyStore->initialize(pw);
640 }
641 case STATE_NO_ERROR: {
642 // rewrite master key with new password.
643 return keyStore->writeMasterKey(pw);
644 }
645 case STATE_LOCKED: {
646 // read master key, decrypt with password, initialize mMasterKey*.
647 return keyStore->readMasterKey(pw);
648 }
649 }
650 return SYSTEM_ERROR;
651}
652
653static ResponseCode lock(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*) {
654 keyStore->lock();
655 return NO_ERROR;
656}
657
658static ResponseCode unlock(KeyStore* keyStore, int sock, uid_t uid, Value* pw, Value* unused) {
659 return password(keyStore, sock, uid, pw, unused);
660}
661
662static ResponseCode zero(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*) {
663 return keyStore->isEmpty() ? KEY_NOT_FOUND : NO_ERROR;
664}
665
666/* Here are the permissions, actions, users, and the main function. */
667
668enum perm {
669 TEST = 1,
670 GET = 2,
671 INSERT = 4,
672 DELETE = 8,
673 EXIST = 16,
674 SAW = 32,
675 RESET = 64,
676 PASSWORD = 128,
677 LOCK = 256,
678 UNLOCK = 512,
679 ZERO = 1024,
680};
681
682static const int MAX_PARAM = 2;
683
684static const State STATE_ANY = (State) 0;
685
686static struct action {
687 ResponseCode (*run)(KeyStore* keyStore, int sock, uid_t uid, Value* param1, Value* param2);
688 int8_t code;
689 State state;
690 uint32_t perm;
691 int lengths[MAX_PARAM];
692} actions[] = {
693 {test, 't', STATE_ANY, TEST, {0, 0}},
694 {get, 'g', STATE_NO_ERROR, GET, {KEY_SIZE, 0}},
695 {insert, 'i', STATE_NO_ERROR, INSERT, {KEY_SIZE, VALUE_SIZE}},
696 {del, 'd', STATE_ANY, DELETE, {KEY_SIZE, 0}},
697 {exist, 'e', STATE_ANY, EXIST, {KEY_SIZE, 0}},
698 {saw, 's', STATE_ANY, SAW, {KEY_SIZE, 0}},
699 {reset, 'r', STATE_ANY, RESET, {0, 0}},
700 {password, 'p', STATE_ANY, PASSWORD, {PASSWORD_SIZE, 0}},
701 {lock, 'l', STATE_NO_ERROR, LOCK, {0, 0}},
702 {unlock, 'u', STATE_LOCKED, UNLOCK, {PASSWORD_SIZE, 0}},
703 {zero, 'z', STATE_ANY, ZERO, {0, 0}},
704 {NULL, 0 , STATE_ANY, 0, {0, 0}},
705};
706
707static struct user {
708 uid_t uid;
709 uid_t euid;
710 uint32_t perms;
711} users[] = {
712 {AID_SYSTEM, ~0, ~GET},
713 {AID_VPN, AID_SYSTEM, GET},
714 {AID_WIFI, AID_SYSTEM, GET},
715 {AID_ROOT, AID_SYSTEM, GET},
716 {AID_KEYCHAIN, AID_SYSTEM, TEST | GET | SAW},
717 {~0, ~0, TEST | GET | INSERT | DELETE | EXIST | SAW},
718};
719
720static ResponseCode process(KeyStore* keyStore, int sock, uid_t uid, int8_t code) {
721 struct user* user = users;
722 struct action* action = actions;
723 int i;
724
725 while (~user->uid && user->uid != uid) {
726 ++user;
727 }
728 while (action->code && action->code != code) {
729 ++action;
730 }
731 if (!action->code) {
732 return UNDEFINED_ACTION;
733 }
734 if (!(action->perm & user->perms)) {
735 return PERMISSION_DENIED;
736 }
737 if (action->state != STATE_ANY && action->state != keyStore->getState()) {
738 return (ResponseCode) keyStore->getState();
739 }
740 if (~user->euid) {
741 uid = user->euid;
742 }
743 Value params[MAX_PARAM];
744 for (i = 0; i < MAX_PARAM && action->lengths[i] != 0; ++i) {
745 params[i].length = recv_message(sock, params[i].value, action->lengths[i]);
746 if (params[i].length < 0) {
747 return PROTOCOL_ERROR;
748 }
749 }
750 if (!recv_end_of_file(sock)) {
751 return PROTOCOL_ERROR;
752 }
753 return action->run(keyStore, sock, uid, &params[0], &params[1]);
754}
755
756int main(int argc, char* argv[]) {
757 int controlSocket = android_get_control_socket("keystore");
758 if (argc < 2) {
759 LOGE("A directory must be specified!");
760 return 1;
761 }
762 if (chdir(argv[1]) == -1) {
763 LOGE("chdir: %s: %s", argv[1], strerror(errno));
764 return 1;
765 }
766
767 Entropy entropy;
768 if (!entropy.open()) {
769 return 1;
770 }
771 if (listen(controlSocket, 3) == -1) {
772 LOGE("listen: %s", strerror(errno));
773 return 1;
774 }
775
776 signal(SIGPIPE, SIG_IGN);
777
778 KeyStore keyStore(&entropy);
779 int sock;
780 while ((sock = accept(controlSocket, NULL, 0)) != -1) {
781 struct timeval tv;
782 tv.tv_sec = 3;
783 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
784 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
785
786 struct ucred cred;
787 socklen_t size = sizeof(cred);
788 int credResult = getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &cred, &size);
789 if (credResult != 0) {
790 LOGW("getsockopt: %s", strerror(errno));
791 } else {
792 int8_t request;
793 if (recv_code(sock, &request)) {
794 State old_state = keyStore.getState();
795 ResponseCode response = process(&keyStore, sock, cred.uid, request);
796 if (response == NO_ERROR_RESPONSE_CODE_SENT) {
797 response = NO_ERROR;
798 } else {
799 send_code(sock, response);
800 }
801 LOGI("uid: %d action: %c -> %d state: %d -> %d retry: %d",
802 cred.uid,
803 request, response,
804 old_state, keyStore.getState(),
805 keyStore.getRetry());
806 }
807 }
808 close(sock);
809 }
810 LOGE("accept: %s", strerror(errno));
811 return 1;
812}