blob: 2f8381cef4bedb6def607296692dae0b040d7195 [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 Sumrall3ed82362011-01-28 23:31:16 -080038#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070039#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070040#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080041#include "cryptfs.h"
42#define LOG_TAG "Cryptfs"
43#include "cutils/log.h"
44#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070045#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080046#include "hardware_legacy/power.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070047#include "VolumeManager.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048
49#define DM_CRYPT_BUF_SIZE 4096
Ken Sumrall8ddbe402011-01-17 15:26:29 -080050#define DATA_MNT_POINT "/data"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080051
Jason parks70a4b3f2011-01-28 10:10:47 -060052#define HASH_COUNT 2000
53#define KEY_LEN_BYTES 16
54#define IV_LEN_BYTES 16
55
Ken Sumrall29d8da82011-05-18 17:20:07 -070056#define KEY_IN_FOOTER "footer"
57
58#define EXT4_FS 1
59#define FAT_FS 2
60
Ken Sumralle919efe2012-09-29 17:07:41 -070061#define TABLE_LOAD_RETRIES 10
62
Ken Sumrall8f869aa2010-12-03 03:47:09 -080063char *me = "cryptfs";
64
Jason parks70a4b3f2011-01-28 10:10:47 -060065static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070066static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060067static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070068static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080069
70extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080071
Ken Sumralladfba362013-06-04 16:37:52 -070072static void cryptfs_reboot(int recovery)
73{
74 if (recovery) {
75 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
76 } else {
77 property_set(ANDROID_RB_PROPERTY, "reboot");
78 }
79 sleep(20);
80
81 /* Shouldn't get here, reboot should happen before sleep times out */
82 return;
83}
84
Ken Sumrall8f869aa2010-12-03 03:47:09 -080085static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
86{
87 memset(io, 0, dataSize);
88 io->data_size = dataSize;
89 io->data_start = sizeof(struct dm_ioctl);
90 io->version[0] = 4;
91 io->version[1] = 0;
92 io->version[2] = 0;
93 io->flags = flags;
94 if (name) {
95 strncpy(io->name, name, sizeof(io->name));
96 }
97}
98
Ken Sumrall3ed82362011-01-28 23:31:16 -080099static unsigned int get_fs_size(char *dev)
100{
101 int fd, block_size;
102 struct ext4_super_block sb;
103 off64_t len;
104
105 if ((fd = open(dev, O_RDONLY)) < 0) {
106 SLOGE("Cannot open device to get filesystem size ");
107 return 0;
108 }
109
110 if (lseek64(fd, 1024, SEEK_SET) < 0) {
111 SLOGE("Cannot seek to superblock");
112 return 0;
113 }
114
115 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
116 SLOGE("Cannot read superblock");
117 return 0;
118 }
119
120 close(fd);
121
122 block_size = 1024 << sb.s_log_block_size;
123 /* compute length in bytes */
124 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
125
126 /* return length in sectors */
127 return (unsigned int) (len / 512);
128}
129
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800130static unsigned int get_blkdev_size(int fd)
131{
132 unsigned int nr_sec;
133
134 if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
135 nr_sec = 0;
136 }
137
138 return nr_sec;
139}
140
Ken Sumrall160b4d62013-04-22 12:15:39 -0700141static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
142{
143 static int cached_data = 0;
144 static off64_t cached_off = 0;
145 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
146 int fd;
147 char key_loc[PROPERTY_VALUE_MAX];
148 char real_blkdev[PROPERTY_VALUE_MAX];
149 unsigned int nr_sec;
150 int rc = -1;
151
152 if (!cached_data) {
153 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
154
155 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
156 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
157 SLOGE("Cannot open real block device %s\n", real_blkdev);
158 return -1;
159 }
160
161 if ((nr_sec = get_blkdev_size(fd))) {
162 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
163 * encryption info footer and key, and plenty of bytes to spare for future
164 * growth.
165 */
166 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
167 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
168 cached_data = 1;
169 } else {
170 SLOGE("Cannot get size of block device %s\n", real_blkdev);
171 }
172 close(fd);
173 } else {
174 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
175 cached_off = 0;
176 cached_data = 1;
177 }
178 }
179
180 if (cached_data) {
181 if (metadata_fname) {
182 *metadata_fname = cached_metadata_fname;
183 }
184 if (off) {
185 *off = cached_off;
186 }
187 rc = 0;
188 }
189
190 return rc;
191}
192
Ken Sumralle8744072011-01-18 22:01:55 -0800193/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800194 * update the failed mount count but not change the key.
195 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700196static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800197{
198 int fd;
199 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700200 /* starting_off is set to the SEEK_SET offset
201 * where the crypto structure starts
202 */
203 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800204 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700205 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700206 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall3be890f2011-09-14 16:53:46 -0700207 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800208
Ken Sumrall160b4d62013-04-22 12:15:39 -0700209 if (get_crypt_ftr_info(&fname, &starting_off)) {
210 SLOGE("Unable to get crypt_ftr_info\n");
211 return -1;
212 }
213 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700214 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700215 return -1;
216 }
217 if ( (fd = open(fname, O_RDWR)) < 0) {
218 SLOGE("Cannot open footer file %s\n", fname);
219 return -1;
220 }
221
222 /* Seek to the start of the crypt footer */
223 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
224 SLOGE("Cannot seek to real block device footer\n");
225 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800226 }
227
228 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
229 SLOGE("Cannot write real block device footer\n");
230 goto errout;
231 }
232
Ken Sumrall3be890f2011-09-14 16:53:46 -0700233 fstat(fd, &statbuf);
234 /* If the keys are kept on a raw block device, do not try to truncate it. */
235 if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700236 if (ftruncate(fd, 0x4000)) {
Ken Sumrall3be890f2011-09-14 16:53:46 -0700237 SLOGE("Cannot set footer file size\n", fname);
Ken Sumralle8744072011-01-18 22:01:55 -0800238 goto errout;
239 }
240 }
241
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800242 /* Success! */
243 rc = 0;
244
245errout:
246 close(fd);
247 return rc;
248
249}
250
Ken Sumrall160b4d62013-04-22 12:15:39 -0700251static inline int unix_read(int fd, void* buff, int len)
252{
253 return TEMP_FAILURE_RETRY(read(fd, buff, len));
254}
255
256static inline int unix_write(int fd, const void* buff, int len)
257{
258 return TEMP_FAILURE_RETRY(write(fd, buff, len));
259}
260
261static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
262{
263 memset(pdata, 0, len);
264 pdata->persist_magic = PERSIST_DATA_MAGIC;
265 pdata->persist_valid_entries = 0;
266}
267
268/* A routine to update the passed in crypt_ftr to the lastest version.
269 * fd is open read/write on the device that holds the crypto footer and persistent
270 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
271 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
272 */
273static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
274{
275 struct crypt_persist_data *pdata;
276 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
277
278 /* This routine can currently only handle upgrading from 1.0 to 1.1.
279 * Do nothing if the passed structure is not version 1.0
280 */
281
282 if ((crypt_ftr->major_version != 1) && (crypt_ftr->minor_version != 0)) {
283 return;
284 }
285
286 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
287 if (pdata == NULL) {
288 SLOGE("Cannot allocate persisent data\n");
289 return;
290 }
291 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
292
293 /* Need to initialize the persistent data area */
294 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
295 SLOGE("Cannot seek to persisent data offset\n");
296 return;
297 }
298 /* Write all zeros to the first copy, making it invalid */
299 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
300
301 /* Write a valid but empty structure to the second copy */
302 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
303 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
304
305 /* Update the footer */
306 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
307 crypt_ftr->persist_data_offset[0] = pdata_offset;
308 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
309 crypt_ftr->minor_version = 1;
310 if (lseek64(fd, offset, SEEK_SET) == -1) {
311 SLOGE("Cannot seek to crypt footer\n");
312 return;
313 }
314 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
315}
316
317
318static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800319{
320 int fd;
321 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700322 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800323 int rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700324 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700325 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700326 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800327
Ken Sumrall160b4d62013-04-22 12:15:39 -0700328 if (get_crypt_ftr_info(&fname, &starting_off)) {
329 SLOGE("Unable to get crypt_ftr_info\n");
330 return -1;
331 }
332 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700333 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700334 return -1;
335 }
336 if ( (fd = open(fname, O_RDWR)) < 0) {
337 SLOGE("Cannot open footer file %s\n", fname);
338 return -1;
339 }
340
341 /* Make sure it's 16 Kbytes in length */
342 fstat(fd, &statbuf);
343 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
344 SLOGE("footer file %s is not the expected size!\n", fname);
345 goto errout;
346 }
347
348 /* Seek to the start of the crypt footer */
349 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
350 SLOGE("Cannot seek to real block device footer\n");
351 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800352 }
353
354 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
355 SLOGE("Cannot read real block device footer\n");
356 goto errout;
357 }
358
359 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700360 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800361 goto errout;
362 }
363
364 if (crypt_ftr->major_version != 1) {
365 SLOGE("Cannot understand major version %d real block device footer\n",
366 crypt_ftr->major_version);
367 goto errout;
368 }
369
Ken Sumrall160b4d62013-04-22 12:15:39 -0700370 if ((crypt_ftr->minor_version != 0) && (crypt_ftr->minor_version != 1)) {
371 SLOGW("Warning: crypto footer minor version %d, expected 0 or 1, continuing...\n",
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800372 crypt_ftr->minor_version);
373 }
374
Ken Sumrall160b4d62013-04-22 12:15:39 -0700375 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
376 * copy on disk before returning.
377 */
378 if (crypt_ftr->minor_version == 0) {
379 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800380 }
381
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800382 /* Success! */
383 rc = 0;
384
385errout:
386 close(fd);
387 return rc;
388}
389
Ken Sumrall160b4d62013-04-22 12:15:39 -0700390static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
391{
392 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
393 crypt_ftr->persist_data_offset[1]) {
394 SLOGE("Crypt_ftr persist data regions overlap");
395 return -1;
396 }
397
398 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
399 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
400 return -1;
401 }
402
403 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
404 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
405 CRYPT_FOOTER_OFFSET) {
406 SLOGE("Persistent data extends past crypto footer");
407 return -1;
408 }
409
410 return 0;
411}
412
413static int load_persistent_data(void)
414{
415 struct crypt_mnt_ftr crypt_ftr;
416 struct crypt_persist_data *pdata = NULL;
417 char encrypted_state[PROPERTY_VALUE_MAX];
418 char *fname;
419 int found = 0;
420 int fd;
421 int ret;
422 int i;
423
424 if (persist_data) {
425 /* Nothing to do, we've already loaded or initialized it */
426 return 0;
427 }
428
429
430 /* If not encrypted, just allocate an empty table and initialize it */
431 property_get("ro.crypto.state", encrypted_state, "");
432 if (strcmp(encrypted_state, "encrypted") ) {
433 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
434 if (pdata) {
435 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
436 persist_data = pdata;
437 return 0;
438 }
439 return -1;
440 }
441
442 if(get_crypt_ftr_and_key(&crypt_ftr)) {
443 return -1;
444 }
445
446 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
447 SLOGE("Crypt_ftr version doesn't support persistent data");
448 return -1;
449 }
450
451 if (get_crypt_ftr_info(&fname, NULL)) {
452 return -1;
453 }
454
455 ret = validate_persistent_data_storage(&crypt_ftr);
456 if (ret) {
457 return -1;
458 }
459
460 fd = open(fname, O_RDONLY);
461 if (fd < 0) {
462 SLOGE("Cannot open %s metadata file", fname);
463 return -1;
464 }
465
466 if (persist_data == NULL) {
467 pdata = malloc(crypt_ftr.persist_data_size);
468 if (pdata == NULL) {
469 SLOGE("Cannot allocate memory for persistent data");
470 goto err;
471 }
472 }
473
474 for (i = 0; i < 2; i++) {
475 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
476 SLOGE("Cannot seek to read persistent data on %s", fname);
477 goto err2;
478 }
479 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
480 SLOGE("Error reading persistent data on iteration %d", i);
481 goto err2;
482 }
483 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
484 found = 1;
485 break;
486 }
487 }
488
489 if (!found) {
490 SLOGI("Could not find valid persistent data, creating");
491 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
492 }
493
494 /* Success */
495 persist_data = pdata;
496 close(fd);
497 return 0;
498
499err2:
500 free(pdata);
501
502err:
503 close(fd);
504 return -1;
505}
506
507static int save_persistent_data(void)
508{
509 struct crypt_mnt_ftr crypt_ftr;
510 struct crypt_persist_data *pdata;
511 char *fname;
512 off64_t write_offset;
513 off64_t erase_offset;
514 int found = 0;
515 int fd;
516 int ret;
517
518 if (persist_data == NULL) {
519 SLOGE("No persistent data to save");
520 return -1;
521 }
522
523 if(get_crypt_ftr_and_key(&crypt_ftr)) {
524 return -1;
525 }
526
527 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
528 SLOGE("Crypt_ftr version doesn't support persistent data");
529 return -1;
530 }
531
532 ret = validate_persistent_data_storage(&crypt_ftr);
533 if (ret) {
534 return -1;
535 }
536
537 if (get_crypt_ftr_info(&fname, NULL)) {
538 return -1;
539 }
540
541 fd = open(fname, O_RDWR);
542 if (fd < 0) {
543 SLOGE("Cannot open %s metadata file", fname);
544 return -1;
545 }
546
547 pdata = malloc(crypt_ftr.persist_data_size);
548 if (pdata == NULL) {
549 SLOGE("Cannot allocate persistant data");
550 goto err;
551 }
552
553 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
554 SLOGE("Cannot seek to read persistent data on %s", fname);
555 goto err2;
556 }
557
558 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
559 SLOGE("Error reading persistent data before save");
560 goto err2;
561 }
562
563 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
564 /* The first copy is the curent valid copy, so write to
565 * the second copy and erase this one */
566 write_offset = crypt_ftr.persist_data_offset[1];
567 erase_offset = crypt_ftr.persist_data_offset[0];
568 } else {
569 /* The second copy must be the valid copy, so write to
570 * the first copy, and erase the second */
571 write_offset = crypt_ftr.persist_data_offset[0];
572 erase_offset = crypt_ftr.persist_data_offset[1];
573 }
574
575 /* Write the new copy first, if successful, then erase the old copy */
576 if (lseek(fd, write_offset, SEEK_SET) < 0) {
577 SLOGE("Cannot seek to write persistent data");
578 goto err2;
579 }
580 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
581 (int) crypt_ftr.persist_data_size) {
582 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
583 SLOGE("Cannot seek to erase previous persistent data");
584 goto err2;
585 }
586 fsync(fd);
587 memset(pdata, 0, crypt_ftr.persist_data_size);
588 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
589 (int) crypt_ftr.persist_data_size) {
590 SLOGE("Cannot write to erase previous persistent data");
591 goto err2;
592 }
593 fsync(fd);
594 } else {
595 SLOGE("Cannot write to save persistent data");
596 goto err2;
597 }
598
599 /* Success */
600 free(pdata);
601 close(fd);
602 return 0;
603
604err2:
605 free(pdata);
606err:
607 close(fd);
608 return -1;
609}
610
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800611/* Convert a binary key of specified length into an ascii hex string equivalent,
612 * without the leading 0x and with null termination
613 */
614void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
615 char *master_key_ascii)
616{
617 unsigned int i, a;
618 unsigned char nibble;
619
620 for (i=0, a=0; i<keysize; i++, a+=2) {
621 /* For each byte, write out two ascii hex digits */
622 nibble = (master_key[i] >> 4) & 0xf;
623 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
624
625 nibble = master_key[i] & 0xf;
626 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
627 }
628
629 /* Add the null termination */
630 master_key_ascii[a] = '\0';
631
632}
633
Ken Sumralldb5e0262013-02-05 17:39:48 -0800634static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
635 char *real_blk_name, const char *name, int fd,
636 char *extra_params)
637{
638 char buffer[DM_CRYPT_BUF_SIZE];
639 struct dm_ioctl *io;
640 struct dm_target_spec *tgt;
641 char *crypt_params;
642 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
643 int i;
644
645 io = (struct dm_ioctl *) buffer;
646
647 /* Load the mapping table for this device */
648 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
649
650 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
651 io->target_count = 1;
652 tgt->status = 0;
653 tgt->sector_start = 0;
654 tgt->length = crypt_ftr->fs_size;
655 strcpy(tgt->target_type, "crypt");
656
657 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
658 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
659 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
660 master_key_ascii, real_blk_name, extra_params);
661 crypt_params += strlen(crypt_params) + 1;
662 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
663 tgt->next = crypt_params - buffer;
664
665 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
666 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
667 break;
668 }
669 usleep(500000);
670 }
671
672 if (i == TABLE_LOAD_RETRIES) {
673 /* We failed to load the table, return an error */
674 return -1;
675 } else {
676 return i + 1;
677 }
678}
679
680
681static int get_dm_crypt_version(int fd, const char *name, int *version)
682{
683 char buffer[DM_CRYPT_BUF_SIZE];
684 struct dm_ioctl *io;
685 struct dm_target_versions *v;
686 int i;
687
688 io = (struct dm_ioctl *) buffer;
689
690 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
691
692 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
693 return -1;
694 }
695
696 /* Iterate over the returned versions, looking for name of "crypt".
697 * When found, get and return the version.
698 */
699 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
700 while (v->next) {
701 if (! strcmp(v->name, "crypt")) {
702 /* We found the crypt driver, return the version, and get out */
703 version[0] = v->version[0];
704 version[1] = v->version[1];
705 version[2] = v->version[2];
706 return 0;
707 }
708 v = (struct dm_target_versions *)(((char *)v) + v->next);
709 }
710
711 return -1;
712}
713
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800714static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700715 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800716{
717 char buffer[DM_CRYPT_BUF_SIZE];
718 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
719 char *crypt_params;
720 struct dm_ioctl *io;
721 struct dm_target_spec *tgt;
722 unsigned int minor;
723 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700724 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800725 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800726 int version[3];
727 char *extra_params;
728 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800729
730 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
731 SLOGE("Cannot open device-mapper\n");
732 goto errout;
733 }
734
735 io = (struct dm_ioctl *) buffer;
736
737 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
738 if (ioctl(fd, DM_DEV_CREATE, io)) {
739 SLOGE("Cannot create dm-crypt device\n");
740 goto errout;
741 }
742
743 /* Get the device status, in particular, the name of it's device file */
744 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
745 if (ioctl(fd, DM_DEV_STATUS, io)) {
746 SLOGE("Cannot retrieve dm-crypt device status\n");
747 goto errout;
748 }
749 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
750 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
751
Ken Sumralldb5e0262013-02-05 17:39:48 -0800752 extra_params = "";
753 if (! get_dm_crypt_version(fd, name, version)) {
754 /* Support for allow_discards was added in version 1.11.0 */
755 if ((version[0] >= 2) ||
756 ((version[0] == 1) && (version[1] >= 11))) {
757 extra_params = "1 allow_discards";
758 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
759 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700760 }
761
Ken Sumralldb5e0262013-02-05 17:39:48 -0800762 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
763 fd, extra_params);
764 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800765 SLOGE("Cannot load dm-crypt mapping table.\n");
766 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800767 } else if (load_count > 1) {
768 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800769 }
770
771 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800772 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800773
774 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
775 SLOGE("Cannot resume the dm-crypt device\n");
776 goto errout;
777 }
778
779 /* We made it here with no errors. Woot! */
780 retval = 0;
781
782errout:
783 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
784
785 return retval;
786}
787
Ken Sumrall29d8da82011-05-18 17:20:07 -0700788static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800789{
790 int fd;
791 char buffer[DM_CRYPT_BUF_SIZE];
792 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800793 int retval = -1;
794
795 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
796 SLOGE("Cannot open device-mapper\n");
797 goto errout;
798 }
799
800 io = (struct dm_ioctl *) buffer;
801
802 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
803 if (ioctl(fd, DM_DEV_REMOVE, io)) {
804 SLOGE("Cannot remove dm-crypt device\n");
805 goto errout;
806 }
807
808 /* We made it here with no errors. Woot! */
809 retval = 0;
810
811errout:
812 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
813
814 return retval;
815
816}
817
Ken Sumralle8744072011-01-18 22:01:55 -0800818static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800819{
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800820 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800821 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800822 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800823}
824
Ken Sumralle8744072011-01-18 22:01:55 -0800825static int encrypt_master_key(char *passwd, unsigned char *salt,
826 unsigned char *decrypted_master_key,
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800827 unsigned char *encrypted_master_key)
828{
829 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
830 EVP_CIPHER_CTX e_ctx;
831 int encrypted_len, final_len;
832
833 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800834 pbkdf2(passwd, salt, ikey);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800835
836 /* Initialize the decryption engine */
837 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
838 SLOGE("EVP_EncryptInit failed\n");
839 return -1;
840 }
841 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800842
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800843 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800844 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
845 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800846 SLOGE("EVP_EncryptUpdate failed\n");
847 return -1;
848 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800849 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800850 SLOGE("EVP_EncryptFinal failed\n");
851 return -1;
852 }
853
854 if (encrypted_len + final_len != KEY_LEN_BYTES) {
855 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
856 return -1;
857 } else {
858 return 0;
859 }
860}
861
Ken Sumralle8744072011-01-18 22:01:55 -0800862static int decrypt_master_key(char *passwd, unsigned char *salt,
863 unsigned char *encrypted_master_key,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800864 unsigned char *decrypted_master_key)
865{
866 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 -0800867 EVP_CIPHER_CTX d_ctx;
868 int decrypted_len, final_len;
869
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800870 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800871 pbkdf2(passwd, salt, ikey);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800872
873 /* Initialize the decryption engine */
874 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
875 return -1;
876 }
877 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
878 /* Decrypt the master key */
879 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
880 encrypted_master_key, KEY_LEN_BYTES)) {
881 return -1;
882 }
883 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
884 return -1;
885 }
886
887 if (decrypted_len + final_len != KEY_LEN_BYTES) {
888 return -1;
889 } else {
890 return 0;
891 }
892}
893
Ken Sumralle8744072011-01-18 22:01:55 -0800894static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800895{
896 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800897 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800898 EVP_CIPHER_CTX e_ctx;
899 int encrypted_len, final_len;
900
901 /* Get some random bits for a key */
902 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -0800903 read(fd, key_buf, sizeof(key_buf));
904 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800905 close(fd);
906
907 /* Now encrypt it with the password */
Ken Sumralle8744072011-01-18 22:01:55 -0800908 return encrypt_master_key(passwd, salt, key_buf, master_key);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800909}
910
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800911static int wait_and_unmount(char *mountpoint)
912{
913 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -0800914#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800915
916 /* Now umount the tmpfs filesystem */
917 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
918 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700919 if (errno == EINVAL) {
920 /* EINVAL is returned if the directory is not a mountpoint,
921 * i.e. there is no filesystem mounted there. So just get out.
922 */
923 break;
924 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800925 sleep(1);
926 i++;
927 } else {
928 break;
929 }
930 }
931
932 if (i < WAIT_UNMOUNT_COUNT) {
933 SLOGD("unmounting %s succeeded\n", mountpoint);
934 rc = 0;
935 } else {
936 SLOGE("unmounting %s failed\n", mountpoint);
937 rc = -1;
938 }
939
940 return rc;
941}
942
Ken Sumrallc5872692013-05-14 15:26:31 -0700943#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800944static int prep_data_fs(void)
945{
946 int i;
947
948 /* Do the prep of the /data filesystem */
949 property_set("vold.post_fs_data_done", "0");
950 property_set("vold.decrypt", "trigger_post_fs_data");
951 SLOGD("Just triggered post_fs_data\n");
952
Ken Sumrallc5872692013-05-14 15:26:31 -0700953 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800954 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700955 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800956
957 property_get("vold.post_fs_data_done", p, "0");
958 if (*p == '1') {
959 break;
960 } else {
961 usleep(250000);
962 }
963 }
964 if (i == DATA_PREP_TIMEOUT) {
965 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -0700966 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800967 return -1;
968 } else {
969 SLOGD("post_fs_data done\n");
970 return 0;
971 }
972}
973
Ken Sumrall6864b7e2011-01-14 15:20:02 -0800974int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800975{
976 char fs_type[32];
977 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -0800978 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800979 char fs_options[256];
980 unsigned long mnt_flags;
981 struct stat statbuf;
982 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -0800983 static int restart_successful = 0;
984
985 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -0600986 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -0800987 SLOGE("Encrypted filesystem not validated, aborting");
988 return -1;
989 }
990
991 if (restart_successful) {
992 SLOGE("System already restarted with encrypted disk, aborting");
993 return -1;
994 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800995
996 /* Here is where we shut down the framework. The init scripts
997 * start all services in one of three classes: core, main or late_start.
998 * On boot, we start core and main. Now, we stop main, but not core,
999 * as core includes vold and a few other really important things that
1000 * we need to keep running. Once main has stopped, we should be able
1001 * to umount the tmpfs /data, then mount the encrypted /data.
1002 * We then restart the class main, and also the class late_start.
1003 * At the moment, I've only put a few things in late_start that I know
1004 * are not needed to bring up the framework, and that also cause problems
1005 * with unmounting the tmpfs /data, but I hope to add add more services
1006 * to the late_start class as we optimize this to decrease the delay
1007 * till the user is asked for the password to the filesystem.
1008 */
1009
1010 /* The init files are setup to stop the class main when vold.decrypt is
1011 * set to trigger_reset_main.
1012 */
1013 property_set("vold.decrypt", "trigger_reset_main");
1014 SLOGD("Just asked init to shut down class main\n");
1015
Ken Sumrall92736ef2012-10-17 20:57:14 -07001016 /* Ugh, shutting down the framework is not synchronous, so until it
1017 * can be fixed, this horrible hack will wait a moment for it all to
1018 * shut down before proceeding. Without it, some devices cannot
1019 * restart the graphics services.
1020 */
1021 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001022
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001023 /* Now that the framework is shutdown, we should be able to umount()
1024 * the tmpfs filesystem, and mount the real one.
1025 */
1026
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001027 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1028 if (strlen(crypto_blkdev) == 0) {
1029 SLOGE("fs_crypto_blkdev not set\n");
1030 return -1;
1031 }
1032
Ken Sumralle5032c42012-04-01 23:58:44 -07001033 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1034 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001035 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001036
Ken Sumralle5032c42012-04-01 23:58:44 -07001037 property_set("vold.decrypt", "trigger_load_persist_props");
1038 /* Create necessary paths on /data */
1039 if (prep_data_fs()) {
1040 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001041 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001042
1043 /* startup service classes main and late_start */
1044 property_set("vold.decrypt", "trigger_restart_framework");
1045 SLOGD("Just triggered restart_framework\n");
1046
1047 /* Give it a few moments to get started */
1048 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001049 }
1050
Ken Sumrall0cc16632011-01-18 20:32:26 -08001051 if (rc == 0) {
1052 restart_successful = 1;
1053 }
1054
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001055 return rc;
1056}
1057
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001058static int do_crypto_complete(char *mount_point)
1059{
1060 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001061 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001062 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001063
1064 property_get("ro.crypto.state", encrypted_state, "");
1065 if (strcmp(encrypted_state, "encrypted") ) {
1066 SLOGE("not running with encryption, aborting");
1067 return 1;
1068 }
1069
Ken Sumrall160b4d62013-04-22 12:15:39 -07001070 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001071 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001072
Ken Sumralle1a45852011-12-14 21:24:27 -08001073 /*
1074 * Only report this error if key_loc is a file and it exists.
1075 * If the device was never encrypted, and /data is not mountable for
1076 * some reason, returning 1 should prevent the UI from presenting the
1077 * a "enter password" screen, or worse, a "press button to wipe the
1078 * device" screen.
1079 */
1080 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1081 SLOGE("master key file does not exist, aborting");
1082 return 1;
1083 } else {
1084 SLOGE("Error getting crypt footer and key\n");
1085 return -1;
1086 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001087 }
1088
1089 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1090 SLOGE("Encryption process didn't finish successfully\n");
1091 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1092 * and give the user an option to wipe the disk */
1093 }
1094
1095 /* We passed the test! We shall diminish, and return to the west */
1096 return 0;
1097}
1098
Ken Sumrall29d8da82011-05-18 17:20:07 -07001099static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001100{
1101 struct crypt_mnt_ftr crypt_ftr;
1102 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001103 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001104 char crypto_blkdev[MAXPATHLEN];
1105 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001107 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001108 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109 int rc;
1110
Ken Sumrall0cc16632011-01-18 20:32:26 -08001111 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001112 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001113 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1114 return -1;
1115 }
1116
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001117 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118
Ken Sumrall160b4d62013-04-22 12:15:39 -07001119 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120 SLOGE("Error getting crypt footer and key\n");
1121 return -1;
1122 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001123
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001124 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1125 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1126
1127 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001128 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key, decrypted_master_key);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129 }
1130
1131 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001132 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001133 SLOGE("Error creating decrypted block device\n");
1134 return -1;
1135 }
1136
Alex Klyubin707795a2013-05-10 15:17:07 -07001137 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001138 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1139 * files and passes that data to me */
1140 /* Create a tmp mount point to try mounting the decryptd fs
1141 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1142 * a directory in it to test mount the decrypted filesystem.
1143 */
1144 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1145 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001146 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001147 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001148 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 crypt_ftr.failed_decrypt_count++;
1150 } else {
1151 /* Success, so just umount and we'll mount it properly when we restart
1152 * the framework.
1153 */
1154 umount(tmp_mount_point);
1155 crypt_ftr.failed_decrypt_count = 0;
1156 }
1157
1158 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001159 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001160 }
1161
1162 if (crypt_ftr.failed_decrypt_count) {
1163 /* We failed to mount the device, so return an error */
1164 rc = crypt_ftr.failed_decrypt_count;
1165
1166 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001167 /* Woot! Success! Save the name of the crypto block device
1168 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001169 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001170 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001171
1172 /* Also save a the master key so we can reencrypted the key
1173 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001174 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001175 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001176 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001177 master_key_saved = 1;
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001178 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001179 }
1180
1181 return rc;
1182}
1183
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001184/* Called by vold when it wants to undo the crypto mapping of a volume it
1185 * manages. This is usually in response to a factory reset, when we want
1186 * to undo the crypto mapping so the volume is formatted in the clear.
1187 */
1188int cryptfs_revert_volume(const char *label)
1189{
1190 return delete_crypto_blk_dev((char *)label);
1191}
1192
Ken Sumrall29d8da82011-05-18 17:20:07 -07001193/*
1194 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1195 * Setup a dm-crypt mapping, use the saved master key from
1196 * setting up the /data mapping, and return the new device path.
1197 */
1198int cryptfs_setup_volume(const char *label, int major, int minor,
1199 char *crypto_sys_path, unsigned int max_path,
1200 int *new_major, int *new_minor)
1201{
1202 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1203 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001204 struct stat statbuf;
1205 int nr_sec, fd;
1206
1207 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1208
Ken Sumrall160b4d62013-04-22 12:15:39 -07001209 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001210
1211 /* Update the fs_size field to be the size of the volume */
1212 fd = open(real_blkdev, O_RDONLY);
1213 nr_sec = get_blkdev_size(fd);
1214 close(fd);
1215 if (nr_sec == 0) {
1216 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1217 return -1;
1218 }
1219
1220 sd_crypt_ftr.fs_size = nr_sec;
1221 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1222 crypto_blkdev, label);
1223
1224 stat(crypto_blkdev, &statbuf);
1225 *new_major = MAJOR(statbuf.st_rdev);
1226 *new_minor = MINOR(statbuf.st_rdev);
1227
1228 /* Create path to sys entry for this block device */
1229 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1230
1231 return 0;
1232}
1233
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001234int cryptfs_crypto_complete(void)
1235{
1236 return do_crypto_complete("/data");
1237}
1238
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001239int cryptfs_check_passwd(char *passwd)
1240{
1241 int rc = -1;
1242
Ken Sumrall29d8da82011-05-18 17:20:07 -07001243 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244
1245 return rc;
1246}
1247
Ken Sumrall3ad90722011-10-04 20:38:29 -07001248int cryptfs_verify_passwd(char *passwd)
1249{
1250 struct crypt_mnt_ftr crypt_ftr;
1251 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001252 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001253 char encrypted_state[PROPERTY_VALUE_MAX];
1254 int rc;
1255
1256 property_get("ro.crypto.state", encrypted_state, "");
1257 if (strcmp(encrypted_state, "encrypted") ) {
1258 SLOGE("device not encrypted, aborting");
1259 return -2;
1260 }
1261
1262 if (!master_key_saved) {
1263 SLOGE("encrypted fs not yet mounted, aborting");
1264 return -1;
1265 }
1266
1267 if (!saved_mount_point) {
1268 SLOGE("encrypted fs failed to save mount point, aborting");
1269 return -1;
1270 }
1271
Ken Sumrall160b4d62013-04-22 12:15:39 -07001272 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001273 SLOGE("Error getting crypt footer and key\n");
1274 return -1;
1275 }
1276
1277 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1278 /* If the device has no password, then just say the password is valid */
1279 rc = 0;
1280 } else {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001281 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key,
1282 decrypted_master_key);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001283 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1284 /* They match, the password is correct */
1285 rc = 0;
1286 } else {
1287 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1288 sleep(1);
1289 rc = 1;
1290 }
1291 }
1292
1293 return rc;
1294}
1295
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296/* Initialize a crypt_mnt_ftr structure. The keysize is
1297 * defaulted to 16 bytes, and the filesystem size to 0.
1298 * Presumably, at a minimum, the caller will update the
1299 * filesystem size and crypto_type_name after calling this function.
1300 */
1301static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1302{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001303 off64_t off;
1304
1305 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306 ftr->magic = CRYPT_MNT_MAGIC;
1307 ftr->major_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001308 ftr->minor_version = 1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001309 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001310 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001311
1312 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1313 if (get_crypt_ftr_info(NULL, &off) == 0) {
1314 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1315 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1316 ftr->persist_data_size;
1317 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001318}
1319
Ken Sumrall29d8da82011-05-18 17:20:07 -07001320static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001321{
1322 char cmdline[256];
1323 int rc = -1;
1324
Ken Sumrall29d8da82011-05-18 17:20:07 -07001325 if (type == EXT4_FS) {
1326 snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
1327 size * 512, crypto_blkdev);
1328 SLOGI("Making empty filesystem with command %s\n", cmdline);
1329 } else if (type== FAT_FS) {
1330 snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
1331 size, crypto_blkdev);
1332 SLOGI("Making empty filesystem with command %s\n", cmdline);
1333 } else {
1334 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1335 return -1;
1336 }
1337
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001338 if (system(cmdline)) {
1339 SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
1340 } else {
1341 SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
1342 rc = 0;
1343 }
1344
1345 return rc;
1346}
1347
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001348#define CRYPT_INPLACE_BUFSIZE 4096
1349#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001350static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1351 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001352{
1353 int realfd, cryptofd;
1354 char *buf[CRYPT_INPLACE_BUFSIZE];
1355 int rc = -1;
1356 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001357 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001358 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001359
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001360 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1361 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1362 return -1;
1363 }
1364
1365 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1366 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1367 close(realfd);
1368 return -1;
1369 }
1370
1371 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1372 * The size passed in is the number of 512 byte sectors in the filesystem.
1373 * So compute the number of whole 4K blocks we should read/write,
1374 * and the remainder.
1375 */
1376 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1377 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001378 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1379 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001380
1381 SLOGE("Encrypting filesystem in place...");
1382
Ken Sumrall29d8da82011-05-18 17:20:07 -07001383 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001384 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001385 /* process the majority of the filesystem in blocks */
1386 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001387 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001388 if (new_pct > cur_pct) {
1389 char buf[8];
1390
1391 cur_pct = new_pct;
1392 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1393 property_set("vold.encrypt_progress", buf);
1394 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001395 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1396 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1397 goto errout;
1398 }
1399 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1400 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1401 goto errout;
1402 }
1403 }
1404
1405 /* Do any remaining sectors */
1406 for (i=0; i<remainder; i++) {
1407 if (unix_read(realfd, buf, 512) <= 0) {
1408 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1409 goto errout;
1410 }
1411 if (unix_write(cryptofd, buf, 512) <= 0) {
1412 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1413 goto errout;
1414 }
1415 }
1416
Ken Sumrall29d8da82011-05-18 17:20:07 -07001417 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418 rc = 0;
1419
1420errout:
1421 close(realfd);
1422 close(cryptofd);
1423
1424 return rc;
1425}
1426
1427#define CRYPTO_ENABLE_WIPE 1
1428#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001429
1430#define FRAMEWORK_BOOT_WAIT 60
1431
Ken Sumrall29d8da82011-05-18 17:20:07 -07001432static inline int should_encrypt(struct volume_info *volume)
1433{
1434 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1435 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1436}
1437
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001438int cryptfs_enable(char *howarg, char *passwd)
1439{
1440 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001441 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001442 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001443 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001444 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001445 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001446 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001447 char tmpfs_options[PROPERTY_VALUE_MAX];
1448 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001449 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001450 char key_loc[PROPERTY_VALUE_MAX];
1451 char fuse_sdcard[PROPERTY_VALUE_MAX];
1452 char *sd_mnt_point;
1453 char sd_blk_dev[256] = { 0 };
1454 int num_vols;
1455 struct volume_info *vol_list = 0;
1456 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001457
1458 property_get("ro.crypto.state", encrypted_state, "");
1459 if (strcmp(encrypted_state, "unencrypted")) {
1460 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001461 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001462 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001463
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001464 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001465
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001466 if (!strcmp(howarg, "wipe")) {
1467 how = CRYPTO_ENABLE_WIPE;
1468 } else if (! strcmp(howarg, "inplace")) {
1469 how = CRYPTO_ENABLE_INPLACE;
1470 } else {
1471 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001472 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001473 }
1474
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001475 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001476
Ken Sumrall3ed82362011-01-28 23:31:16 -08001477 /* Get the size of the real block device */
1478 fd = open(real_blkdev, O_RDONLY);
1479 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1480 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1481 goto error_unencrypted;
1482 }
1483 close(fd);
1484
1485 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001486 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001487 unsigned int fs_size_sec, max_fs_size_sec;
1488
1489 fs_size_sec = get_fs_size(real_blkdev);
1490 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1491
1492 if (fs_size_sec > max_fs_size_sec) {
1493 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1494 goto error_unencrypted;
1495 }
1496 }
1497
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001498 /* Get a wakelock as this may take a while, and we don't want the
1499 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1500 * wants to keep the screen on, it can grab a full wakelock.
1501 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001502 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001503 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1504
Jeff Sharkey7382f812012-08-23 14:08:59 -07001505 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001506 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001507 if (!sd_mnt_point) {
1508 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1509 }
1510 if (!sd_mnt_point) {
1511 sd_mnt_point = "/mnt/sdcard";
1512 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001513
1514 num_vols=vold_getNumDirectVolumes();
1515 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1516 vold_getDirectVolumeList(vol_list);
1517
1518 for (i=0; i<num_vols; i++) {
1519 if (should_encrypt(&vol_list[i])) {
1520 fd = open(vol_list[i].blk_dev, O_RDONLY);
1521 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1522 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1523 goto error_unencrypted;
1524 }
1525 close(fd);
1526
Ken Sumrall3b170052011-07-11 15:38:57 -07001527 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001528 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1529 /* -2 is returned when the device exists but is not currently mounted.
1530 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001531 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1532 goto error_unencrypted;
1533 }
1534 }
1535 }
1536
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001537 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001538 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539 */
1540 property_set("vold.decrypt", "trigger_shutdown_framework");
1541 SLOGD("Just asked init to shut down class main\n");
1542
Ken Sumrall425524d2012-06-14 20:55:28 -07001543 if (vold_unmountAllAsecs()) {
1544 /* Just report the error. If any are left mounted,
1545 * umounting /data below will fail and handle the error.
1546 */
1547 SLOGE("Error unmounting internal asecs");
1548 }
1549
Ken Sumrall29d8da82011-05-18 17:20:07 -07001550 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1551 if (!strcmp(fuse_sdcard, "true")) {
1552 /* This is a device using the fuse layer to emulate the sdcard semantics
1553 * on top of the userdata partition. vold does not manage it, it is managed
1554 * by the sdcard service. The sdcard service was killed by the property trigger
1555 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1556 * unlike the case for vold managed devices above.
1557 */
1558 if (wait_and_unmount(sd_mnt_point)) {
1559 goto error_shutting_down;
1560 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001561 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562
1563 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001564 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001565 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001566 }
1567
1568 /* Do extra work for a better UX when doing the long inplace encryption */
1569 if (how == CRYPTO_ENABLE_INPLACE) {
1570 /* Now that /data is unmounted, we need to mount a tmpfs
1571 * /data, set a property saying we're doing inplace encryption,
1572 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001573 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001574 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001575 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001576 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001577 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001578 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001579
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001580 /* restart the framework. */
1581 /* Create necessary paths on /data */
1582 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001583 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 }
1585
Ken Sumrall92736ef2012-10-17 20:57:14 -07001586 /* Ugh, shutting down the framework is not synchronous, so until it
1587 * can be fixed, this horrible hack will wait a moment for it all to
1588 * shut down before proceeding. Without it, some devices cannot
1589 * restart the graphics services.
1590 */
1591 sleep(2);
1592
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001593 /* startup service classes main and late_start */
1594 property_set("vold.decrypt", "trigger_restart_min_framework");
1595 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596
Ken Sumrall7df84122011-01-18 14:04:08 -08001597 /* OK, the framework is restarted and will soon be showing a
1598 * progress bar. Time to setup an encrypted mapping, and
1599 * either write a new filesystem, or encrypt in place updating
1600 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001601 */
1602 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001603
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001604 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001605 /* Initialize a crypt_mnt_ftr for the partition */
1606 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001607
Ken Sumrall29d8da82011-05-18 17:20:07 -07001608 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1609 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1610 } else {
1611 crypt_ftr.fs_size = nr_sec;
1612 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001613 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001614 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1615
1616 /* Make an encrypted master key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001617 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001618 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001619 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001620 }
1621
1622 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001623 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001624
Ken Sumrall160b4d62013-04-22 12:15:39 -07001625 /* If any persistent data has been remembered, save it.
1626 * If none, create a valid empty table and save that.
1627 */
1628 if (!persist_data) {
1629 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1630 if (pdata) {
1631 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1632 persist_data = pdata;
1633 }
1634 }
1635 if (persist_data) {
1636 save_persistent_data();
1637 }
1638
1639 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key, decrypted_master_key);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001640 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1641 "userdata");
1642
Ken Sumrall128626f2011-06-28 18:45:14 -07001643 /* The size of the userdata partition, and add in the vold volumes below */
1644 tot_encryption_size = crypt_ftr.fs_size;
1645
Ken Sumrall29d8da82011-05-18 17:20:07 -07001646 /* setup crypto mapping for all encryptable volumes handled by vold */
1647 for (i=0; i<num_vols; i++) {
1648 if (should_encrypt(&vol_list[i])) {
1649 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1650 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1651 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1652 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1653 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001654 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001655 }
1656 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001657
1658 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001659 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1660 /* Encrypt all encryptable volumes handled by vold */
1661 if (!rc) {
1662 for (i=0; i<num_vols; i++) {
1663 if (should_encrypt(&vol_list[i])) {
1664 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1665 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1666 }
1667 }
1668 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001669 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001670 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1671 &cur_encryption_done, tot_encryption_size);
1672 /* Encrypt all encryptable volumes handled by vold */
1673 if (!rc) {
1674 for (i=0; i<num_vols; i++) {
1675 if (should_encrypt(&vol_list[i])) {
1676 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1677 vol_list[i].blk_dev,
1678 vol_list[i].crypt_ftr.fs_size,
1679 &cur_encryption_done, tot_encryption_size);
1680 }
1681 }
1682 }
1683 if (!rc) {
1684 /* The inplace routine never actually sets the progress to 100%
1685 * due to the round down nature of integer division, so set it here */
1686 property_set("vold.encrypt_progress", "100");
1687 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001689 /* Shouldn't happen */
1690 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001691 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001692 }
1693
1694 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001695 delete_crypto_blk_dev("userdata");
1696 for (i=0; i<num_vols; i++) {
1697 if (should_encrypt(&vol_list[i])) {
1698 delete_crypto_blk_dev(vol_list[i].label);
1699 }
1700 }
1701
1702 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001703
1704 if (! rc) {
1705 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001706
Ken Sumralld33d4172011-02-01 00:49:13 -08001707 /* Clear the encryption in progres flag in the footer */
1708 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001709 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001710
Ken Sumrall29d8da82011-05-18 17:20:07 -07001711 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07001712 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001713 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001714 char value[PROPERTY_VALUE_MAX];
1715
Ken Sumrall319369a2012-06-27 16:30:18 -07001716 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001717 if (!strcmp(value, "1")) {
1718 /* wipe data if encryption failed */
1719 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1720 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001721 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001722 if (fd >= 0) {
1723 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1724 close(fd);
1725 } else {
1726 SLOGE("could not open /cache/recovery/command\n");
1727 }
Ken Sumralladfba362013-06-04 16:37:52 -07001728 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001729 } else {
1730 /* set property to trigger dialog */
1731 property_set("vold.encrypt_progress", "error_partially_encrypted");
1732 release_wake_lock(lockid);
1733 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001734 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001735 }
1736
Ken Sumrall3ed82362011-01-28 23:31:16 -08001737 /* hrm, the encrypt step claims success, but the reboot failed.
1738 * This should not happen.
1739 * Set the property and return. Hope the framework can deal with it.
1740 */
1741 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001742 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001743 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001744
1745error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001746 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001747 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001748 if (lockid[0]) {
1749 release_wake_lock(lockid);
1750 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001751 return -1;
1752
1753error_shutting_down:
1754 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1755 * but the framework is stopped and not restarted to show the error, so it's up to
1756 * vold to restart the system.
1757 */
1758 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07001759 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001760
1761 /* shouldn't get here */
1762 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001763 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001764 if (lockid[0]) {
1765 release_wake_lock(lockid);
1766 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001767 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001768}
1769
Jason parks70a4b3f2011-01-28 10:10:47 -06001770int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001771{
1772 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001773 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001774
1775 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001776 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001777 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001778 return -1;
1779 }
1780
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001781 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001782 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001783 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001784 return -1;
1785 }
1786
Ken Sumrall160b4d62013-04-22 12:15:39 -07001787 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001788
Jason parks70a4b3f2011-01-28 10:10:47 -06001789 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001790 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001791
1792 return 0;
1793}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001794
1795static int persist_get_key(char *fieldname, char *value)
1796{
1797 unsigned int i;
1798
1799 if (persist_data == NULL) {
1800 return -1;
1801 }
1802 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1803 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1804 /* We found it! */
1805 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1806 return 0;
1807 }
1808 }
1809
1810 return -1;
1811}
1812
1813static int persist_set_key(char *fieldname, char *value, int encrypted)
1814{
1815 unsigned int i;
1816 unsigned int num;
1817 struct crypt_mnt_ftr crypt_ftr;
1818 unsigned int max_persistent_entries;
1819 unsigned int dsize;
1820
1821 if (persist_data == NULL) {
1822 return -1;
1823 }
1824
1825 /* If encrypted, use the values from the crypt_ftr, otherwise
1826 * use the values for the current spec.
1827 */
1828 if (encrypted) {
1829 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1830 return -1;
1831 }
1832 dsize = crypt_ftr.persist_data_size;
1833 } else {
1834 dsize = CRYPT_PERSIST_DATA_SIZE;
1835 }
1836 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1837 sizeof(struct crypt_persist_entry);
1838
1839 num = persist_data->persist_valid_entries;
1840
1841 for (i = 0; i < num; i++) {
1842 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1843 /* We found an existing entry, update it! */
1844 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1845 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1846 return 0;
1847 }
1848 }
1849
1850 /* We didn't find it, add it to the end, if there is room */
1851 if (persist_data->persist_valid_entries < max_persistent_entries) {
1852 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
1853 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
1854 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
1855 persist_data->persist_valid_entries++;
1856 return 0;
1857 }
1858
1859 return -1;
1860}
1861
1862/* Return the value of the specified field. */
1863int cryptfs_getfield(char *fieldname, char *value, int len)
1864{
1865 char temp_value[PROPERTY_VALUE_MAX];
1866 char real_blkdev[MAXPATHLEN];
1867 /* 0 is success, 1 is not encrypted,
1868 * -1 is value not set, -2 is any other error
1869 */
1870 int rc = -2;
1871
1872 if (persist_data == NULL) {
1873 load_persistent_data();
1874 if (persist_data == NULL) {
1875 SLOGE("Getfield error, cannot load persistent data");
1876 goto out;
1877 }
1878 }
1879
1880 if (!persist_get_key(fieldname, temp_value)) {
1881 /* We found it, copy it to the caller's buffer and return */
1882 strlcpy(value, temp_value, len);
1883 rc = 0;
1884 } else {
1885 /* Sadness, it's not there. Return the error */
1886 rc = -1;
1887 }
1888
1889out:
1890 return rc;
1891}
1892
1893/* Set the value of the specified field. */
1894int cryptfs_setfield(char *fieldname, char *value)
1895{
1896 struct crypt_persist_data stored_pdata;
1897 struct crypt_persist_data *pdata_p;
1898 struct crypt_mnt_ftr crypt_ftr;
1899 char encrypted_state[PROPERTY_VALUE_MAX];
1900 /* 0 is success, -1 is an error */
1901 int rc = -1;
1902 int encrypted = 0;
1903
1904 if (persist_data == NULL) {
1905 load_persistent_data();
1906 if (persist_data == NULL) {
1907 SLOGE("Setfield error, cannot load persistent data");
1908 goto out;
1909 }
1910 }
1911
1912 property_get("ro.crypto.state", encrypted_state, "");
1913 if (!strcmp(encrypted_state, "encrypted") ) {
1914 encrypted = 1;
1915 }
1916
1917 if (persist_set_key(fieldname, value, encrypted)) {
1918 goto out;
1919 }
1920
1921 /* If we are running encrypted, save the persistent data now */
1922 if (encrypted) {
1923 if (save_persistent_data()) {
1924 SLOGE("Setfield error, cannot save persistent data");
1925 goto out;
1926 }
1927 }
1928
1929 rc = 0;
1930
1931out:
1932 return rc;
1933}