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 <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 53 /* Here is the encoding of keys. This is necessary in order to allow arbitrary 54 * characters in keys. Characters in [0-~] are not encoded. Others are encoded 55 * into two bytes. The first byte is one of [+-.] which represents the first 56 * two bits of the character. The second byte encodes the rest of the bits into 57 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note 58 * that Base64 cannot be used here due to the need of prefix match on keys. */ 59 60 static int encode_key(char *out, uint8_t *in, int length) 61 { 62 int i; 63 for (i = length; i > 0; --i, ++in, ++out) { 64 if (*in >= '0' && *in <= '~') { 65 *out = *in; 66 } else { 67 *out = '+' + (*in >> 6); 68 *++out = '0' + (*in & 0x3F); 69 ++length; 70 } 71 } 72 *out = 0; 73 return length; 74 } 75 76 static int decode_key(uint8_t *out, char *in, int length) 77 { 78 int i; 79 for (i = 0; i < length; ++i, ++in, ++out) { 80 if (*in >= '0' && *in <= '~') { 81 *out = *in; 82 } else { 83 *out = (*in - '+') << 6; 84 *out |= (*++in - '0') & 0x3F; 85 --length; 86 } 87 } 88 *out = 0; 89 return length; 90 } 91 92 /* Here is the protocol used in both requests and responses: 93 * code [length_1 message_1 ... length_n message_n] end-of-file 94 * where code is one byte long and lengths are unsigned 16-bit integers in 95 * network order. Thus the maximum length of a message is 65535 bytes. */ 96 97 static int the_socket = -1; 98 99 static int recv_code(int8_t *code) 100 { 101 return recv(the_socket, code, 1, 0) == 1; 102 } 103 104 static int recv_message(uint8_t *message, int length) 105 { 106 uint8_t bytes[2]; 107 if (recv(the_socket, &bytes[0], 1, 0) != 1 || 108 recv(the_socket, &bytes[1], 1, 0) != 1) { 109 return -1; 110 } else { 111 int offset = bytes[0] << 8 | bytes[1]; 112 if (length < offset) { 113 return -1; 114 } 115 length = offset; 116 offset = 0; 117 while (offset < length) { 118 int n = recv(the_socket, &message[offset], length - offset, 0); 119 if (n <= 0) { 120 return -1; 121 } 122 offset += n; 123 } 124 } 125 return length; 126 } 127 128 static int recv_end_of_file() 129 { 130 uint8_t byte; 131 return recv(the_socket, &byte, 1, 0) == 0; 132 } 133 134 static void send_code(int8_t code) 135 { 136 send(the_socket, &code, 1, 0); 137 } 138 139 static void send_message(uint8_t *message, int length) 140 { 141 uint16_t bytes = htons(length); 142 send(the_socket, &bytes, 2, 0); 143 send(the_socket, message, length, 0); 144 } 145 146 /* Here is the file format. There are two parts in blob.value, the secret and 147 * the description. The secret is stored in ciphertext, and its original size 148 * can be found in blob.length. The description is stored after the secret in 149 * plaintext, and its size is specified in blob.info. The total size of the two 150 * parts must be no more than VALUE_SIZE bytes. The first three bytes of the 151 * file are reserved for future use and are always set to zero. Fields other 152 * than blob.info, blob.length, and blob.value are modified by encrypt_blob() 153 * and decrypt_blob(). Thus they should not be accessed from outside. */ 154 155 static int the_entropy = -1; 156 157 static struct __attribute__((packed)) { 158 uint8_t reserved[3]; 159 uint8_t info; 160 uint8_t vector[AES_BLOCK_SIZE]; 161 uint8_t encrypted[0]; 162 uint8_t digest[MD5_DIGEST_LENGTH]; 163 uint8_t digested[0]; 164 int32_t length; 165 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE]; 166 } blob; 167 168 static int8_t encrypt_blob(char *name, AES_KEY *aes_key) 169 { 170 uint8_t vector[AES_BLOCK_SIZE]; 171 int length; 172 int fd; 173 174 if (read(the_entropy, blob.vector, AES_BLOCK_SIZE) != AES_BLOCK_SIZE) { 175 return SYSTEM_ERROR; 176 } 177 178 length = blob.length + (blob.value - blob.encrypted); 179 length = (length + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE * AES_BLOCK_SIZE; 180 181 if (blob.info != 0) { 182 memmove(&blob.encrypted[length], &blob.value[blob.length], blob.info); 183 } 184 185 blob.length = htonl(blob.length); 186 MD5(blob.digested, length - (blob.digested - blob.encrypted), blob.digest); 187 188 memcpy(vector, blob.vector, AES_BLOCK_SIZE); 189 AES_cbc_encrypt(blob.encrypted, blob.encrypted, length, aes_key, vector, 190 AES_ENCRYPT); 191 192 memset(blob.reserved, 0, sizeof(blob.reserved)); 193 length += (blob.encrypted - (uint8_t *)&blob) + blob.info; 194 195 fd = open(".tmp", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR); 196 length -= write(fd, &blob, length); 197 close(fd); 198 return (length || rename(".tmp", name)) ? SYSTEM_ERROR : NO_ERROR; 199 } 200 201 static int8_t decrypt_blob(char *name, AES_KEY *aes_key) 202 { 203 int fd = open(name, O_RDONLY); 204 int length; 205 206 if (fd == -1) { 207 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR; 208 } 209 length = read(fd, &blob, sizeof(blob)); 210 close(fd); 211 212 length -= (blob.encrypted - (uint8_t *)&blob) + blob.info; 213 if (length < blob.value - blob.encrypted || length % AES_BLOCK_SIZE != 0) { 214 return VALUE_CORRUPTED; 215 } 216 217 AES_cbc_encrypt(blob.encrypted, blob.encrypted, length, aes_key, 218 blob.vector, AES_DECRYPT); 219 length -= blob.digested - blob.encrypted; 220 if (memcmp(blob.digest, MD5(blob.digested, length, NULL), 221 MD5_DIGEST_LENGTH)) { 222 return VALUE_CORRUPTED; 223 } 224 225 length -= blob.value - blob.digested; 226 blob.length = ntohl(blob.length); 227 if (blob.length < 0 || blob.length > length) { 228 return VALUE_CORRUPTED; 229 } 230 if (blob.info != 0) { 231 memmove(&blob.value[blob.length], &blob.value[length], blob.info); 232 } 233 return NO_ERROR; 234 } 235 236 /* Here are the actions. Each of them is a function without arguments. All 237 * information is defined in global variables, which are set properly before 238 * performing an action. The number of parameters required by each action is 239 * fixed and defined in a table. If the return value of an action is positive, 240 * it will be treated as a response code and transmitted to the client. Note 241 * that the lengths of parameters are checked when they are received, so 242 * boundary checks on parameters are omitted. */ 243 244 #define MAX_PARAM 2 245 #define MAX_RETRY 4 246 247 static uid_t uid = -1; 248 static int8_t state = UNINITIALIZED; 249 static int8_t retry = MAX_RETRY; 250 251 static struct { 252 int length; 253 uint8_t value[VALUE_SIZE]; 254 } params[MAX_PARAM]; 255 256 static AES_KEY encryption_key; 257 static AES_KEY decryption_key; 258 259 static int8_t test() 260 { 261 return state; 262 } 263 264 static int8_t get() 265 { 266 char name[NAME_MAX]; 267 int n = sprintf(name, "%u_", uid); 268 encode_key(&name[n], params[0].value, params[0].length); 269 n = decrypt_blob(name, &decryption_key); 270 if (n != NO_ERROR) { 271 return n; 272 } 273 send_code(NO_ERROR); 274 send_message(blob.value, blob.length); 275 return -NO_ERROR; 276 } 277 278 static int8_t insert() 279 { 280 char name[NAME_MAX]; 281 int n = sprintf(name, "%u_", uid); 282 encode_key(&name[n], params[0].value, params[0].length); 283 blob.info = 0; 284 blob.length = params[1].length; 285 memcpy(blob.value, params[1].value, params[1].length); 286 return encrypt_blob(name, &encryption_key); 287 } 288 289 static int8_t delete() 290 { 291 char name[NAME_MAX]; 292 int n = sprintf(name, "%u_", uid); 293 encode_key(&name[n], params[0].value, params[0].length); 294 return (unlink(name) && errno != ENOENT) ? SYSTEM_ERROR : NO_ERROR; 295 } 296 297 static int8_t exist() 298 { 299 char name[NAME_MAX]; 300 int n = sprintf(name, "%u_", uid); 301 encode_key(&name[n], params[0].value, params[0].length); 302 if (access(name, R_OK) == -1) { 303 return (errno != ENOENT) ? SYSTEM_ERROR : KEY_NOT_FOUND; 304 } 305 return NO_ERROR; 306 } 307 308 static int8_t saw() 309 { 310 DIR *dir = opendir("."); 311 struct dirent *file; 312 char name[NAME_MAX]; 313 int n; 314 315 if (!dir) { 316 return SYSTEM_ERROR; 317 } 318 n = sprintf(name, "%u_", uid); 319 n += encode_key(&name[n], params[0].value, params[0].length); 320 send_code(NO_ERROR); 321 while ((file = readdir(dir)) != NULL) { 322 if (!strncmp(name, file->d_name, n)) { 323 char *p = &file->d_name[n]; 324 params[0].length = decode_key(params[0].value, p, strlen(p)); 325 send_message(params[0].value, params[0].length); 326 } 327 } 328 closedir(dir); 329 return -NO_ERROR; 330 } 331 332 static int8_t reset() 333 { 334 DIR *dir = opendir("."); 335 struct dirent *file; 336 337 memset(&encryption_key, 0, sizeof(encryption_key)); 338 memset(&decryption_key, 0, sizeof(decryption_key)); 339 state = UNINITIALIZED; 340 retry = MAX_RETRY; 341 342 if (!dir) { 343 return SYSTEM_ERROR; 344 } 345 while ((file = readdir(dir)) != NULL) { 346 unlink(file->d_name); 347 } 348 closedir(dir); 349 return NO_ERROR; 350 } 351 352 #define MASTER_KEY_FILE ".masterkey" 353 #define MASTER_KEY_SIZE 16 354 #define SALT_SIZE 16 355 356 static void set_key(uint8_t *key, uint8_t *password, int length, uint8_t *salt) 357 { 358 if (salt) { 359 PKCS5_PBKDF2_HMAC_SHA1((char *)password, length, salt, SALT_SIZE, 360 8192, MASTER_KEY_SIZE, key); 361 } else { 362 PKCS5_PBKDF2_HMAC_SHA1((char *)password, length, (uint8_t *)"keystore", 363 sizeof("keystore"), 1024, MASTER_KEY_SIZE, key); 364 } 365 } 366 367 /* Here is the history. To improve the security, the parameters to generate the 368 * master key has been changed. To make a seamless transition, we update the 369 * file using the same password when the user unlock it for the first time. If 370 * any thing goes wrong during the transition, the new file will not overwrite 371 * the old one. This avoids permanent damages of the existing data. */ 372 373 static int8_t password() 374 { 375 uint8_t key[MASTER_KEY_SIZE]; 376 AES_KEY aes_key; 377 int8_t response = SYSTEM_ERROR; 378 379 if (state == UNINITIALIZED) { 380 if (read(the_entropy, blob.value, MASTER_KEY_SIZE) != MASTER_KEY_SIZE) { 381 return SYSTEM_ERROR; 382 } 383 } else { 384 int fd = open(MASTER_KEY_FILE, O_RDONLY); 385 uint8_t *salt = NULL; 386 if (fd != -1) { 387 int length = read(fd, &blob, sizeof(blob)); 388 close(fd); 389 if (length > SALT_SIZE && blob.info == SALT_SIZE) { 390 salt = (uint8_t *)&blob + length - SALT_SIZE; 391 } 392 } 393 394 set_key(key, params[0].value, params[0].length, salt); 395 AES_set_decrypt_key(key, MASTER_KEY_SIZE * 8, &aes_key); 396 response = decrypt_blob(MASTER_KEY_FILE, &aes_key); 397 if (response == SYSTEM_ERROR) { 398 return SYSTEM_ERROR; 399 } 400 if (response != NO_ERROR || blob.length != MASTER_KEY_SIZE) { 401 if (retry <= 0) { 402 reset(); 403 return UNINITIALIZED; 404 } 405 return WRONG_PASSWORD + --retry; 406 } 407 408 if (!salt && params[1].length == -1) { 409 params[1] = params[0]; 410 } 411 } 412 413 if (params[1].length == -1) { 414 memcpy(key, blob.value, MASTER_KEY_SIZE); 415 } else { 416 uint8_t *salt = &blob.value[MASTER_KEY_SIZE]; 417 if (read(the_entropy, salt, SALT_SIZE) != SALT_SIZE) { 418 return SYSTEM_ERROR; 419 } 420 421 set_key(key, params[1].value, params[1].length, salt); 422 AES_set_encrypt_key(key, MASTER_KEY_SIZE * 8, &aes_key); 423 memcpy(key, blob.value, MASTER_KEY_SIZE); 424 blob.info = SALT_SIZE; 425 blob.length = MASTER_KEY_SIZE; 426 response = encrypt_blob(MASTER_KEY_FILE, &aes_key); 427 } 428 429 if (response == NO_ERROR) { 430 AES_set_encrypt_key(key, MASTER_KEY_SIZE * 8, &encryption_key); 431 AES_set_decrypt_key(key, MASTER_KEY_SIZE * 8, &decryption_key); 432 state = NO_ERROR; 433 retry = MAX_RETRY; 434 } 435 return response; 436 } 437 438 static int8_t lock() 439 { 440 memset(&encryption_key, 0, sizeof(encryption_key)); 441 memset(&decryption_key, 0, sizeof(decryption_key)); 442 state = LOCKED; 443 return NO_ERROR; 444 } 445 446 static int8_t unlock() 447 { 448 params[1].length = -1; 449 return password(); 450 } 451 452 /* Here are the permissions, actions, users, and the main function. */ 453 454 enum perm { 455 TEST = 1, 456 GET = 2, 457 INSERT = 4, 458 DELETE = 8, 459 EXIST = 16, 460 SAW = 32, 461 RESET = 64, 462 PASSWORD = 128, 463 LOCK = 256, 464 UNLOCK = 512, 465 }; 466 467 static struct action { 468 int8_t (*run)(); 469 int8_t code; 470 int8_t state; 471 uint32_t perm; 472 int lengths[MAX_PARAM]; 473 } actions[] = { 474 {test, 't', 0, TEST, {0}}, 475 {get, 'g', NO_ERROR, GET, {KEY_SIZE}}, 476 {insert, 'i', NO_ERROR, INSERT, {KEY_SIZE, VALUE_SIZE}}, 477 {delete, 'd', 0, DELETE, {KEY_SIZE}}, 478 {exist, 'e', 0, EXIST, {KEY_SIZE}}, 479 {saw, 's', 0, SAW, {KEY_SIZE}}, 480 {reset, 'r', 0, RESET, {0}}, 481 {password, 'p', 0, PASSWORD, {PASSWORD_SIZE, PASSWORD_SIZE}}, 482 {lock, 'l', NO_ERROR, LOCK, {0}}, 483 {unlock, 'u', LOCKED, UNLOCK, {PASSWORD_SIZE}}, 484 {NULL, 0 , 0, 0, {0}}, 485 }; 486 487 static struct user { 488 uid_t uid; 489 uid_t euid; 490 uint32_t perms; 491 } users[] = { 492 {AID_SYSTEM, ~0, ~GET}, 493 {AID_VPN, AID_SYSTEM, GET}, 494 {AID_WIFI, AID_SYSTEM, GET}, 495 {AID_ROOT, AID_SYSTEM, GET}, 496 {~0, ~0, TEST | GET | INSERT | DELETE | EXIST | SAW}, 497 }; 498 499 static int8_t process(int8_t code) { 500 struct user *user = users; 501 struct action *action = actions; 502 int i; 503 504 while (~user->uid && user->uid != uid) { 505 ++user; 506 } 507 while (action->code && action->code != code) { 508 ++action; 509 } 510 if (!action->code) { 511 return UNDEFINED_ACTION; 512 } 513 if (!(action->perm & user->perms)) { 514 return PERMISSION_DENIED; 515 } 516 if (action->state && action->state != state) { 517 return state; 518 } 519 if (~user->euid) { 520 uid = user->euid; 521 } 522 for (i = 0; i < MAX_PARAM && action->lengths[i]; ++i) { 523 params[i].length = recv_message(params[i].value, action->lengths[i]); 524 if (params[i].length == -1) { 525 return PROTOCOL_ERROR; 526 } 527 } 528 if (!recv_end_of_file()) { 529 return PROTOCOL_ERROR; 530 } 531 return action->run(); 532 } 533 534 #define RANDOM_DEVICE "/dev/urandom" 535 536 int main(int argc, char **argv) 537 { 538 int control_socket = android_get_control_socket("keystore"); 539 if (argc < 2) { 540 LOGE("A directory must be specified!"); 541 return 1; 542 } 543 if (chdir(argv[1]) == -1) { 544 LOGE("chdir: %s: %s", argv[1], strerror(errno)); 545 return 1; 546 } 547 if ((the_entropy = open(RANDOM_DEVICE, O_RDONLY)) == -1) { 548 LOGE("open: %s: %s", RANDOM_DEVICE, strerror(errno)); 549 return 1; 550 } 551 if (listen(control_socket, 3) == -1) { 552 LOGE("listen: %s", strerror(errno)); 553 return 1; 554 } 555 556 signal(SIGPIPE, SIG_IGN); 557 if (access(MASTER_KEY_FILE, R_OK) == 0) { 558 state = LOCKED; 559 } 560 561 while ((the_socket = accept(control_socket, NULL, 0)) != -1) { 562 struct timeval tv = {.tv_sec = 3}; 563 struct ucred cred; 564 socklen_t size = sizeof(cred); 565 int8_t request; 566 567 setsockopt(the_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); 568 setsockopt(the_socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); 569 570 if (getsockopt(the_socket, SOL_SOCKET, SO_PEERCRED, &cred, &size)) { 571 LOGW("getsockopt: %s", strerror(errno)); 572 } else if (recv_code(&request)) { 573 int8_t old_state = state; 574 int8_t response; 575 uid = cred.uid; 576 577 if ((response = process(request)) > 0) { 578 send_code(response); 579 response = -response; 580 } 581 582 LOGI("uid: %d action: %c -> %d state: %d -> %d retry: %d", 583 cred.uid, request, -response, old_state, state, retry); 584 } 585 close(the_socket); 586 } 587 LOGE("accept: %s", strerror(errno)); 588 return 1; 589 } 590