blob: c86e7120579ac2e349d85f24f125d48b057c0d5f [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 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/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
24#include <sys/stat.h>
25#include <fcntl.h>
26#include <unistd.h>
27#include <stdio.h>
28#include <sys/ioctl.h>
29#include <linux/dm-ioctl.h>
30#include <libgen.h>
31#include <stdlib.h>
32#include <sys/param.h>
33#include <string.h>
34#include <sys/mount.h>
35#include <openssl/evp.h>
Ken Sumrall8ddbe402011-01-17 15:26:29 -080036#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080037#include <errno.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080038#include <cutils/android_reboot.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080039#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070040#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080042#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
Mike Lockwoodee6d8c42012-02-15 13:43:28 -080044#include "cutils/android_reboot.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080045#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070048#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070049#include "VoldUtil.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050
51#define DM_CRYPT_BUF_SIZE 4096
Ken Sumrall8ddbe402011-01-17 15:26:29 -080052#define DATA_MNT_POINT "/data"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080053
Jason parks70a4b3f2011-01-28 10:10:47 -060054#define HASH_COUNT 2000
55#define KEY_LEN_BYTES 16
56#define IV_LEN_BYTES 16
57
Ken Sumrall29d8da82011-05-18 17:20:07 -070058#define KEY_IN_FOOTER "footer"
59
60#define EXT4_FS 1
61#define FAT_FS 2
62
Ken Sumralle919efe2012-09-29 17:07:41 -070063#define TABLE_LOAD_RETRIES 10
64
Ken Sumrall8f869aa2010-12-03 03:47:09 -080065char *me = "cryptfs";
66
Jason parks70a4b3f2011-01-28 10:10:47 -060067static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070068static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060069static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070070static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080071
72extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080073
Ken Sumrall8f869aa2010-12-03 03:47:09 -080074static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
75{
76 memset(io, 0, dataSize);
77 io->data_size = dataSize;
78 io->data_start = sizeof(struct dm_ioctl);
79 io->version[0] = 4;
80 io->version[1] = 0;
81 io->version[2] = 0;
82 io->flags = flags;
83 if (name) {
84 strncpy(io->name, name, sizeof(io->name));
85 }
86}
87
Ken Sumrall3ed82362011-01-28 23:31:16 -080088static unsigned int get_fs_size(char *dev)
89{
90 int fd, block_size;
91 struct ext4_super_block sb;
92 off64_t len;
93
94 if ((fd = open(dev, O_RDONLY)) < 0) {
95 SLOGE("Cannot open device to get filesystem size ");
96 return 0;
97 }
98
99 if (lseek64(fd, 1024, SEEK_SET) < 0) {
100 SLOGE("Cannot seek to superblock");
101 return 0;
102 }
103
104 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
105 SLOGE("Cannot read superblock");
106 return 0;
107 }
108
109 close(fd);
110
111 block_size = 1024 << sb.s_log_block_size;
112 /* compute length in bytes */
113 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
114
115 /* return length in sectors */
116 return (unsigned int) (len / 512);
117}
118
Ken Sumrall160b4d62013-04-22 12:15:39 -0700119static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
120{
121 static int cached_data = 0;
122 static off64_t cached_off = 0;
123 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
124 int fd;
125 char key_loc[PROPERTY_VALUE_MAX];
126 char real_blkdev[PROPERTY_VALUE_MAX];
127 unsigned int nr_sec;
128 int rc = -1;
129
130 if (!cached_data) {
131 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
132
133 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
134 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
135 SLOGE("Cannot open real block device %s\n", real_blkdev);
136 return -1;
137 }
138
139 if ((nr_sec = get_blkdev_size(fd))) {
140 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
141 * encryption info footer and key, and plenty of bytes to spare for future
142 * growth.
143 */
144 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
145 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
146 cached_data = 1;
147 } else {
148 SLOGE("Cannot get size of block device %s\n", real_blkdev);
149 }
150 close(fd);
151 } else {
152 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
153 cached_off = 0;
154 cached_data = 1;
155 }
156 }
157
158 if (cached_data) {
159 if (metadata_fname) {
160 *metadata_fname = cached_metadata_fname;
161 }
162 if (off) {
163 *off = cached_off;
164 }
165 rc = 0;
166 }
167
168 return rc;
169}
170
Ken Sumralle8744072011-01-18 22:01:55 -0800171/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800172 * update the failed mount count but not change the key.
173 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700174static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800175{
176 int fd;
177 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700178 /* starting_off is set to the SEEK_SET offset
179 * where the crypto structure starts
180 */
181 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800182 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700183 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700184 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall3be890f2011-09-14 16:53:46 -0700185 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800186
Ken Sumrall160b4d62013-04-22 12:15:39 -0700187 if (get_crypt_ftr_info(&fname, &starting_off)) {
188 SLOGE("Unable to get crypt_ftr_info\n");
189 return -1;
190 }
191 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700192 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700193 return -1;
194 }
195 if ( (fd = open(fname, O_RDWR)) < 0) {
196 SLOGE("Cannot open footer file %s\n", fname);
197 return -1;
198 }
199
200 /* Seek to the start of the crypt footer */
201 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
202 SLOGE("Cannot seek to real block device footer\n");
203 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800204 }
205
206 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
207 SLOGE("Cannot write real block device footer\n");
208 goto errout;
209 }
210
Ken Sumrall3be890f2011-09-14 16:53:46 -0700211 fstat(fd, &statbuf);
212 /* If the keys are kept on a raw block device, do not try to truncate it. */
213 if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700214 if (ftruncate(fd, 0x4000)) {
Ken Sumrall3be890f2011-09-14 16:53:46 -0700215 SLOGE("Cannot set footer file size\n", fname);
Ken Sumralle8744072011-01-18 22:01:55 -0800216 goto errout;
217 }
218 }
219
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800220 /* Success! */
221 rc = 0;
222
223errout:
224 close(fd);
225 return rc;
226
227}
228
Ken Sumrall160b4d62013-04-22 12:15:39 -0700229static inline int unix_read(int fd, void* buff, int len)
230{
231 return TEMP_FAILURE_RETRY(read(fd, buff, len));
232}
233
234static inline int unix_write(int fd, const void* buff, int len)
235{
236 return TEMP_FAILURE_RETRY(write(fd, buff, len));
237}
238
239static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
240{
241 memset(pdata, 0, len);
242 pdata->persist_magic = PERSIST_DATA_MAGIC;
243 pdata->persist_valid_entries = 0;
244}
245
246/* A routine to update the passed in crypt_ftr to the lastest version.
247 * fd is open read/write on the device that holds the crypto footer and persistent
248 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
249 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
250 */
251static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
252{
253 struct crypt_persist_data *pdata;
254 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
255
256 /* This routine can currently only handle upgrading from 1.0 to 1.1.
257 * Do nothing if the passed structure is not version 1.0
258 */
259
260 if ((crypt_ftr->major_version != 1) && (crypt_ftr->minor_version != 0)) {
261 return;
262 }
263
264 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
265 if (pdata == NULL) {
266 SLOGE("Cannot allocate persisent data\n");
267 return;
268 }
269 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
270
271 /* Need to initialize the persistent data area */
272 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
273 SLOGE("Cannot seek to persisent data offset\n");
274 return;
275 }
276 /* Write all zeros to the first copy, making it invalid */
277 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
278
279 /* Write a valid but empty structure to the second copy */
280 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
281 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
282
283 /* Update the footer */
284 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
285 crypt_ftr->persist_data_offset[0] = pdata_offset;
286 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
287 crypt_ftr->minor_version = 1;
288 if (lseek64(fd, offset, SEEK_SET) == -1) {
289 SLOGE("Cannot seek to crypt footer\n");
290 return;
291 }
292 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
293}
294
295
296static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800297{
298 int fd;
299 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700300 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800301 int rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700302 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700303 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700304 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800305
Ken Sumrall160b4d62013-04-22 12:15:39 -0700306 if (get_crypt_ftr_info(&fname, &starting_off)) {
307 SLOGE("Unable to get crypt_ftr_info\n");
308 return -1;
309 }
310 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700311 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700312 return -1;
313 }
314 if ( (fd = open(fname, O_RDWR)) < 0) {
315 SLOGE("Cannot open footer file %s\n", fname);
316 return -1;
317 }
318
319 /* Make sure it's 16 Kbytes in length */
320 fstat(fd, &statbuf);
321 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
322 SLOGE("footer file %s is not the expected size!\n", fname);
323 goto errout;
324 }
325
326 /* Seek to the start of the crypt footer */
327 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
328 SLOGE("Cannot seek to real block device footer\n");
329 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800330 }
331
332 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
333 SLOGE("Cannot read real block device footer\n");
334 goto errout;
335 }
336
337 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700338 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800339 goto errout;
340 }
341
342 if (crypt_ftr->major_version != 1) {
343 SLOGE("Cannot understand major version %d real block device footer\n",
344 crypt_ftr->major_version);
345 goto errout;
346 }
347
Ken Sumrall160b4d62013-04-22 12:15:39 -0700348 if ((crypt_ftr->minor_version != 0) && (crypt_ftr->minor_version != 1)) {
349 SLOGW("Warning: crypto footer minor version %d, expected 0 or 1, continuing...\n",
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800350 crypt_ftr->minor_version);
351 }
352
Ken Sumrall160b4d62013-04-22 12:15:39 -0700353 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
354 * copy on disk before returning.
355 */
356 if (crypt_ftr->minor_version == 0) {
357 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800358 }
359
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800360 /* Success! */
361 rc = 0;
362
363errout:
364 close(fd);
365 return rc;
366}
367
Ken Sumrall160b4d62013-04-22 12:15:39 -0700368static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
369{
370 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
371 crypt_ftr->persist_data_offset[1]) {
372 SLOGE("Crypt_ftr persist data regions overlap");
373 return -1;
374 }
375
376 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
377 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
378 return -1;
379 }
380
381 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
382 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
383 CRYPT_FOOTER_OFFSET) {
384 SLOGE("Persistent data extends past crypto footer");
385 return -1;
386 }
387
388 return 0;
389}
390
391static int load_persistent_data(void)
392{
393 struct crypt_mnt_ftr crypt_ftr;
394 struct crypt_persist_data *pdata = NULL;
395 char encrypted_state[PROPERTY_VALUE_MAX];
396 char *fname;
397 int found = 0;
398 int fd;
399 int ret;
400 int i;
401
402 if (persist_data) {
403 /* Nothing to do, we've already loaded or initialized it */
404 return 0;
405 }
406
407
408 /* If not encrypted, just allocate an empty table and initialize it */
409 property_get("ro.crypto.state", encrypted_state, "");
410 if (strcmp(encrypted_state, "encrypted") ) {
411 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
412 if (pdata) {
413 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
414 persist_data = pdata;
415 return 0;
416 }
417 return -1;
418 }
419
420 if(get_crypt_ftr_and_key(&crypt_ftr)) {
421 return -1;
422 }
423
424 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
425 SLOGE("Crypt_ftr version doesn't support persistent data");
426 return -1;
427 }
428
429 if (get_crypt_ftr_info(&fname, NULL)) {
430 return -1;
431 }
432
433 ret = validate_persistent_data_storage(&crypt_ftr);
434 if (ret) {
435 return -1;
436 }
437
438 fd = open(fname, O_RDONLY);
439 if (fd < 0) {
440 SLOGE("Cannot open %s metadata file", fname);
441 return -1;
442 }
443
444 if (persist_data == NULL) {
445 pdata = malloc(crypt_ftr.persist_data_size);
446 if (pdata == NULL) {
447 SLOGE("Cannot allocate memory for persistent data");
448 goto err;
449 }
450 }
451
452 for (i = 0; i < 2; i++) {
453 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
454 SLOGE("Cannot seek to read persistent data on %s", fname);
455 goto err2;
456 }
457 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
458 SLOGE("Error reading persistent data on iteration %d", i);
459 goto err2;
460 }
461 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
462 found = 1;
463 break;
464 }
465 }
466
467 if (!found) {
468 SLOGI("Could not find valid persistent data, creating");
469 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
470 }
471
472 /* Success */
473 persist_data = pdata;
474 close(fd);
475 return 0;
476
477err2:
478 free(pdata);
479
480err:
481 close(fd);
482 return -1;
483}
484
485static int save_persistent_data(void)
486{
487 struct crypt_mnt_ftr crypt_ftr;
488 struct crypt_persist_data *pdata;
489 char *fname;
490 off64_t write_offset;
491 off64_t erase_offset;
492 int found = 0;
493 int fd;
494 int ret;
495
496 if (persist_data == NULL) {
497 SLOGE("No persistent data to save");
498 return -1;
499 }
500
501 if(get_crypt_ftr_and_key(&crypt_ftr)) {
502 return -1;
503 }
504
505 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
506 SLOGE("Crypt_ftr version doesn't support persistent data");
507 return -1;
508 }
509
510 ret = validate_persistent_data_storage(&crypt_ftr);
511 if (ret) {
512 return -1;
513 }
514
515 if (get_crypt_ftr_info(&fname, NULL)) {
516 return -1;
517 }
518
519 fd = open(fname, O_RDWR);
520 if (fd < 0) {
521 SLOGE("Cannot open %s metadata file", fname);
522 return -1;
523 }
524
525 pdata = malloc(crypt_ftr.persist_data_size);
526 if (pdata == NULL) {
527 SLOGE("Cannot allocate persistant data");
528 goto err;
529 }
530
531 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
532 SLOGE("Cannot seek to read persistent data on %s", fname);
533 goto err2;
534 }
535
536 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
537 SLOGE("Error reading persistent data before save");
538 goto err2;
539 }
540
541 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
542 /* The first copy is the curent valid copy, so write to
543 * the second copy and erase this one */
544 write_offset = crypt_ftr.persist_data_offset[1];
545 erase_offset = crypt_ftr.persist_data_offset[0];
546 } else {
547 /* The second copy must be the valid copy, so write to
548 * the first copy, and erase the second */
549 write_offset = crypt_ftr.persist_data_offset[0];
550 erase_offset = crypt_ftr.persist_data_offset[1];
551 }
552
553 /* Write the new copy first, if successful, then erase the old copy */
554 if (lseek(fd, write_offset, SEEK_SET) < 0) {
555 SLOGE("Cannot seek to write persistent data");
556 goto err2;
557 }
558 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
559 (int) crypt_ftr.persist_data_size) {
560 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
561 SLOGE("Cannot seek to erase previous persistent data");
562 goto err2;
563 }
564 fsync(fd);
565 memset(pdata, 0, crypt_ftr.persist_data_size);
566 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
567 (int) crypt_ftr.persist_data_size) {
568 SLOGE("Cannot write to erase previous persistent data");
569 goto err2;
570 }
571 fsync(fd);
572 } else {
573 SLOGE("Cannot write to save persistent data");
574 goto err2;
575 }
576
577 /* Success */
578 free(pdata);
579 close(fd);
580 return 0;
581
582err2:
583 free(pdata);
584err:
585 close(fd);
586 return -1;
587}
588
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800589/* Convert a binary key of specified length into an ascii hex string equivalent,
590 * without the leading 0x and with null termination
591 */
592void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
593 char *master_key_ascii)
594{
595 unsigned int i, a;
596 unsigned char nibble;
597
598 for (i=0, a=0; i<keysize; i++, a+=2) {
599 /* For each byte, write out two ascii hex digits */
600 nibble = (master_key[i] >> 4) & 0xf;
601 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
602
603 nibble = master_key[i] & 0xf;
604 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
605 }
606
607 /* Add the null termination */
608 master_key_ascii[a] = '\0';
609
610}
611
Ken Sumralldb5e0262013-02-05 17:39:48 -0800612static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
613 char *real_blk_name, const char *name, int fd,
614 char *extra_params)
615{
616 char buffer[DM_CRYPT_BUF_SIZE];
617 struct dm_ioctl *io;
618 struct dm_target_spec *tgt;
619 char *crypt_params;
620 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
621 int i;
622
623 io = (struct dm_ioctl *) buffer;
624
625 /* Load the mapping table for this device */
626 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
627
628 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
629 io->target_count = 1;
630 tgt->status = 0;
631 tgt->sector_start = 0;
632 tgt->length = crypt_ftr->fs_size;
633 strcpy(tgt->target_type, "crypt");
634
635 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
636 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
637 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
638 master_key_ascii, real_blk_name, extra_params);
639 crypt_params += strlen(crypt_params) + 1;
640 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
641 tgt->next = crypt_params - buffer;
642
643 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
644 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
645 break;
646 }
647 usleep(500000);
648 }
649
650 if (i == TABLE_LOAD_RETRIES) {
651 /* We failed to load the table, return an error */
652 return -1;
653 } else {
654 return i + 1;
655 }
656}
657
658
659static int get_dm_crypt_version(int fd, const char *name, int *version)
660{
661 char buffer[DM_CRYPT_BUF_SIZE];
662 struct dm_ioctl *io;
663 struct dm_target_versions *v;
664 int i;
665
666 io = (struct dm_ioctl *) buffer;
667
668 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
669
670 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
671 return -1;
672 }
673
674 /* Iterate over the returned versions, looking for name of "crypt".
675 * When found, get and return the version.
676 */
677 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
678 while (v->next) {
679 if (! strcmp(v->name, "crypt")) {
680 /* We found the crypt driver, return the version, and get out */
681 version[0] = v->version[0];
682 version[1] = v->version[1];
683 version[2] = v->version[2];
684 return 0;
685 }
686 v = (struct dm_target_versions *)(((char *)v) + v->next);
687 }
688
689 return -1;
690}
691
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800692static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700693 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800694{
695 char buffer[DM_CRYPT_BUF_SIZE];
696 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
697 char *crypt_params;
698 struct dm_ioctl *io;
699 struct dm_target_spec *tgt;
700 unsigned int minor;
701 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700702 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800703 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800704 int version[3];
705 char *extra_params;
706 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800707
708 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
709 SLOGE("Cannot open device-mapper\n");
710 goto errout;
711 }
712
713 io = (struct dm_ioctl *) buffer;
714
715 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
716 if (ioctl(fd, DM_DEV_CREATE, io)) {
717 SLOGE("Cannot create dm-crypt device\n");
718 goto errout;
719 }
720
721 /* Get the device status, in particular, the name of it's device file */
722 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
723 if (ioctl(fd, DM_DEV_STATUS, io)) {
724 SLOGE("Cannot retrieve dm-crypt device status\n");
725 goto errout;
726 }
727 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
728 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
729
Ken Sumralldb5e0262013-02-05 17:39:48 -0800730 extra_params = "";
731 if (! get_dm_crypt_version(fd, name, version)) {
732 /* Support for allow_discards was added in version 1.11.0 */
733 if ((version[0] >= 2) ||
734 ((version[0] == 1) && (version[1] >= 11))) {
735 extra_params = "1 allow_discards";
736 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
737 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700738 }
739
Ken Sumralldb5e0262013-02-05 17:39:48 -0800740 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
741 fd, extra_params);
742 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800743 SLOGE("Cannot load dm-crypt mapping table.\n");
744 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800745 } else if (load_count > 1) {
746 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800747 }
748
749 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800750 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800751
752 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
753 SLOGE("Cannot resume the dm-crypt device\n");
754 goto errout;
755 }
756
757 /* We made it here with no errors. Woot! */
758 retval = 0;
759
760errout:
761 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
762
763 return retval;
764}
765
Ken Sumrall29d8da82011-05-18 17:20:07 -0700766static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800767{
768 int fd;
769 char buffer[DM_CRYPT_BUF_SIZE];
770 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800771 int retval = -1;
772
773 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
774 SLOGE("Cannot open device-mapper\n");
775 goto errout;
776 }
777
778 io = (struct dm_ioctl *) buffer;
779
780 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
781 if (ioctl(fd, DM_DEV_REMOVE, io)) {
782 SLOGE("Cannot remove dm-crypt device\n");
783 goto errout;
784 }
785
786 /* We made it here with no errors. Woot! */
787 retval = 0;
788
789errout:
790 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
791
792 return retval;
793
794}
795
Ken Sumralle8744072011-01-18 22:01:55 -0800796static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800797{
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800798 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800799 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800800 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800801}
802
Ken Sumralle8744072011-01-18 22:01:55 -0800803static int encrypt_master_key(char *passwd, unsigned char *salt,
804 unsigned char *decrypted_master_key,
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800805 unsigned char *encrypted_master_key)
806{
807 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
808 EVP_CIPHER_CTX e_ctx;
809 int encrypted_len, final_len;
810
811 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800812 pbkdf2(passwd, salt, ikey);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800813
814 /* Initialize the decryption engine */
815 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
816 SLOGE("EVP_EncryptInit failed\n");
817 return -1;
818 }
819 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800820
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800821 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800822 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
823 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800824 SLOGE("EVP_EncryptUpdate failed\n");
825 return -1;
826 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800827 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828 SLOGE("EVP_EncryptFinal failed\n");
829 return -1;
830 }
831
832 if (encrypted_len + final_len != KEY_LEN_BYTES) {
833 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
834 return -1;
835 } else {
836 return 0;
837 }
838}
839
Ken Sumralle8744072011-01-18 22:01:55 -0800840static int decrypt_master_key(char *passwd, unsigned char *salt,
841 unsigned char *encrypted_master_key,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800842 unsigned char *decrypted_master_key)
843{
844 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800845 EVP_CIPHER_CTX d_ctx;
846 int decrypted_len, final_len;
847
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800848 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800849 pbkdf2(passwd, salt, ikey);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800850
851 /* Initialize the decryption engine */
852 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
853 return -1;
854 }
855 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
856 /* Decrypt the master key */
857 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
858 encrypted_master_key, KEY_LEN_BYTES)) {
859 return -1;
860 }
861 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
862 return -1;
863 }
864
865 if (decrypted_len + final_len != KEY_LEN_BYTES) {
866 return -1;
867 } else {
868 return 0;
869 }
870}
871
Ken Sumralle8744072011-01-18 22:01:55 -0800872static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800873{
874 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800875 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800876 EVP_CIPHER_CTX e_ctx;
877 int encrypted_len, final_len;
878
879 /* Get some random bits for a key */
880 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -0800881 read(fd, key_buf, sizeof(key_buf));
882 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800883 close(fd);
884
885 /* Now encrypt it with the password */
Ken Sumralle8744072011-01-18 22:01:55 -0800886 return encrypt_master_key(passwd, salt, key_buf, master_key);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800887}
888
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800889static int wait_and_unmount(char *mountpoint)
890{
891 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -0800892#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800893
894 /* Now umount the tmpfs filesystem */
895 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
896 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700897 if (errno == EINVAL) {
898 /* EINVAL is returned if the directory is not a mountpoint,
899 * i.e. there is no filesystem mounted there. So just get out.
900 */
901 break;
902 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800903 sleep(1);
904 i++;
905 } else {
906 break;
907 }
908 }
909
910 if (i < WAIT_UNMOUNT_COUNT) {
911 SLOGD("unmounting %s succeeded\n", mountpoint);
912 rc = 0;
913 } else {
914 SLOGE("unmounting %s failed\n", mountpoint);
915 rc = -1;
916 }
917
918 return rc;
919}
920
Ken Sumrallc5872692013-05-14 15:26:31 -0700921#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800922static int prep_data_fs(void)
923{
924 int i;
925
926 /* Do the prep of the /data filesystem */
927 property_set("vold.post_fs_data_done", "0");
928 property_set("vold.decrypt", "trigger_post_fs_data");
929 SLOGD("Just triggered post_fs_data\n");
930
Ken Sumrallc5872692013-05-14 15:26:31 -0700931 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800932 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700933 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800934
935 property_get("vold.post_fs_data_done", p, "0");
936 if (*p == '1') {
937 break;
938 } else {
939 usleep(250000);
940 }
941 }
942 if (i == DATA_PREP_TIMEOUT) {
943 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -0700944 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800945 return -1;
946 } else {
947 SLOGD("post_fs_data done\n");
948 return 0;
949 }
950}
951
Ken Sumrall6864b7e2011-01-14 15:20:02 -0800952int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953{
954 char fs_type[32];
955 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -0800956 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800957 char fs_options[256];
958 unsigned long mnt_flags;
959 struct stat statbuf;
960 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -0800961 static int restart_successful = 0;
962
963 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -0600964 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -0800965 SLOGE("Encrypted filesystem not validated, aborting");
966 return -1;
967 }
968
969 if (restart_successful) {
970 SLOGE("System already restarted with encrypted disk, aborting");
971 return -1;
972 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800973
974 /* Here is where we shut down the framework. The init scripts
975 * start all services in one of three classes: core, main or late_start.
976 * On boot, we start core and main. Now, we stop main, but not core,
977 * as core includes vold and a few other really important things that
978 * we need to keep running. Once main has stopped, we should be able
979 * to umount the tmpfs /data, then mount the encrypted /data.
980 * We then restart the class main, and also the class late_start.
981 * At the moment, I've only put a few things in late_start that I know
982 * are not needed to bring up the framework, and that also cause problems
983 * with unmounting the tmpfs /data, but I hope to add add more services
984 * to the late_start class as we optimize this to decrease the delay
985 * till the user is asked for the password to the filesystem.
986 */
987
988 /* The init files are setup to stop the class main when vold.decrypt is
989 * set to trigger_reset_main.
990 */
991 property_set("vold.decrypt", "trigger_reset_main");
992 SLOGD("Just asked init to shut down class main\n");
993
Ken Sumrall92736ef2012-10-17 20:57:14 -0700994 /* Ugh, shutting down the framework is not synchronous, so until it
995 * can be fixed, this horrible hack will wait a moment for it all to
996 * shut down before proceeding. Without it, some devices cannot
997 * restart the graphics services.
998 */
999 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001000
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001001 /* Now that the framework is shutdown, we should be able to umount()
1002 * the tmpfs filesystem, and mount the real one.
1003 */
1004
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001005 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1006 if (strlen(crypto_blkdev) == 0) {
1007 SLOGE("fs_crypto_blkdev not set\n");
1008 return -1;
1009 }
1010
Ken Sumralle5032c42012-04-01 23:58:44 -07001011 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1012 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001013 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001014
Ken Sumralle5032c42012-04-01 23:58:44 -07001015 property_set("vold.decrypt", "trigger_load_persist_props");
1016 /* Create necessary paths on /data */
1017 if (prep_data_fs()) {
1018 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001019 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001020
1021 /* startup service classes main and late_start */
1022 property_set("vold.decrypt", "trigger_restart_framework");
1023 SLOGD("Just triggered restart_framework\n");
1024
1025 /* Give it a few moments to get started */
1026 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001027 }
1028
Ken Sumrall0cc16632011-01-18 20:32:26 -08001029 if (rc == 0) {
1030 restart_successful = 1;
1031 }
1032
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001033 return rc;
1034}
1035
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001036static int do_crypto_complete(char *mount_point)
1037{
1038 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001039 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001040 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001041
1042 property_get("ro.crypto.state", encrypted_state, "");
1043 if (strcmp(encrypted_state, "encrypted") ) {
1044 SLOGE("not running with encryption, aborting");
1045 return 1;
1046 }
1047
Ken Sumrall160b4d62013-04-22 12:15:39 -07001048 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001049 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001050
Ken Sumralle1a45852011-12-14 21:24:27 -08001051 /*
1052 * Only report this error if key_loc is a file and it exists.
1053 * If the device was never encrypted, and /data is not mountable for
1054 * some reason, returning 1 should prevent the UI from presenting the
1055 * a "enter password" screen, or worse, a "press button to wipe the
1056 * device" screen.
1057 */
1058 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1059 SLOGE("master key file does not exist, aborting");
1060 return 1;
1061 } else {
1062 SLOGE("Error getting crypt footer and key\n");
1063 return -1;
1064 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001065 }
1066
1067 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1068 SLOGE("Encryption process didn't finish successfully\n");
1069 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1070 * and give the user an option to wipe the disk */
1071 }
1072
1073 /* We passed the test! We shall diminish, and return to the west */
1074 return 0;
1075}
1076
Ken Sumrall29d8da82011-05-18 17:20:07 -07001077static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001078{
1079 struct crypt_mnt_ftr crypt_ftr;
1080 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001081 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001082 char crypto_blkdev[MAXPATHLEN];
1083 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001084 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001085 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001086 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001087 int rc;
1088
Ken Sumrall0cc16632011-01-18 20:32:26 -08001089 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001090 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001091 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1092 return -1;
1093 }
1094
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001095 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001096
Ken Sumrall160b4d62013-04-22 12:15:39 -07001097 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001098 SLOGE("Error getting crypt footer and key\n");
1099 return -1;
1100 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001101
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001102 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1103 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1104
1105 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001106 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key, decrypted_master_key);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001107 }
1108
1109 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001110 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001111 SLOGE("Error creating decrypted block device\n");
1112 return -1;
1113 }
1114
Alex Klyubin707795a2013-05-10 15:17:07 -07001115 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001116 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1117 * files and passes that data to me */
1118 /* Create a tmp mount point to try mounting the decryptd fs
1119 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1120 * a directory in it to test mount the decrypted filesystem.
1121 */
1122 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1123 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001124 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001126 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001127 crypt_ftr.failed_decrypt_count++;
1128 } else {
1129 /* Success, so just umount and we'll mount it properly when we restart
1130 * the framework.
1131 */
1132 umount(tmp_mount_point);
1133 crypt_ftr.failed_decrypt_count = 0;
1134 }
1135
1136 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001137 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001138 }
1139
1140 if (crypt_ftr.failed_decrypt_count) {
1141 /* We failed to mount the device, so return an error */
1142 rc = crypt_ftr.failed_decrypt_count;
1143
1144 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001145 /* Woot! Success! Save the name of the crypto block device
1146 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001147 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001148 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001149
1150 /* Also save a the master key so we can reencrypted the key
1151 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001152 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001153 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001154 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001155 master_key_saved = 1;
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001156 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 }
1158
1159 return rc;
1160}
1161
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001162/* Called by vold when it wants to undo the crypto mapping of a volume it
1163 * manages. This is usually in response to a factory reset, when we want
1164 * to undo the crypto mapping so the volume is formatted in the clear.
1165 */
1166int cryptfs_revert_volume(const char *label)
1167{
1168 return delete_crypto_blk_dev((char *)label);
1169}
1170
Ken Sumrall29d8da82011-05-18 17:20:07 -07001171/*
1172 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1173 * Setup a dm-crypt mapping, use the saved master key from
1174 * setting up the /data mapping, and return the new device path.
1175 */
1176int cryptfs_setup_volume(const char *label, int major, int minor,
1177 char *crypto_sys_path, unsigned int max_path,
1178 int *new_major, int *new_minor)
1179{
1180 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1181 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001182 struct stat statbuf;
1183 int nr_sec, fd;
1184
1185 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1186
Ken Sumrall160b4d62013-04-22 12:15:39 -07001187 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001188
1189 /* Update the fs_size field to be the size of the volume */
1190 fd = open(real_blkdev, O_RDONLY);
1191 nr_sec = get_blkdev_size(fd);
1192 close(fd);
1193 if (nr_sec == 0) {
1194 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1195 return -1;
1196 }
1197
1198 sd_crypt_ftr.fs_size = nr_sec;
1199 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1200 crypto_blkdev, label);
1201
1202 stat(crypto_blkdev, &statbuf);
1203 *new_major = MAJOR(statbuf.st_rdev);
1204 *new_minor = MINOR(statbuf.st_rdev);
1205
1206 /* Create path to sys entry for this block device */
1207 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1208
1209 return 0;
1210}
1211
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001212int cryptfs_crypto_complete(void)
1213{
1214 return do_crypto_complete("/data");
1215}
1216
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001217int cryptfs_check_passwd(char *passwd)
1218{
1219 int rc = -1;
1220
Ken Sumrall29d8da82011-05-18 17:20:07 -07001221 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001222
1223 return rc;
1224}
1225
Ken Sumrall3ad90722011-10-04 20:38:29 -07001226int cryptfs_verify_passwd(char *passwd)
1227{
1228 struct crypt_mnt_ftr crypt_ftr;
1229 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001230 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001231 char encrypted_state[PROPERTY_VALUE_MAX];
1232 int rc;
1233
1234 property_get("ro.crypto.state", encrypted_state, "");
1235 if (strcmp(encrypted_state, "encrypted") ) {
1236 SLOGE("device not encrypted, aborting");
1237 return -2;
1238 }
1239
1240 if (!master_key_saved) {
1241 SLOGE("encrypted fs not yet mounted, aborting");
1242 return -1;
1243 }
1244
1245 if (!saved_mount_point) {
1246 SLOGE("encrypted fs failed to save mount point, aborting");
1247 return -1;
1248 }
1249
Ken Sumrall160b4d62013-04-22 12:15:39 -07001250 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001251 SLOGE("Error getting crypt footer and key\n");
1252 return -1;
1253 }
1254
1255 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1256 /* If the device has no password, then just say the password is valid */
1257 rc = 0;
1258 } else {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001259 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key,
1260 decrypted_master_key);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001261 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1262 /* They match, the password is correct */
1263 rc = 0;
1264 } else {
1265 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1266 sleep(1);
1267 rc = 1;
1268 }
1269 }
1270
1271 return rc;
1272}
1273
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001274/* Initialize a crypt_mnt_ftr structure. The keysize is
1275 * defaulted to 16 bytes, and the filesystem size to 0.
1276 * Presumably, at a minimum, the caller will update the
1277 * filesystem size and crypto_type_name after calling this function.
1278 */
1279static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1280{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001281 off64_t off;
1282
1283 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001284 ftr->magic = CRYPT_MNT_MAGIC;
1285 ftr->major_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001286 ftr->minor_version = 1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001287 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001288 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001289
1290 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1291 if (get_crypt_ftr_info(NULL, &off) == 0) {
1292 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1293 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1294 ftr->persist_data_size;
1295 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296}
1297
Ken Sumrall29d8da82011-05-18 17:20:07 -07001298static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299{
1300 char cmdline[256];
1301 int rc = -1;
1302
Ken Sumrall29d8da82011-05-18 17:20:07 -07001303 if (type == EXT4_FS) {
1304 snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
1305 size * 512, crypto_blkdev);
1306 SLOGI("Making empty filesystem with command %s\n", cmdline);
1307 } else if (type== FAT_FS) {
1308 snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
1309 size, crypto_blkdev);
1310 SLOGI("Making empty filesystem with command %s\n", cmdline);
1311 } else {
1312 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1313 return -1;
1314 }
1315
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001316 if (system(cmdline)) {
1317 SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
1318 } else {
1319 SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
1320 rc = 0;
1321 }
1322
1323 return rc;
1324}
1325
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001326#define CRYPT_INPLACE_BUFSIZE 4096
1327#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001328static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1329 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001330{
1331 int realfd, cryptofd;
1332 char *buf[CRYPT_INPLACE_BUFSIZE];
1333 int rc = -1;
1334 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001335 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001336 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001337
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001338 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1339 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1340 return -1;
1341 }
1342
1343 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1344 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1345 close(realfd);
1346 return -1;
1347 }
1348
1349 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1350 * The size passed in is the number of 512 byte sectors in the filesystem.
1351 * So compute the number of whole 4K blocks we should read/write,
1352 * and the remainder.
1353 */
1354 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1355 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001356 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1357 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001358
1359 SLOGE("Encrypting filesystem in place...");
1360
Ken Sumrall29d8da82011-05-18 17:20:07 -07001361 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001362 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001363 /* process the majority of the filesystem in blocks */
1364 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001365 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001366 if (new_pct > cur_pct) {
1367 char buf[8];
1368
1369 cur_pct = new_pct;
1370 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1371 property_set("vold.encrypt_progress", buf);
1372 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1374 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1375 goto errout;
1376 }
1377 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1378 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1379 goto errout;
1380 }
1381 }
1382
1383 /* Do any remaining sectors */
1384 for (i=0; i<remainder; i++) {
1385 if (unix_read(realfd, buf, 512) <= 0) {
1386 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1387 goto errout;
1388 }
1389 if (unix_write(cryptofd, buf, 512) <= 0) {
1390 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1391 goto errout;
1392 }
1393 }
1394
Ken Sumrall29d8da82011-05-18 17:20:07 -07001395 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001396 rc = 0;
1397
1398errout:
1399 close(realfd);
1400 close(cryptofd);
1401
1402 return rc;
1403}
1404
1405#define CRYPTO_ENABLE_WIPE 1
1406#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001407
1408#define FRAMEWORK_BOOT_WAIT 60
1409
Ken Sumrall29d8da82011-05-18 17:20:07 -07001410static inline int should_encrypt(struct volume_info *volume)
1411{
1412 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1413 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1414}
1415
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001416int cryptfs_enable(char *howarg, char *passwd)
1417{
1418 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001419 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001420 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001421 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001422 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001423 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001424 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001425 char tmpfs_options[PROPERTY_VALUE_MAX];
1426 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001427 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001428 char key_loc[PROPERTY_VALUE_MAX];
1429 char fuse_sdcard[PROPERTY_VALUE_MAX];
1430 char *sd_mnt_point;
1431 char sd_blk_dev[256] = { 0 };
1432 int num_vols;
1433 struct volume_info *vol_list = 0;
1434 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001435
1436 property_get("ro.crypto.state", encrypted_state, "");
1437 if (strcmp(encrypted_state, "unencrypted")) {
1438 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001439 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001440 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001442 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001443
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444 if (!strcmp(howarg, "wipe")) {
1445 how = CRYPTO_ENABLE_WIPE;
1446 } else if (! strcmp(howarg, "inplace")) {
1447 how = CRYPTO_ENABLE_INPLACE;
1448 } else {
1449 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001450 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001451 }
1452
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001453 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001454
Ken Sumrall3ed82362011-01-28 23:31:16 -08001455 /* Get the size of the real block device */
1456 fd = open(real_blkdev, O_RDONLY);
1457 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1458 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1459 goto error_unencrypted;
1460 }
1461 close(fd);
1462
1463 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001464 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001465 unsigned int fs_size_sec, max_fs_size_sec;
1466
1467 fs_size_sec = get_fs_size(real_blkdev);
1468 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1469
1470 if (fs_size_sec > max_fs_size_sec) {
1471 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1472 goto error_unencrypted;
1473 }
1474 }
1475
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001476 /* Get a wakelock as this may take a while, and we don't want the
1477 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1478 * wants to keep the screen on, it can grab a full wakelock.
1479 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001480 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001481 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1482
Jeff Sharkey7382f812012-08-23 14:08:59 -07001483 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001484 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001485 if (!sd_mnt_point) {
1486 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1487 }
1488 if (!sd_mnt_point) {
1489 sd_mnt_point = "/mnt/sdcard";
1490 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001491
1492 num_vols=vold_getNumDirectVolumes();
1493 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1494 vold_getDirectVolumeList(vol_list);
1495
1496 for (i=0; i<num_vols; i++) {
1497 if (should_encrypt(&vol_list[i])) {
1498 fd = open(vol_list[i].blk_dev, O_RDONLY);
1499 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1500 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1501 goto error_unencrypted;
1502 }
1503 close(fd);
1504
Ken Sumrall3b170052011-07-11 15:38:57 -07001505 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001506 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1507 /* -2 is returned when the device exists but is not currently mounted.
1508 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001509 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1510 goto error_unencrypted;
1511 }
1512 }
1513 }
1514
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001515 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001516 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001517 */
1518 property_set("vold.decrypt", "trigger_shutdown_framework");
1519 SLOGD("Just asked init to shut down class main\n");
1520
Ken Sumrall425524d2012-06-14 20:55:28 -07001521 if (vold_unmountAllAsecs()) {
1522 /* Just report the error. If any are left mounted,
1523 * umounting /data below will fail and handle the error.
1524 */
1525 SLOGE("Error unmounting internal asecs");
1526 }
1527
Ken Sumrall29d8da82011-05-18 17:20:07 -07001528 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1529 if (!strcmp(fuse_sdcard, "true")) {
1530 /* This is a device using the fuse layer to emulate the sdcard semantics
1531 * on top of the userdata partition. vold does not manage it, it is managed
1532 * by the sdcard service. The sdcard service was killed by the property trigger
1533 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1534 * unlike the case for vold managed devices above.
1535 */
1536 if (wait_and_unmount(sd_mnt_point)) {
1537 goto error_shutting_down;
1538 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001539 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540
1541 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001542 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001543 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001544 }
1545
1546 /* Do extra work for a better UX when doing the long inplace encryption */
1547 if (how == CRYPTO_ENABLE_INPLACE) {
1548 /* Now that /data is unmounted, we need to mount a tmpfs
1549 * /data, set a property saying we're doing inplace encryption,
1550 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001551 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001552 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001553 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001554 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001555 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001556 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001557
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001558 /* restart the framework. */
1559 /* Create necessary paths on /data */
1560 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001561 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562 }
1563
Ken Sumrall92736ef2012-10-17 20:57:14 -07001564 /* Ugh, shutting down the framework is not synchronous, so until it
1565 * can be fixed, this horrible hack will wait a moment for it all to
1566 * shut down before proceeding. Without it, some devices cannot
1567 * restart the graphics services.
1568 */
1569 sleep(2);
1570
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001571 /* startup service classes main and late_start */
1572 property_set("vold.decrypt", "trigger_restart_min_framework");
1573 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001574
Ken Sumrall7df84122011-01-18 14:04:08 -08001575 /* OK, the framework is restarted and will soon be showing a
1576 * progress bar. Time to setup an encrypted mapping, and
1577 * either write a new filesystem, or encrypt in place updating
1578 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001579 */
1580 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001581
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001582 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001583 /* Initialize a crypt_mnt_ftr for the partition */
1584 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001585
Ken Sumrall29d8da82011-05-18 17:20:07 -07001586 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1587 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1588 } else {
1589 crypt_ftr.fs_size = nr_sec;
1590 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001591 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001592 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1593
1594 /* Make an encrypted master key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001595 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001596 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001597 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001598 }
1599
1600 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001601 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001602
Ken Sumrall160b4d62013-04-22 12:15:39 -07001603 /* If any persistent data has been remembered, save it.
1604 * If none, create a valid empty table and save that.
1605 */
1606 if (!persist_data) {
1607 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1608 if (pdata) {
1609 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1610 persist_data = pdata;
1611 }
1612 }
1613 if (persist_data) {
1614 save_persistent_data();
1615 }
1616
1617 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key, decrypted_master_key);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001618 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1619 "userdata");
1620
Ken Sumrall128626f2011-06-28 18:45:14 -07001621 /* The size of the userdata partition, and add in the vold volumes below */
1622 tot_encryption_size = crypt_ftr.fs_size;
1623
Ken Sumrall29d8da82011-05-18 17:20:07 -07001624 /* setup crypto mapping for all encryptable volumes handled by vold */
1625 for (i=0; i<num_vols; i++) {
1626 if (should_encrypt(&vol_list[i])) {
1627 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1628 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1629 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1630 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1631 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001632 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001633 }
1634 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001635
1636 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001637 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1638 /* Encrypt all encryptable volumes handled by vold */
1639 if (!rc) {
1640 for (i=0; i<num_vols; i++) {
1641 if (should_encrypt(&vol_list[i])) {
1642 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1643 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1644 }
1645 }
1646 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001647 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001648 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1649 &cur_encryption_done, tot_encryption_size);
1650 /* Encrypt all encryptable volumes handled by vold */
1651 if (!rc) {
1652 for (i=0; i<num_vols; i++) {
1653 if (should_encrypt(&vol_list[i])) {
1654 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1655 vol_list[i].blk_dev,
1656 vol_list[i].crypt_ftr.fs_size,
1657 &cur_encryption_done, tot_encryption_size);
1658 }
1659 }
1660 }
1661 if (!rc) {
1662 /* The inplace routine never actually sets the progress to 100%
1663 * due to the round down nature of integer division, so set it here */
1664 property_set("vold.encrypt_progress", "100");
1665 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001666 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001667 /* Shouldn't happen */
1668 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001669 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001670 }
1671
1672 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001673 delete_crypto_blk_dev("userdata");
1674 for (i=0; i<num_vols; i++) {
1675 if (should_encrypt(&vol_list[i])) {
1676 delete_crypto_blk_dev(vol_list[i].label);
1677 }
1678 }
1679
1680 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001681
1682 if (! rc) {
1683 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001684
Ken Sumralld33d4172011-02-01 00:49:13 -08001685 /* Clear the encryption in progres flag in the footer */
1686 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001687 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001688
Ken Sumrall29d8da82011-05-18 17:20:07 -07001689 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumrallc290eaf2011-03-07 23:40:35 -08001690 android_reboot(ANDROID_RB_RESTART, 0, 0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001691 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001692 char value[PROPERTY_VALUE_MAX];
1693
Ken Sumrall319369a2012-06-27 16:30:18 -07001694 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001695 if (!strcmp(value, "1")) {
1696 /* wipe data if encryption failed */
1697 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1698 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001699 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001700 if (fd >= 0) {
1701 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1702 close(fd);
1703 } else {
1704 SLOGE("could not open /cache/recovery/command\n");
1705 }
1706 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
1707 } else {
1708 /* set property to trigger dialog */
1709 property_set("vold.encrypt_progress", "error_partially_encrypted");
1710 release_wake_lock(lockid);
1711 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001712 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001713 }
1714
Ken Sumrall3ed82362011-01-28 23:31:16 -08001715 /* hrm, the encrypt step claims success, but the reboot failed.
1716 * This should not happen.
1717 * Set the property and return. Hope the framework can deal with it.
1718 */
1719 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001720 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001721 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001722
1723error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001724 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001725 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001726 if (lockid[0]) {
1727 release_wake_lock(lockid);
1728 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001729 return -1;
1730
1731error_shutting_down:
1732 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1733 * but the framework is stopped and not restarted to show the error, so it's up to
1734 * vold to restart the system.
1735 */
1736 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumrallc290eaf2011-03-07 23:40:35 -08001737 android_reboot(ANDROID_RB_RESTART, 0, 0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001738
1739 /* shouldn't get here */
1740 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001741 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001742 if (lockid[0]) {
1743 release_wake_lock(lockid);
1744 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001745 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001746}
1747
Jason parks70a4b3f2011-01-28 10:10:47 -06001748int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001749{
1750 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001751 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001752
1753 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001754 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001755 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001756 return -1;
1757 }
1758
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001759 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001760 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001761 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001762 return -1;
1763 }
1764
Ken Sumrall160b4d62013-04-22 12:15:39 -07001765 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001766
Jason parks70a4b3f2011-01-28 10:10:47 -06001767 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001768 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001769
1770 return 0;
1771}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001772
1773static int persist_get_key(char *fieldname, char *value)
1774{
1775 unsigned int i;
1776
1777 if (persist_data == NULL) {
1778 return -1;
1779 }
1780 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1781 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1782 /* We found it! */
1783 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1784 return 0;
1785 }
1786 }
1787
1788 return -1;
1789}
1790
1791static int persist_set_key(char *fieldname, char *value, int encrypted)
1792{
1793 unsigned int i;
1794 unsigned int num;
1795 struct crypt_mnt_ftr crypt_ftr;
1796 unsigned int max_persistent_entries;
1797 unsigned int dsize;
1798
1799 if (persist_data == NULL) {
1800 return -1;
1801 }
1802
1803 /* If encrypted, use the values from the crypt_ftr, otherwise
1804 * use the values for the current spec.
1805 */
1806 if (encrypted) {
1807 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1808 return -1;
1809 }
1810 dsize = crypt_ftr.persist_data_size;
1811 } else {
1812 dsize = CRYPT_PERSIST_DATA_SIZE;
1813 }
1814 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1815 sizeof(struct crypt_persist_entry);
1816
1817 num = persist_data->persist_valid_entries;
1818
1819 for (i = 0; i < num; i++) {
1820 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1821 /* We found an existing entry, update it! */
1822 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1823 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1824 return 0;
1825 }
1826 }
1827
1828 /* We didn't find it, add it to the end, if there is room */
1829 if (persist_data->persist_valid_entries < max_persistent_entries) {
1830 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
1831 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
1832 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
1833 persist_data->persist_valid_entries++;
1834 return 0;
1835 }
1836
1837 return -1;
1838}
1839
1840/* Return the value of the specified field. */
1841int cryptfs_getfield(char *fieldname, char *value, int len)
1842{
1843 char temp_value[PROPERTY_VALUE_MAX];
1844 char real_blkdev[MAXPATHLEN];
1845 /* 0 is success, 1 is not encrypted,
1846 * -1 is value not set, -2 is any other error
1847 */
1848 int rc = -2;
1849
1850 if (persist_data == NULL) {
1851 load_persistent_data();
1852 if (persist_data == NULL) {
1853 SLOGE("Getfield error, cannot load persistent data");
1854 goto out;
1855 }
1856 }
1857
1858 if (!persist_get_key(fieldname, temp_value)) {
1859 /* We found it, copy it to the caller's buffer and return */
1860 strlcpy(value, temp_value, len);
1861 rc = 0;
1862 } else {
1863 /* Sadness, it's not there. Return the error */
1864 rc = -1;
1865 }
1866
1867out:
1868 return rc;
1869}
1870
1871/* Set the value of the specified field. */
1872int cryptfs_setfield(char *fieldname, char *value)
1873{
1874 struct crypt_persist_data stored_pdata;
1875 struct crypt_persist_data *pdata_p;
1876 struct crypt_mnt_ftr crypt_ftr;
1877 char encrypted_state[PROPERTY_VALUE_MAX];
1878 /* 0 is success, -1 is an error */
1879 int rc = -1;
1880 int encrypted = 0;
1881
1882 if (persist_data == NULL) {
1883 load_persistent_data();
1884 if (persist_data == NULL) {
1885 SLOGE("Setfield error, cannot load persistent data");
1886 goto out;
1887 }
1888 }
1889
1890 property_get("ro.crypto.state", encrypted_state, "");
1891 if (!strcmp(encrypted_state, "encrypted") ) {
1892 encrypted = 1;
1893 }
1894
1895 if (persist_set_key(fieldname, value, encrypted)) {
1896 goto out;
1897 }
1898
1899 /* If we are running encrypted, save the persistent data now */
1900 if (encrypted) {
1901 if (save_persistent_data()) {
1902 SLOGE("Setfield error, cannot save persistent data");
1903 goto out;
1904 }
1905 }
1906
1907 rc = 0;
1908
1909out:
1910 return rc;
1911}