blob: 89d578e0da0eafd3d92eb169782a354db378ff1e [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
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
Kenny Root51878182012-03-13 12:53:19 -070083static int decode_key(uint8_t* out, const char* in, int length) {
Kenny Roota91203b2012-02-15 15:00:46 -080084 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 ALOGE("open: %s: %s", randomDevice, strerror(errno));
137 return false;
138 }
139 return true;
140 }
141
Kenny Root51878182012-03-13 12:53:19 -0700142 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800143 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
Kenny Root51878182012-03-13 12:53:19 -0700186 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800187 return mBlob.value;
188 }
189
Kenny Root51878182012-03-13 12:53:19 -0700190 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800191 return mBlob.length;
192 }
193
Kenny Root51878182012-03-13 12:53:19 -0700194 const uint8_t* getInfo() const {
195 return mBlob.value + mBlob.length;
196 }
197
198 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800199 return mBlob.info;
200 }
201
202 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
203 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
204 return SYSTEM_ERROR;
205 }
206
207 // data includes the value and the value's length
208 size_t dataLength = mBlob.length + sizeof(mBlob.length);
209 // pad data to the AES_BLOCK_SIZE
210 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
211 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
212 // encrypted data includes the digest value
213 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
214 // move info after space for padding
215 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
216 // zero padding area
217 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
218
219 mBlob.length = htonl(mBlob.length);
220 MD5(mBlob.digested, digestedLength, mBlob.digest);
221
222 uint8_t vector[AES_BLOCK_SIZE];
223 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
224 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
225 aes_key, vector, AES_ENCRYPT);
226
227 memset(mBlob.reserved, 0, sizeof(mBlob.reserved));
228 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
229 size_t fileLength = encryptedLength + headerLength + mBlob.info;
230
231 const char* tmpFileName = ".tmp";
232 int out = open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
233 if (out == -1) {
234 return SYSTEM_ERROR;
235 }
236 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
237 if (close(out) != 0) {
238 return SYSTEM_ERROR;
239 }
240 if (writtenBytes != fileLength) {
241 unlink(tmpFileName);
242 return SYSTEM_ERROR;
243 }
244 return (rename(tmpFileName, filename) == 0) ? NO_ERROR : SYSTEM_ERROR;
245 }
246
247 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
248 int in = open(filename, O_RDONLY);
249 if (in == -1) {
250 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
251 }
252 // fileLength may be less than sizeof(mBlob) since the in
253 // memory version has extra padding to tolerate rounding up to
254 // the AES_BLOCK_SIZE
255 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
256 if (close(in) != 0) {
257 return SYSTEM_ERROR;
258 }
259 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
260 if (fileLength < headerLength) {
261 return VALUE_CORRUPTED;
262 }
263
264 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
265 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
266 return VALUE_CORRUPTED;
267 }
268 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
269 mBlob.vector, AES_DECRYPT);
270 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
271 uint8_t computedDigest[MD5_DIGEST_LENGTH];
272 MD5(mBlob.digested, digestedLength, computedDigest);
273 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
274 return VALUE_CORRUPTED;
275 }
276
277 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
278 mBlob.length = ntohl(mBlob.length);
279 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
280 return VALUE_CORRUPTED;
281 }
282 if (mBlob.info != 0) {
283 // move info from after padding to after data
284 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
285 }
286 return NO_ERROR;
287 }
288
289private:
290 struct blob mBlob;
291};
292
293class KeyStore {
294public:
Kenny Root51878182012-03-13 12:53:19 -0700295 KeyStore(Entropy* entropy)
296 : mEntropy(entropy)
297 , mRetry(MAX_RETRY)
298 {
Kenny Roota91203b2012-02-15 15:00:46 -0800299 if (access(MASTER_KEY_FILE, R_OK) == 0) {
300 setState(STATE_LOCKED);
301 } else {
302 setState(STATE_UNINITIALIZED);
303 }
304 }
305
Kenny Root51878182012-03-13 12:53:19 -0700306 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800307 return mState;
308 }
309
Kenny Root51878182012-03-13 12:53:19 -0700310 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800311 return mRetry;
312 }
313
314 ResponseCode initialize(Value* pw) {
315 if (!generateMasterKey()) {
316 return SYSTEM_ERROR;
317 }
318 ResponseCode response = writeMasterKey(pw);
319 if (response != NO_ERROR) {
320 return response;
321 }
322 setupMasterKeys();
323 return NO_ERROR;
324 }
325
326 ResponseCode writeMasterKey(Value* pw) {
327 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
328 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
329 AES_KEY passwordAesKey;
330 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
331 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt));
332 return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
333 }
334
335 ResponseCode readMasterKey(Value* pw) {
336 int in = open(MASTER_KEY_FILE, O_RDONLY);
337 if (in == -1) {
338 return SYSTEM_ERROR;
339 }
340
341 // we read the raw blob to just to get the salt to generate
342 // the AES key, then we create the Blob to use with decryptBlob
343 blob rawBlob;
344 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
345 if (close(in) != 0) {
346 return SYSTEM_ERROR;
347 }
348 // find salt at EOF if present, otherwise we have an old file
349 uint8_t* salt;
350 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
351 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
352 } else {
353 salt = NULL;
354 }
355 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
356 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
357 AES_KEY passwordAesKey;
358 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
359 Blob masterKeyBlob(rawBlob);
360 ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
361 if (response == SYSTEM_ERROR) {
362 return SYSTEM_ERROR;
363 }
364 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
365 // if salt was missing, generate one and write a new master key file with the salt.
366 if (salt == NULL) {
367 if (!generateSalt()) {
368 return SYSTEM_ERROR;
369 }
370 response = writeMasterKey(pw);
371 }
372 if (response == NO_ERROR) {
373 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
374 setupMasterKeys();
375 }
376 return response;
377 }
378 if (mRetry <= 0) {
379 reset();
380 return UNINITIALIZED;
381 }
382 --mRetry;
383 switch (mRetry) {
384 case 0: return WRONG_PASSWORD_0;
385 case 1: return WRONG_PASSWORD_1;
386 case 2: return WRONG_PASSWORD_2;
387 case 3: return WRONG_PASSWORD_3;
388 default: return WRONG_PASSWORD_3;
389 }
390 }
391
392 bool reset() {
393 clearMasterKeys();
394 setState(STATE_UNINITIALIZED);
395
396 DIR* dir = opendir(".");
397 struct dirent* file;
398
399 if (!dir) {
400 return false;
401 }
402 while ((file = readdir(dir)) != NULL) {
403 unlink(file->d_name);
404 }
405 closedir(dir);
406 return true;
407 }
408
Kenny Root51878182012-03-13 12:53:19 -0700409 bool isEmpty() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800410 DIR* dir = opendir(".");
411 struct dirent* file;
412 if (!dir) {
413 return true;
414 }
415 bool result = true;
416 while ((file = readdir(dir)) != NULL) {
417 if (isKeyFile(file->d_name)) {
418 result = false;
419 break;
420 }
421 }
422 closedir(dir);
423 return result;
424 }
425
426 void lock() {
427 clearMasterKeys();
428 setState(STATE_LOCKED);
429 }
430
431 ResponseCode get(const char* filename, Blob* keyBlob) {
432 return keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
433 }
434
435 ResponseCode put(const char* filename, Blob* keyBlob) {
436 return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
437 }
438
439private:
440 static const char* MASTER_KEY_FILE;
441 static const int MASTER_KEY_SIZE_BYTES = 16;
442 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
443
444 static const int MAX_RETRY = 4;
445 static const size_t SALT_SIZE = 16;
446
447 Entropy* mEntropy;
448
449 State mState;
450 int8_t mRetry;
451
452 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
453 uint8_t mSalt[SALT_SIZE];
454
455 AES_KEY mMasterKeyEncryption;
456 AES_KEY mMasterKeyDecryption;
457
458 void setState(State state) {
459 mState = state;
460 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
461 mRetry = MAX_RETRY;
462 }
463 }
464
465 bool generateSalt() {
466 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
467 }
468
469 bool generateMasterKey() {
470 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
471 return false;
472 }
473 if (!generateSalt()) {
474 return false;
475 }
476 return true;
477 }
478
479 void setupMasterKeys() {
480 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
481 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
482 setState(STATE_NO_ERROR);
483 }
484
485 void clearMasterKeys() {
486 memset(mMasterKey, 0, sizeof(mMasterKey));
487 memset(mSalt, 0, sizeof(mSalt));
488 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
489 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
490 }
491
492 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, Value* pw, uint8_t* salt) {
493 size_t saltSize;
494 if (salt != NULL) {
495 saltSize = SALT_SIZE;
496 } else {
497 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
498 salt = (uint8_t*) "keystore";
499 // sizeof = 9, not strlen = 8
500 saltSize = sizeof("keystore");
501 }
502 PKCS5_PBKDF2_HMAC_SHA1((char*) pw->value, pw->length, salt, saltSize, 8192, keySize, key);
503 }
504
505 static bool isKeyFile(const char* filename) {
506 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
507 && (strcmp(filename, ".") != 0)
508 && (strcmp(filename, "..") != 0));
509 }
510};
511
512const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
513
514/* Here is the protocol used in both requests and responses:
515 * code [length_1 message_1 ... length_n message_n] end-of-file
516 * where code is one byte long and lengths are unsigned 16-bit integers in
517 * network order. Thus the maximum length of a message is 65535 bytes. */
518
519static int recv_code(int sock, int8_t* code) {
520 return recv(sock, code, 1, 0) == 1;
521}
522
523static int recv_message(int sock, uint8_t* message, int length) {
524 uint8_t bytes[2];
525 if (recv(sock, &bytes[0], 1, 0) != 1 ||
526 recv(sock, &bytes[1], 1, 0) != 1) {
527 return -1;
528 } else {
529 int offset = bytes[0] << 8 | bytes[1];
530 if (length < offset) {
531 return -1;
532 }
533 length = offset;
534 offset = 0;
535 while (offset < length) {
536 int n = recv(sock, &message[offset], length - offset, 0);
537 if (n <= 0) {
538 return -1;
539 }
540 offset += n;
541 }
542 }
543 return length;
544}
545
546static int recv_end_of_file(int sock) {
547 uint8_t byte;
548 return recv(sock, &byte, 1, 0) == 0;
549}
550
551static void send_code(int sock, int8_t code) {
552 send(sock, &code, 1, 0);
553}
554
Kenny Root51878182012-03-13 12:53:19 -0700555static void send_message(int sock, const uint8_t* message, int length) {
Kenny Roota91203b2012-02-15 15:00:46 -0800556 uint16_t bytes = htons(length);
557 send(sock, &bytes, 2, 0);
558 send(sock, message, length, 0);
559}
560
561/* Here are the actions. Each of them is a function without arguments. All
562 * information is defined in global variables, which are set properly before
563 * performing an action. The number of parameters required by each action is
564 * fixed and defined in a table. If the return value of an action is positive,
565 * it will be treated as a response code and transmitted to the client. Note
566 * that the lengths of parameters are checked when they are received, so
567 * boundary checks on parameters are omitted. */
568
569static const ResponseCode NO_ERROR_RESPONSE_CODE_SENT = (ResponseCode) 0;
570
Kenny Root51878182012-03-13 12:53:19 -0700571static ResponseCode test(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800572 return (ResponseCode) keyStore->getState();
573}
574
Kenny Root51878182012-03-13 12:53:19 -0700575static ResponseCode get(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800576 char filename[NAME_MAX];
577 encode_key(filename, uid, keyName);
578 Blob keyBlob;
579 ResponseCode responseCode = keyStore->get(filename, &keyBlob);
580 if (responseCode != NO_ERROR) {
581 return responseCode;
582 }
583 send_code(sock, NO_ERROR);
584 send_message(sock, keyBlob.getValue(), keyBlob.getLength());
585 return NO_ERROR_RESPONSE_CODE_SENT;
586}
587
Kenny Root51878182012-03-13 12:53:19 -0700588static ResponseCode insert(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value* val,
589 Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800590 char filename[NAME_MAX];
591 encode_key(filename, uid, keyName);
592 Blob keyBlob(val->value, val->length, NULL, 0);
593 return keyStore->put(filename, &keyBlob);
594}
595
Kenny Root51878182012-03-13 12:53:19 -0700596static ResponseCode del(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800597 char filename[NAME_MAX];
598 encode_key(filename, uid, keyName);
599 return (unlink(filename) && errno != ENOENT) ? SYSTEM_ERROR : NO_ERROR;
600}
601
Kenny Root51878182012-03-13 12:53:19 -0700602static ResponseCode exist(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800603 char filename[NAME_MAX];
604 encode_key(filename, uid, keyName);
605 if (access(filename, R_OK) == -1) {
606 return (errno != ENOENT) ? SYSTEM_ERROR : KEY_NOT_FOUND;
607 }
608 return NO_ERROR;
609}
610
Kenny Root51878182012-03-13 12:53:19 -0700611static ResponseCode saw(KeyStore* keyStore, int sock, uid_t uid, Value* keyPrefix, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800612 DIR* dir = opendir(".");
613 if (!dir) {
614 return SYSTEM_ERROR;
615 }
616 char filename[NAME_MAX];
617 int n = encode_key(filename, uid, keyPrefix);
618 send_code(sock, NO_ERROR);
619
620 struct dirent* file;
621 while ((file = readdir(dir)) != NULL) {
622 if (!strncmp(filename, file->d_name, n)) {
Kenny Root51878182012-03-13 12:53:19 -0700623 const char* p = &file->d_name[n];
Kenny Roota91203b2012-02-15 15:00:46 -0800624 keyPrefix->length = decode_key(keyPrefix->value, p, strlen(p));
625 send_message(sock, keyPrefix->value, keyPrefix->length);
626 }
627 }
628 closedir(dir);
629 return NO_ERROR_RESPONSE_CODE_SENT;
630}
631
Kenny Root51878182012-03-13 12:53:19 -0700632static ResponseCode reset(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800633 return keyStore->reset() ? NO_ERROR : SYSTEM_ERROR;
634}
635
636/* Here is the history. To improve the security, the parameters to generate the
637 * master key has been changed. To make a seamless transition, we update the
638 * file using the same password when the user unlock it for the first time. If
639 * any thing goes wrong during the transition, the new file will not overwrite
640 * the old one. This avoids permanent damages of the existing data. */
641
Kenny Root51878182012-03-13 12:53:19 -0700642static ResponseCode password(KeyStore* keyStore, int sock, uid_t uid, Value* pw, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800643 switch (keyStore->getState()) {
644 case STATE_UNINITIALIZED: {
645 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
646 return keyStore->initialize(pw);
647 }
648 case STATE_NO_ERROR: {
649 // rewrite master key with new password.
650 return keyStore->writeMasterKey(pw);
651 }
652 case STATE_LOCKED: {
653 // read master key, decrypt with password, initialize mMasterKey*.
654 return keyStore->readMasterKey(pw);
655 }
656 }
657 return SYSTEM_ERROR;
658}
659
Kenny Root51878182012-03-13 12:53:19 -0700660static ResponseCode lock(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800661 keyStore->lock();
662 return NO_ERROR;
663}
664
Kenny Root51878182012-03-13 12:53:19 -0700665static ResponseCode unlock(KeyStore* keyStore, int sock, uid_t uid, Value* pw, Value* unused,
666 Value* unused2) {
667 return password(keyStore, sock, uid, pw, unused, unused2);
Kenny Roota91203b2012-02-15 15:00:46 -0800668}
669
Kenny Root51878182012-03-13 12:53:19 -0700670static ResponseCode zero(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*, Value*) {
Kenny Roota91203b2012-02-15 15:00:46 -0800671 return keyStore->isEmpty() ? KEY_NOT_FOUND : NO_ERROR;
672}
673
674/* Here are the permissions, actions, users, and the main function. */
675
676enum perm {
Kenny Root51878182012-03-13 12:53:19 -0700677 P_TEST = 1 << TEST,
678 P_GET = 1 << GET,
679 P_INSERT = 1 << INSERT,
680 P_DELETE = 1 << DELETE,
681 P_EXIST = 1 << EXIST,
682 P_SAW = 1 << SAW,
683 P_RESET = 1 << RESET,
684 P_PASSWORD = 1 << PASSWORD,
685 P_LOCK = 1 << LOCK,
686 P_UNLOCK = 1 << UNLOCK,
687 P_ZERO = 1 << ZERO,
Kenny Roota91203b2012-02-15 15:00:46 -0800688};
689
Kenny Root51878182012-03-13 12:53:19 -0700690static const int MAX_PARAM = 3;
Kenny Roota91203b2012-02-15 15:00:46 -0800691
692static const State STATE_ANY = (State) 0;
693
694static struct action {
Kenny Root51878182012-03-13 12:53:19 -0700695 ResponseCode (*run)(KeyStore* keyStore, int sock, uid_t uid, Value* param1, Value* param2,
696 Value* param3);
Kenny Roota91203b2012-02-15 15:00:46 -0800697 int8_t code;
698 State state;
699 uint32_t perm;
700 int lengths[MAX_PARAM];
701} actions[] = {
Kenny Root51878182012-03-13 12:53:19 -0700702 {test, CommandCodes[TEST], STATE_ANY, P_TEST, {0, 0, 0}},
703 {get, CommandCodes[GET], STATE_NO_ERROR, P_GET, {KEY_SIZE, 0, 0}},
704 {insert, CommandCodes[INSERT], STATE_NO_ERROR, P_INSERT, {KEY_SIZE, VALUE_SIZE, 0}},
705 {del, CommandCodes[DELETE], STATE_ANY, P_DELETE, {KEY_SIZE, 0, 0}},
706 {exist, CommandCodes[EXIST], STATE_ANY, P_EXIST, {KEY_SIZE, 0, 0}},
707 {saw, CommandCodes[SAW], STATE_ANY, P_SAW, {KEY_SIZE, 0, 0}},
708 {reset, CommandCodes[RESET], STATE_ANY, P_RESET, {0, 0, 0}},
709 {password, CommandCodes[PASSWORD], STATE_ANY, P_PASSWORD, {PASSWORD_SIZE, 0, 0}},
710 {lock, CommandCodes[LOCK], STATE_NO_ERROR, P_LOCK, {0, 0, 0}},
711 {unlock, CommandCodes[UNLOCK], STATE_LOCKED, P_UNLOCK, {PASSWORD_SIZE, 0, 0}},
712 {zero, CommandCodes[ZERO], STATE_ANY, P_ZERO, {0, 0, 0}},
713 {NULL, 0, STATE_ANY, 0, {0, 0, 0}},
Kenny Roota91203b2012-02-15 15:00:46 -0800714};
715
716static struct user {
717 uid_t uid;
718 uid_t euid;
719 uint32_t perms;
720} users[] = {
721 {AID_SYSTEM, ~0, ~0},
Kenny Root51878182012-03-13 12:53:19 -0700722 {AID_VPN, AID_SYSTEM, P_GET},
723 {AID_WIFI, AID_SYSTEM, P_GET},
724 {AID_ROOT, AID_SYSTEM, P_GET},
725 {~0, ~0, P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW},
Kenny Roota91203b2012-02-15 15:00:46 -0800726};
727
728static ResponseCode process(KeyStore* keyStore, int sock, uid_t uid, int8_t code) {
729 struct user* user = users;
730 struct action* action = actions;
731 int i;
732
733 while (~user->uid && user->uid != uid) {
734 ++user;
735 }
736 while (action->code && action->code != code) {
737 ++action;
738 }
739 if (!action->code) {
740 return UNDEFINED_ACTION;
741 }
742 if (!(action->perm & user->perms)) {
743 return PERMISSION_DENIED;
744 }
745 if (action->state != STATE_ANY && action->state != keyStore->getState()) {
746 return (ResponseCode) keyStore->getState();
747 }
748 if (~user->euid) {
749 uid = user->euid;
750 }
751 Value params[MAX_PARAM];
752 for (i = 0; i < MAX_PARAM && action->lengths[i] != 0; ++i) {
753 params[i].length = recv_message(sock, params[i].value, action->lengths[i]);
754 if (params[i].length < 0) {
755 return PROTOCOL_ERROR;
756 }
757 }
758 if (!recv_end_of_file(sock)) {
759 return PROTOCOL_ERROR;
760 }
Kenny Root51878182012-03-13 12:53:19 -0700761 return action->run(keyStore, sock, uid, &params[0], &params[1], &params[2]);
Kenny Roota91203b2012-02-15 15:00:46 -0800762}
763
764int main(int argc, char* argv[]) {
765 int controlSocket = android_get_control_socket("keystore");
766 if (argc < 2) {
767 ALOGE("A directory must be specified!");
768 return 1;
769 }
770 if (chdir(argv[1]) == -1) {
771 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
772 return 1;
773 }
774
775 Entropy entropy;
776 if (!entropy.open()) {
777 return 1;
778 }
779 if (listen(controlSocket, 3) == -1) {
780 ALOGE("listen: %s", strerror(errno));
781 return 1;
782 }
783
784 signal(SIGPIPE, SIG_IGN);
785
786 KeyStore keyStore(&entropy);
787 int sock;
788 while ((sock = accept(controlSocket, NULL, 0)) != -1) {
789 struct timeval tv;
790 tv.tv_sec = 3;
791 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
792 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
793
794 struct ucred cred;
795 socklen_t size = sizeof(cred);
796 int credResult = getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &cred, &size);
797 if (credResult != 0) {
798 ALOGW("getsockopt: %s", strerror(errno));
799 } else {
800 int8_t request;
801 if (recv_code(sock, &request)) {
802 State old_state = keyStore.getState();
803 ResponseCode response = process(&keyStore, sock, cred.uid, request);
804 if (response == NO_ERROR_RESPONSE_CODE_SENT) {
805 response = NO_ERROR;
806 } else {
807 send_code(sock, response);
808 }
809 ALOGI("uid: %d action: %c -> %d state: %d -> %d retry: %d",
810 cred.uid,
811 request, response,
812 old_state, keyStore.getState(),
813 keyStore.getRetry());
814 }
815 }
816 close(sock);
817 }
818 ALOGE("accept: %s", strerror(errno));
819 return 1;
820}