blob: 1bf70498a45161e4ae29e67a722095e1e66ed4b3 [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 Sumrall8f869aa2010-12-03 03:47:09 -080049
50#define DM_CRYPT_BUF_SIZE 4096
Ken Sumrall8ddbe402011-01-17 15:26:29 -080051#define DATA_MNT_POINT "/data"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080052
Jason parks70a4b3f2011-01-28 10:10:47 -060053#define HASH_COUNT 2000
54#define KEY_LEN_BYTES 16
55#define IV_LEN_BYTES 16
56
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#define KEY_IN_FOOTER "footer"
58
59#define EXT4_FS 1
60#define FAT_FS 2
61
Ken Sumralle919efe2012-09-29 17:07:41 -070062#define TABLE_LOAD_RETRIES 10
63
Ken Sumrall8f869aa2010-12-03 03:47:09 -080064char *me = "cryptfs";
65
Jason parks70a4b3f2011-01-28 10:10:47 -060066static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070067static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060068static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070069static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080070
71extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080072
Ken Sumrall8f869aa2010-12-03 03:47:09 -080073static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
74{
75 memset(io, 0, dataSize);
76 io->data_size = dataSize;
77 io->data_start = sizeof(struct dm_ioctl);
78 io->version[0] = 4;
79 io->version[1] = 0;
80 io->version[2] = 0;
81 io->flags = flags;
82 if (name) {
83 strncpy(io->name, name, sizeof(io->name));
84 }
85}
86
Ken Sumrall3ed82362011-01-28 23:31:16 -080087static unsigned int get_fs_size(char *dev)
88{
89 int fd, block_size;
90 struct ext4_super_block sb;
91 off64_t len;
92
93 if ((fd = open(dev, O_RDONLY)) < 0) {
94 SLOGE("Cannot open device to get filesystem size ");
95 return 0;
96 }
97
98 if (lseek64(fd, 1024, SEEK_SET) < 0) {
99 SLOGE("Cannot seek to superblock");
100 return 0;
101 }
102
103 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
104 SLOGE("Cannot read superblock");
105 return 0;
106 }
107
108 close(fd);
109
110 block_size = 1024 << sb.s_log_block_size;
111 /* compute length in bytes */
112 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
113
114 /* return length in sectors */
115 return (unsigned int) (len / 512);
116}
117
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800118static unsigned int get_blkdev_size(int fd)
119{
120 unsigned int nr_sec;
121
122 if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
123 nr_sec = 0;
124 }
125
126 return nr_sec;
127}
128
Ken Sumrall160b4d62013-04-22 12:15:39 -0700129static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
130{
131 static int cached_data = 0;
132 static off64_t cached_off = 0;
133 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
134 int fd;
135 char key_loc[PROPERTY_VALUE_MAX];
136 char real_blkdev[PROPERTY_VALUE_MAX];
137 unsigned int nr_sec;
138 int rc = -1;
139
140 if (!cached_data) {
141 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
142
143 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
144 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
145 SLOGE("Cannot open real block device %s\n", real_blkdev);
146 return -1;
147 }
148
149 if ((nr_sec = get_blkdev_size(fd))) {
150 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
151 * encryption info footer and key, and plenty of bytes to spare for future
152 * growth.
153 */
154 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
155 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
156 cached_data = 1;
157 } else {
158 SLOGE("Cannot get size of block device %s\n", real_blkdev);
159 }
160 close(fd);
161 } else {
162 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
163 cached_off = 0;
164 cached_data = 1;
165 }
166 }
167
168 if (cached_data) {
169 if (metadata_fname) {
170 *metadata_fname = cached_metadata_fname;
171 }
172 if (off) {
173 *off = cached_off;
174 }
175 rc = 0;
176 }
177
178 return rc;
179}
180
Ken Sumralle8744072011-01-18 22:01:55 -0800181/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800182 * update the failed mount count but not change the key.
183 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700184static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800185{
186 int fd;
187 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700188 /* starting_off is set to the SEEK_SET offset
189 * where the crypto structure starts
190 */
191 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800192 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700193 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700194 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall3be890f2011-09-14 16:53:46 -0700195 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800196
Ken Sumrall160b4d62013-04-22 12:15:39 -0700197 if (get_crypt_ftr_info(&fname, &starting_off)) {
198 SLOGE("Unable to get crypt_ftr_info\n");
199 return -1;
200 }
201 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700202 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700203 return -1;
204 }
205 if ( (fd = open(fname, O_RDWR)) < 0) {
206 SLOGE("Cannot open footer file %s\n", fname);
207 return -1;
208 }
209
210 /* Seek to the start of the crypt footer */
211 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
212 SLOGE("Cannot seek to real block device footer\n");
213 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800214 }
215
216 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
217 SLOGE("Cannot write real block device footer\n");
218 goto errout;
219 }
220
Ken Sumrall3be890f2011-09-14 16:53:46 -0700221 fstat(fd, &statbuf);
222 /* If the keys are kept on a raw block device, do not try to truncate it. */
223 if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700224 if (ftruncate(fd, 0x4000)) {
Ken Sumrall3be890f2011-09-14 16:53:46 -0700225 SLOGE("Cannot set footer file size\n", fname);
Ken Sumralle8744072011-01-18 22:01:55 -0800226 goto errout;
227 }
228 }
229
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800230 /* Success! */
231 rc = 0;
232
233errout:
234 close(fd);
235 return rc;
236
237}
238
Ken Sumrall160b4d62013-04-22 12:15:39 -0700239static inline int unix_read(int fd, void* buff, int len)
240{
241 return TEMP_FAILURE_RETRY(read(fd, buff, len));
242}
243
244static inline int unix_write(int fd, const void* buff, int len)
245{
246 return TEMP_FAILURE_RETRY(write(fd, buff, len));
247}
248
249static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
250{
251 memset(pdata, 0, len);
252 pdata->persist_magic = PERSIST_DATA_MAGIC;
253 pdata->persist_valid_entries = 0;
254}
255
256/* A routine to update the passed in crypt_ftr to the lastest version.
257 * fd is open read/write on the device that holds the crypto footer and persistent
258 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
259 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
260 */
261static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
262{
263 struct crypt_persist_data *pdata;
264 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
265
266 /* This routine can currently only handle upgrading from 1.0 to 1.1.
267 * Do nothing if the passed structure is not version 1.0
268 */
269
270 if ((crypt_ftr->major_version != 1) && (crypt_ftr->minor_version != 0)) {
271 return;
272 }
273
274 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
275 if (pdata == NULL) {
276 SLOGE("Cannot allocate persisent data\n");
277 return;
278 }
279 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
280
281 /* Need to initialize the persistent data area */
282 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
283 SLOGE("Cannot seek to persisent data offset\n");
284 return;
285 }
286 /* Write all zeros to the first copy, making it invalid */
287 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
288
289 /* Write a valid but empty structure to the second copy */
290 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
291 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
292
293 /* Update the footer */
294 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
295 crypt_ftr->persist_data_offset[0] = pdata_offset;
296 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
297 crypt_ftr->minor_version = 1;
298 if (lseek64(fd, offset, SEEK_SET) == -1) {
299 SLOGE("Cannot seek to crypt footer\n");
300 return;
301 }
302 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
303}
304
305
306static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800307{
308 int fd;
309 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700310 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800311 int rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700312 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700313 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700314 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800315
Ken Sumrall160b4d62013-04-22 12:15:39 -0700316 if (get_crypt_ftr_info(&fname, &starting_off)) {
317 SLOGE("Unable to get crypt_ftr_info\n");
318 return -1;
319 }
320 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700321 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700322 return -1;
323 }
324 if ( (fd = open(fname, O_RDWR)) < 0) {
325 SLOGE("Cannot open footer file %s\n", fname);
326 return -1;
327 }
328
329 /* Make sure it's 16 Kbytes in length */
330 fstat(fd, &statbuf);
331 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
332 SLOGE("footer file %s is not the expected size!\n", fname);
333 goto errout;
334 }
335
336 /* Seek to the start of the crypt footer */
337 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
338 SLOGE("Cannot seek to real block device footer\n");
339 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800340 }
341
342 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
343 SLOGE("Cannot read real block device footer\n");
344 goto errout;
345 }
346
347 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700348 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800349 goto errout;
350 }
351
352 if (crypt_ftr->major_version != 1) {
353 SLOGE("Cannot understand major version %d real block device footer\n",
354 crypt_ftr->major_version);
355 goto errout;
356 }
357
Ken Sumrall160b4d62013-04-22 12:15:39 -0700358 if ((crypt_ftr->minor_version != 0) && (crypt_ftr->minor_version != 1)) {
359 SLOGW("Warning: crypto footer minor version %d, expected 0 or 1, continuing...\n",
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800360 crypt_ftr->minor_version);
361 }
362
Ken Sumrall160b4d62013-04-22 12:15:39 -0700363 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
364 * copy on disk before returning.
365 */
366 if (crypt_ftr->minor_version == 0) {
367 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800368 }
369
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800370 /* Success! */
371 rc = 0;
372
373errout:
374 close(fd);
375 return rc;
376}
377
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
379{
380 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
381 crypt_ftr->persist_data_offset[1]) {
382 SLOGE("Crypt_ftr persist data regions overlap");
383 return -1;
384 }
385
386 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
387 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
388 return -1;
389 }
390
391 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
392 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
393 CRYPT_FOOTER_OFFSET) {
394 SLOGE("Persistent data extends past crypto footer");
395 return -1;
396 }
397
398 return 0;
399}
400
401static int load_persistent_data(void)
402{
403 struct crypt_mnt_ftr crypt_ftr;
404 struct crypt_persist_data *pdata = NULL;
405 char encrypted_state[PROPERTY_VALUE_MAX];
406 char *fname;
407 int found = 0;
408 int fd;
409 int ret;
410 int i;
411
412 if (persist_data) {
413 /* Nothing to do, we've already loaded or initialized it */
414 return 0;
415 }
416
417
418 /* If not encrypted, just allocate an empty table and initialize it */
419 property_get("ro.crypto.state", encrypted_state, "");
420 if (strcmp(encrypted_state, "encrypted") ) {
421 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
422 if (pdata) {
423 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
424 persist_data = pdata;
425 return 0;
426 }
427 return -1;
428 }
429
430 if(get_crypt_ftr_and_key(&crypt_ftr)) {
431 return -1;
432 }
433
434 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
435 SLOGE("Crypt_ftr version doesn't support persistent data");
436 return -1;
437 }
438
439 if (get_crypt_ftr_info(&fname, NULL)) {
440 return -1;
441 }
442
443 ret = validate_persistent_data_storage(&crypt_ftr);
444 if (ret) {
445 return -1;
446 }
447
448 fd = open(fname, O_RDONLY);
449 if (fd < 0) {
450 SLOGE("Cannot open %s metadata file", fname);
451 return -1;
452 }
453
454 if (persist_data == NULL) {
455 pdata = malloc(crypt_ftr.persist_data_size);
456 if (pdata == NULL) {
457 SLOGE("Cannot allocate memory for persistent data");
458 goto err;
459 }
460 }
461
462 for (i = 0; i < 2; i++) {
463 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
464 SLOGE("Cannot seek to read persistent data on %s", fname);
465 goto err2;
466 }
467 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
468 SLOGE("Error reading persistent data on iteration %d", i);
469 goto err2;
470 }
471 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
472 found = 1;
473 break;
474 }
475 }
476
477 if (!found) {
478 SLOGI("Could not find valid persistent data, creating");
479 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
480 }
481
482 /* Success */
483 persist_data = pdata;
484 close(fd);
485 return 0;
486
487err2:
488 free(pdata);
489
490err:
491 close(fd);
492 return -1;
493}
494
495static int save_persistent_data(void)
496{
497 struct crypt_mnt_ftr crypt_ftr;
498 struct crypt_persist_data *pdata;
499 char *fname;
500 off64_t write_offset;
501 off64_t erase_offset;
502 int found = 0;
503 int fd;
504 int ret;
505
506 if (persist_data == NULL) {
507 SLOGE("No persistent data to save");
508 return -1;
509 }
510
511 if(get_crypt_ftr_and_key(&crypt_ftr)) {
512 return -1;
513 }
514
515 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
516 SLOGE("Crypt_ftr version doesn't support persistent data");
517 return -1;
518 }
519
520 ret = validate_persistent_data_storage(&crypt_ftr);
521 if (ret) {
522 return -1;
523 }
524
525 if (get_crypt_ftr_info(&fname, NULL)) {
526 return -1;
527 }
528
529 fd = open(fname, O_RDWR);
530 if (fd < 0) {
531 SLOGE("Cannot open %s metadata file", fname);
532 return -1;
533 }
534
535 pdata = malloc(crypt_ftr.persist_data_size);
536 if (pdata == NULL) {
537 SLOGE("Cannot allocate persistant data");
538 goto err;
539 }
540
541 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
542 SLOGE("Cannot seek to read persistent data on %s", fname);
543 goto err2;
544 }
545
546 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
547 SLOGE("Error reading persistent data before save");
548 goto err2;
549 }
550
551 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
552 /* The first copy is the curent valid copy, so write to
553 * the second copy and erase this one */
554 write_offset = crypt_ftr.persist_data_offset[1];
555 erase_offset = crypt_ftr.persist_data_offset[0];
556 } else {
557 /* The second copy must be the valid copy, so write to
558 * the first copy, and erase the second */
559 write_offset = crypt_ftr.persist_data_offset[0];
560 erase_offset = crypt_ftr.persist_data_offset[1];
561 }
562
563 /* Write the new copy first, if successful, then erase the old copy */
564 if (lseek(fd, write_offset, SEEK_SET) < 0) {
565 SLOGE("Cannot seek to write persistent data");
566 goto err2;
567 }
568 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
569 (int) crypt_ftr.persist_data_size) {
570 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
571 SLOGE("Cannot seek to erase previous persistent data");
572 goto err2;
573 }
574 fsync(fd);
575 memset(pdata, 0, crypt_ftr.persist_data_size);
576 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
577 (int) crypt_ftr.persist_data_size) {
578 SLOGE("Cannot write to erase previous persistent data");
579 goto err2;
580 }
581 fsync(fd);
582 } else {
583 SLOGE("Cannot write to save persistent data");
584 goto err2;
585 }
586
587 /* Success */
588 free(pdata);
589 close(fd);
590 return 0;
591
592err2:
593 free(pdata);
594err:
595 close(fd);
596 return -1;
597}
598
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800599/* Convert a binary key of specified length into an ascii hex string equivalent,
600 * without the leading 0x and with null termination
601 */
602void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
603 char *master_key_ascii)
604{
605 unsigned int i, a;
606 unsigned char nibble;
607
608 for (i=0, a=0; i<keysize; i++, a+=2) {
609 /* For each byte, write out two ascii hex digits */
610 nibble = (master_key[i] >> 4) & 0xf;
611 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
612
613 nibble = master_key[i] & 0xf;
614 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
615 }
616
617 /* Add the null termination */
618 master_key_ascii[a] = '\0';
619
620}
621
Ken Sumralldb5e0262013-02-05 17:39:48 -0800622static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
623 char *real_blk_name, const char *name, int fd,
624 char *extra_params)
625{
626 char buffer[DM_CRYPT_BUF_SIZE];
627 struct dm_ioctl *io;
628 struct dm_target_spec *tgt;
629 char *crypt_params;
630 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
631 int i;
632
633 io = (struct dm_ioctl *) buffer;
634
635 /* Load the mapping table for this device */
636 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
637
638 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
639 io->target_count = 1;
640 tgt->status = 0;
641 tgt->sector_start = 0;
642 tgt->length = crypt_ftr->fs_size;
643 strcpy(tgt->target_type, "crypt");
644
645 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
646 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
647 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
648 master_key_ascii, real_blk_name, extra_params);
649 crypt_params += strlen(crypt_params) + 1;
650 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
651 tgt->next = crypt_params - buffer;
652
653 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
654 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
655 break;
656 }
657 usleep(500000);
658 }
659
660 if (i == TABLE_LOAD_RETRIES) {
661 /* We failed to load the table, return an error */
662 return -1;
663 } else {
664 return i + 1;
665 }
666}
667
668
669static int get_dm_crypt_version(int fd, const char *name, int *version)
670{
671 char buffer[DM_CRYPT_BUF_SIZE];
672 struct dm_ioctl *io;
673 struct dm_target_versions *v;
674 int i;
675
676 io = (struct dm_ioctl *) buffer;
677
678 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
679
680 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
681 return -1;
682 }
683
684 /* Iterate over the returned versions, looking for name of "crypt".
685 * When found, get and return the version.
686 */
687 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
688 while (v->next) {
689 if (! strcmp(v->name, "crypt")) {
690 /* We found the crypt driver, return the version, and get out */
691 version[0] = v->version[0];
692 version[1] = v->version[1];
693 version[2] = v->version[2];
694 return 0;
695 }
696 v = (struct dm_target_versions *)(((char *)v) + v->next);
697 }
698
699 return -1;
700}
701
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800702static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700703 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800704{
705 char buffer[DM_CRYPT_BUF_SIZE];
706 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
707 char *crypt_params;
708 struct dm_ioctl *io;
709 struct dm_target_spec *tgt;
710 unsigned int minor;
711 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700712 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800713 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800714 int version[3];
715 char *extra_params;
716 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800717
718 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
719 SLOGE("Cannot open device-mapper\n");
720 goto errout;
721 }
722
723 io = (struct dm_ioctl *) buffer;
724
725 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
726 if (ioctl(fd, DM_DEV_CREATE, io)) {
727 SLOGE("Cannot create dm-crypt device\n");
728 goto errout;
729 }
730
731 /* Get the device status, in particular, the name of it's device file */
732 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
733 if (ioctl(fd, DM_DEV_STATUS, io)) {
734 SLOGE("Cannot retrieve dm-crypt device status\n");
735 goto errout;
736 }
737 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
738 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
739
Ken Sumralldb5e0262013-02-05 17:39:48 -0800740 extra_params = "";
741 if (! get_dm_crypt_version(fd, name, version)) {
742 /* Support for allow_discards was added in version 1.11.0 */
743 if ((version[0] >= 2) ||
744 ((version[0] == 1) && (version[1] >= 11))) {
745 extra_params = "1 allow_discards";
746 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
747 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700748 }
749
Ken Sumralldb5e0262013-02-05 17:39:48 -0800750 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
751 fd, extra_params);
752 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800753 SLOGE("Cannot load dm-crypt mapping table.\n");
754 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800755 } else if (load_count > 1) {
756 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800757 }
758
759 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800760 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800761
762 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
763 SLOGE("Cannot resume the dm-crypt device\n");
764 goto errout;
765 }
766
767 /* We made it here with no errors. Woot! */
768 retval = 0;
769
770errout:
771 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
772
773 return retval;
774}
775
Ken Sumrall29d8da82011-05-18 17:20:07 -0700776static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800777{
778 int fd;
779 char buffer[DM_CRYPT_BUF_SIZE];
780 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800781 int retval = -1;
782
783 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
784 SLOGE("Cannot open device-mapper\n");
785 goto errout;
786 }
787
788 io = (struct dm_ioctl *) buffer;
789
790 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
791 if (ioctl(fd, DM_DEV_REMOVE, io)) {
792 SLOGE("Cannot remove dm-crypt device\n");
793 goto errout;
794 }
795
796 /* We made it here with no errors. Woot! */
797 retval = 0;
798
799errout:
800 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
801
802 return retval;
803
804}
805
Ken Sumralle8744072011-01-18 22:01:55 -0800806static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800807{
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800808 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800809 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800810 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800811}
812
Ken Sumralle8744072011-01-18 22:01:55 -0800813static int encrypt_master_key(char *passwd, unsigned char *salt,
814 unsigned char *decrypted_master_key,
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800815 unsigned char *encrypted_master_key)
816{
817 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
818 EVP_CIPHER_CTX e_ctx;
819 int encrypted_len, final_len;
820
821 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800822 pbkdf2(passwd, salt, ikey);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800823
824 /* Initialize the decryption engine */
825 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
826 SLOGE("EVP_EncryptInit failed\n");
827 return -1;
828 }
829 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800830
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800831 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800832 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
833 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800834 SLOGE("EVP_EncryptUpdate failed\n");
835 return -1;
836 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800837 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800838 SLOGE("EVP_EncryptFinal failed\n");
839 return -1;
840 }
841
842 if (encrypted_len + final_len != KEY_LEN_BYTES) {
843 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
844 return -1;
845 } else {
846 return 0;
847 }
848}
849
Ken Sumralle8744072011-01-18 22:01:55 -0800850static int decrypt_master_key(char *passwd, unsigned char *salt,
851 unsigned char *encrypted_master_key,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800852 unsigned char *decrypted_master_key)
853{
854 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 -0800855 EVP_CIPHER_CTX d_ctx;
856 int decrypted_len, final_len;
857
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800858 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800859 pbkdf2(passwd, salt, ikey);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800860
861 /* Initialize the decryption engine */
862 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
863 return -1;
864 }
865 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
866 /* Decrypt the master key */
867 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
868 encrypted_master_key, KEY_LEN_BYTES)) {
869 return -1;
870 }
871 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
872 return -1;
873 }
874
875 if (decrypted_len + final_len != KEY_LEN_BYTES) {
876 return -1;
877 } else {
878 return 0;
879 }
880}
881
Ken Sumralle8744072011-01-18 22:01:55 -0800882static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800883{
884 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800885 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800886 EVP_CIPHER_CTX e_ctx;
887 int encrypted_len, final_len;
888
889 /* Get some random bits for a key */
890 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -0800891 read(fd, key_buf, sizeof(key_buf));
892 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800893 close(fd);
894
895 /* Now encrypt it with the password */
Ken Sumralle8744072011-01-18 22:01:55 -0800896 return encrypt_master_key(passwd, salt, key_buf, master_key);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800897}
898
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800899static int wait_and_unmount(char *mountpoint)
900{
901 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -0800902#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800903
904 /* Now umount the tmpfs filesystem */
905 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
906 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700907 if (errno == EINVAL) {
908 /* EINVAL is returned if the directory is not a mountpoint,
909 * i.e. there is no filesystem mounted there. So just get out.
910 */
911 break;
912 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800913 sleep(1);
914 i++;
915 } else {
916 break;
917 }
918 }
919
920 if (i < WAIT_UNMOUNT_COUNT) {
921 SLOGD("unmounting %s succeeded\n", mountpoint);
922 rc = 0;
923 } else {
924 SLOGE("unmounting %s failed\n", mountpoint);
925 rc = -1;
926 }
927
928 return rc;
929}
930
Ken Sumrallc5872692013-05-14 15:26:31 -0700931#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800932static int prep_data_fs(void)
933{
934 int i;
935
936 /* Do the prep of the /data filesystem */
937 property_set("vold.post_fs_data_done", "0");
938 property_set("vold.decrypt", "trigger_post_fs_data");
939 SLOGD("Just triggered post_fs_data\n");
940
Ken Sumrallc5872692013-05-14 15:26:31 -0700941 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800942 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700943 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800944
945 property_get("vold.post_fs_data_done", p, "0");
946 if (*p == '1') {
947 break;
948 } else {
949 usleep(250000);
950 }
951 }
952 if (i == DATA_PREP_TIMEOUT) {
953 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -0700954 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800955 return -1;
956 } else {
957 SLOGD("post_fs_data done\n");
958 return 0;
959 }
960}
961
Ken Sumrall6864b7e2011-01-14 15:20:02 -0800962int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800963{
964 char fs_type[32];
965 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -0800966 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800967 char fs_options[256];
968 unsigned long mnt_flags;
969 struct stat statbuf;
970 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -0800971 static int restart_successful = 0;
972
973 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -0600974 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -0800975 SLOGE("Encrypted filesystem not validated, aborting");
976 return -1;
977 }
978
979 if (restart_successful) {
980 SLOGE("System already restarted with encrypted disk, aborting");
981 return -1;
982 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800983
984 /* Here is where we shut down the framework. The init scripts
985 * start all services in one of three classes: core, main or late_start.
986 * On boot, we start core and main. Now, we stop main, but not core,
987 * as core includes vold and a few other really important things that
988 * we need to keep running. Once main has stopped, we should be able
989 * to umount the tmpfs /data, then mount the encrypted /data.
990 * We then restart the class main, and also the class late_start.
991 * At the moment, I've only put a few things in late_start that I know
992 * are not needed to bring up the framework, and that also cause problems
993 * with unmounting the tmpfs /data, but I hope to add add more services
994 * to the late_start class as we optimize this to decrease the delay
995 * till the user is asked for the password to the filesystem.
996 */
997
998 /* The init files are setup to stop the class main when vold.decrypt is
999 * set to trigger_reset_main.
1000 */
1001 property_set("vold.decrypt", "trigger_reset_main");
1002 SLOGD("Just asked init to shut down class main\n");
1003
Ken Sumrall92736ef2012-10-17 20:57:14 -07001004 /* Ugh, shutting down the framework is not synchronous, so until it
1005 * can be fixed, this horrible hack will wait a moment for it all to
1006 * shut down before proceeding. Without it, some devices cannot
1007 * restart the graphics services.
1008 */
1009 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001010
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001011 /* Now that the framework is shutdown, we should be able to umount()
1012 * the tmpfs filesystem, and mount the real one.
1013 */
1014
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001015 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1016 if (strlen(crypto_blkdev) == 0) {
1017 SLOGE("fs_crypto_blkdev not set\n");
1018 return -1;
1019 }
1020
Ken Sumralle5032c42012-04-01 23:58:44 -07001021 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1022 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001023 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001024
Ken Sumralle5032c42012-04-01 23:58:44 -07001025 property_set("vold.decrypt", "trigger_load_persist_props");
1026 /* Create necessary paths on /data */
1027 if (prep_data_fs()) {
1028 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001029 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001030
1031 /* startup service classes main and late_start */
1032 property_set("vold.decrypt", "trigger_restart_framework");
1033 SLOGD("Just triggered restart_framework\n");
1034
1035 /* Give it a few moments to get started */
1036 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001037 }
1038
Ken Sumrall0cc16632011-01-18 20:32:26 -08001039 if (rc == 0) {
1040 restart_successful = 1;
1041 }
1042
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001043 return rc;
1044}
1045
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001046static int do_crypto_complete(char *mount_point)
1047{
1048 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001049 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001050 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001051
1052 property_get("ro.crypto.state", encrypted_state, "");
1053 if (strcmp(encrypted_state, "encrypted") ) {
1054 SLOGE("not running with encryption, aborting");
1055 return 1;
1056 }
1057
Ken Sumrall160b4d62013-04-22 12:15:39 -07001058 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001059 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001060
Ken Sumralle1a45852011-12-14 21:24:27 -08001061 /*
1062 * Only report this error if key_loc is a file and it exists.
1063 * If the device was never encrypted, and /data is not mountable for
1064 * some reason, returning 1 should prevent the UI from presenting the
1065 * a "enter password" screen, or worse, a "press button to wipe the
1066 * device" screen.
1067 */
1068 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1069 SLOGE("master key file does not exist, aborting");
1070 return 1;
1071 } else {
1072 SLOGE("Error getting crypt footer and key\n");
1073 return -1;
1074 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001075 }
1076
1077 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1078 SLOGE("Encryption process didn't finish successfully\n");
1079 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1080 * and give the user an option to wipe the disk */
1081 }
1082
1083 /* We passed the test! We shall diminish, and return to the west */
1084 return 0;
1085}
1086
Ken Sumrall29d8da82011-05-18 17:20:07 -07001087static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001088{
1089 struct crypt_mnt_ftr crypt_ftr;
1090 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001091 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092 char crypto_blkdev[MAXPATHLEN];
1093 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001094 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001095 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001096 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001097 int rc;
1098
Ken Sumrall0cc16632011-01-18 20:32:26 -08001099 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001100 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001101 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1102 return -1;
1103 }
1104
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001105 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106
Ken Sumrall160b4d62013-04-22 12:15:39 -07001107 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001108 SLOGE("Error getting crypt footer and key\n");
1109 return -1;
1110 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001111
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001112 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1113 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1114
1115 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001116 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key, decrypted_master_key);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117 }
1118
1119 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001120 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121 SLOGE("Error creating decrypted block device\n");
1122 return -1;
1123 }
1124
Alex Klyubin707795a2013-05-10 15:17:07 -07001125 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1127 * files and passes that data to me */
1128 /* Create a tmp mount point to try mounting the decryptd fs
1129 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1130 * a directory in it to test mount the decrypted filesystem.
1131 */
1132 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1133 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001134 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001135 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001136 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001137 crypt_ftr.failed_decrypt_count++;
1138 } else {
1139 /* Success, so just umount and we'll mount it properly when we restart
1140 * the framework.
1141 */
1142 umount(tmp_mount_point);
1143 crypt_ftr.failed_decrypt_count = 0;
1144 }
1145
1146 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001147 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001148 }
1149
1150 if (crypt_ftr.failed_decrypt_count) {
1151 /* We failed to mount the device, so return an error */
1152 rc = crypt_ftr.failed_decrypt_count;
1153
1154 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001155 /* Woot! Success! Save the name of the crypto block device
1156 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001158 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001159
1160 /* Also save a the master key so we can reencrypted the key
1161 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001162 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001163 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001164 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001165 master_key_saved = 1;
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001166 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001167 }
1168
1169 return rc;
1170}
1171
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001172/* Called by vold when it wants to undo the crypto mapping of a volume it
1173 * manages. This is usually in response to a factory reset, when we want
1174 * to undo the crypto mapping so the volume is formatted in the clear.
1175 */
1176int cryptfs_revert_volume(const char *label)
1177{
1178 return delete_crypto_blk_dev((char *)label);
1179}
1180
Ken Sumrall29d8da82011-05-18 17:20:07 -07001181/*
1182 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1183 * Setup a dm-crypt mapping, use the saved master key from
1184 * setting up the /data mapping, and return the new device path.
1185 */
1186int cryptfs_setup_volume(const char *label, int major, int minor,
1187 char *crypto_sys_path, unsigned int max_path,
1188 int *new_major, int *new_minor)
1189{
1190 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1191 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001192 struct stat statbuf;
1193 int nr_sec, fd;
1194
1195 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1196
Ken Sumrall160b4d62013-04-22 12:15:39 -07001197 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001198
1199 /* Update the fs_size field to be the size of the volume */
1200 fd = open(real_blkdev, O_RDONLY);
1201 nr_sec = get_blkdev_size(fd);
1202 close(fd);
1203 if (nr_sec == 0) {
1204 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1205 return -1;
1206 }
1207
1208 sd_crypt_ftr.fs_size = nr_sec;
1209 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1210 crypto_blkdev, label);
1211
1212 stat(crypto_blkdev, &statbuf);
1213 *new_major = MAJOR(statbuf.st_rdev);
1214 *new_minor = MINOR(statbuf.st_rdev);
1215
1216 /* Create path to sys entry for this block device */
1217 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1218
1219 return 0;
1220}
1221
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001222int cryptfs_crypto_complete(void)
1223{
1224 return do_crypto_complete("/data");
1225}
1226
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227int cryptfs_check_passwd(char *passwd)
1228{
1229 int rc = -1;
1230
Ken Sumrall29d8da82011-05-18 17:20:07 -07001231 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001232
1233 return rc;
1234}
1235
Ken Sumrall3ad90722011-10-04 20:38:29 -07001236int cryptfs_verify_passwd(char *passwd)
1237{
1238 struct crypt_mnt_ftr crypt_ftr;
1239 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001240 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001241 char encrypted_state[PROPERTY_VALUE_MAX];
1242 int rc;
1243
1244 property_get("ro.crypto.state", encrypted_state, "");
1245 if (strcmp(encrypted_state, "encrypted") ) {
1246 SLOGE("device not encrypted, aborting");
1247 return -2;
1248 }
1249
1250 if (!master_key_saved) {
1251 SLOGE("encrypted fs not yet mounted, aborting");
1252 return -1;
1253 }
1254
1255 if (!saved_mount_point) {
1256 SLOGE("encrypted fs failed to save mount point, aborting");
1257 return -1;
1258 }
1259
Ken Sumrall160b4d62013-04-22 12:15:39 -07001260 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001261 SLOGE("Error getting crypt footer and key\n");
1262 return -1;
1263 }
1264
1265 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1266 /* If the device has no password, then just say the password is valid */
1267 rc = 0;
1268 } else {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001269 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key,
1270 decrypted_master_key);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001271 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1272 /* They match, the password is correct */
1273 rc = 0;
1274 } else {
1275 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1276 sleep(1);
1277 rc = 1;
1278 }
1279 }
1280
1281 return rc;
1282}
1283
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001284/* Initialize a crypt_mnt_ftr structure. The keysize is
1285 * defaulted to 16 bytes, and the filesystem size to 0.
1286 * Presumably, at a minimum, the caller will update the
1287 * filesystem size and crypto_type_name after calling this function.
1288 */
1289static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1290{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001291 off64_t off;
1292
1293 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 ftr->magic = CRYPT_MNT_MAGIC;
1295 ftr->major_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001296 ftr->minor_version = 1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001298 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001299
1300 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1301 if (get_crypt_ftr_info(NULL, &off) == 0) {
1302 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1303 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1304 ftr->persist_data_size;
1305 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306}
1307
Ken Sumrall29d8da82011-05-18 17:20:07 -07001308static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001309{
1310 char cmdline[256];
1311 int rc = -1;
1312
Ken Sumrall29d8da82011-05-18 17:20:07 -07001313 if (type == EXT4_FS) {
1314 snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
1315 size * 512, crypto_blkdev);
1316 SLOGI("Making empty filesystem with command %s\n", cmdline);
1317 } else if (type== FAT_FS) {
1318 snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
1319 size, crypto_blkdev);
1320 SLOGI("Making empty filesystem with command %s\n", cmdline);
1321 } else {
1322 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1323 return -1;
1324 }
1325
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001326 if (system(cmdline)) {
1327 SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
1328 } else {
1329 SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
1330 rc = 0;
1331 }
1332
1333 return rc;
1334}
1335
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001336#define CRYPT_INPLACE_BUFSIZE 4096
1337#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001338static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1339 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001340{
1341 int realfd, cryptofd;
1342 char *buf[CRYPT_INPLACE_BUFSIZE];
1343 int rc = -1;
1344 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001345 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001346 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001347
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001348 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1349 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1350 return -1;
1351 }
1352
1353 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1354 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1355 close(realfd);
1356 return -1;
1357 }
1358
1359 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1360 * The size passed in is the number of 512 byte sectors in the filesystem.
1361 * So compute the number of whole 4K blocks we should read/write,
1362 * and the remainder.
1363 */
1364 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1365 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001366 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1367 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001368
1369 SLOGE("Encrypting filesystem in place...");
1370
Ken Sumrall29d8da82011-05-18 17:20:07 -07001371 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001372 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373 /* process the majority of the filesystem in blocks */
1374 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001375 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001376 if (new_pct > cur_pct) {
1377 char buf[8];
1378
1379 cur_pct = new_pct;
1380 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1381 property_set("vold.encrypt_progress", buf);
1382 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001383 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1384 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1385 goto errout;
1386 }
1387 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1388 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1389 goto errout;
1390 }
1391 }
1392
1393 /* Do any remaining sectors */
1394 for (i=0; i<remainder; i++) {
1395 if (unix_read(realfd, buf, 512) <= 0) {
1396 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1397 goto errout;
1398 }
1399 if (unix_write(cryptofd, buf, 512) <= 0) {
1400 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1401 goto errout;
1402 }
1403 }
1404
Ken Sumrall29d8da82011-05-18 17:20:07 -07001405 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001406 rc = 0;
1407
1408errout:
1409 close(realfd);
1410 close(cryptofd);
1411
1412 return rc;
1413}
1414
1415#define CRYPTO_ENABLE_WIPE 1
1416#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001417
1418#define FRAMEWORK_BOOT_WAIT 60
1419
Ken Sumrall29d8da82011-05-18 17:20:07 -07001420static inline int should_encrypt(struct volume_info *volume)
1421{
1422 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1423 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1424}
1425
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426int cryptfs_enable(char *howarg, char *passwd)
1427{
1428 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001429 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001430 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001431 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001432 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001433 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001434 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001435 char tmpfs_options[PROPERTY_VALUE_MAX];
1436 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001437 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001438 char key_loc[PROPERTY_VALUE_MAX];
1439 char fuse_sdcard[PROPERTY_VALUE_MAX];
1440 char *sd_mnt_point;
1441 char sd_blk_dev[256] = { 0 };
1442 int num_vols;
1443 struct volume_info *vol_list = 0;
1444 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001445
1446 property_get("ro.crypto.state", encrypted_state, "");
1447 if (strcmp(encrypted_state, "unencrypted")) {
1448 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001449 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001450 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001451
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001452 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001453
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001454 if (!strcmp(howarg, "wipe")) {
1455 how = CRYPTO_ENABLE_WIPE;
1456 } else if (! strcmp(howarg, "inplace")) {
1457 how = CRYPTO_ENABLE_INPLACE;
1458 } else {
1459 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001460 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001461 }
1462
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001463 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001464
Ken Sumrall3ed82362011-01-28 23:31:16 -08001465 /* Get the size of the real block device */
1466 fd = open(real_blkdev, O_RDONLY);
1467 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1468 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1469 goto error_unencrypted;
1470 }
1471 close(fd);
1472
1473 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001474 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001475 unsigned int fs_size_sec, max_fs_size_sec;
1476
1477 fs_size_sec = get_fs_size(real_blkdev);
1478 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1479
1480 if (fs_size_sec > max_fs_size_sec) {
1481 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1482 goto error_unencrypted;
1483 }
1484 }
1485
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001486 /* Get a wakelock as this may take a while, and we don't want the
1487 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1488 * wants to keep the screen on, it can grab a full wakelock.
1489 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001490 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001491 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1492
Jeff Sharkey7382f812012-08-23 14:08:59 -07001493 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001494 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001495 if (!sd_mnt_point) {
1496 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1497 }
1498 if (!sd_mnt_point) {
1499 sd_mnt_point = "/mnt/sdcard";
1500 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001501
1502 num_vols=vold_getNumDirectVolumes();
1503 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1504 vold_getDirectVolumeList(vol_list);
1505
1506 for (i=0; i<num_vols; i++) {
1507 if (should_encrypt(&vol_list[i])) {
1508 fd = open(vol_list[i].blk_dev, O_RDONLY);
1509 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1510 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1511 goto error_unencrypted;
1512 }
1513 close(fd);
1514
Ken Sumrall3b170052011-07-11 15:38:57 -07001515 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001516 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1517 /* -2 is returned when the device exists but is not currently mounted.
1518 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001519 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1520 goto error_unencrypted;
1521 }
1522 }
1523 }
1524
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001526 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001527 */
1528 property_set("vold.decrypt", "trigger_shutdown_framework");
1529 SLOGD("Just asked init to shut down class main\n");
1530
Ken Sumrall425524d2012-06-14 20:55:28 -07001531 if (vold_unmountAllAsecs()) {
1532 /* Just report the error. If any are left mounted,
1533 * umounting /data below will fail and handle the error.
1534 */
1535 SLOGE("Error unmounting internal asecs");
1536 }
1537
Ken Sumrall29d8da82011-05-18 17:20:07 -07001538 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1539 if (!strcmp(fuse_sdcard, "true")) {
1540 /* This is a device using the fuse layer to emulate the sdcard semantics
1541 * on top of the userdata partition. vold does not manage it, it is managed
1542 * by the sdcard service. The sdcard service was killed by the property trigger
1543 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1544 * unlike the case for vold managed devices above.
1545 */
1546 if (wait_and_unmount(sd_mnt_point)) {
1547 goto error_shutting_down;
1548 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001549 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001550
1551 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001552 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001553 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001554 }
1555
1556 /* Do extra work for a better UX when doing the long inplace encryption */
1557 if (how == CRYPTO_ENABLE_INPLACE) {
1558 /* Now that /data is unmounted, we need to mount a tmpfs
1559 * /data, set a property saying we're doing inplace encryption,
1560 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001562 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001563 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001564 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001565 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001566 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001568 /* restart the framework. */
1569 /* Create necessary paths on /data */
1570 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001571 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572 }
1573
Ken Sumrall92736ef2012-10-17 20:57:14 -07001574 /* Ugh, shutting down the framework is not synchronous, so until it
1575 * can be fixed, this horrible hack will wait a moment for it all to
1576 * shut down before proceeding. Without it, some devices cannot
1577 * restart the graphics services.
1578 */
1579 sleep(2);
1580
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001581 /* startup service classes main and late_start */
1582 property_set("vold.decrypt", "trigger_restart_min_framework");
1583 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584
Ken Sumrall7df84122011-01-18 14:04:08 -08001585 /* OK, the framework is restarted and will soon be showing a
1586 * progress bar. Time to setup an encrypted mapping, and
1587 * either write a new filesystem, or encrypt in place updating
1588 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001589 */
1590 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001591
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001592 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001593 /* Initialize a crypt_mnt_ftr for the partition */
1594 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001595
Ken Sumrall29d8da82011-05-18 17:20:07 -07001596 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1597 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1598 } else {
1599 crypt_ftr.fs_size = nr_sec;
1600 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001601 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001602 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1603
1604 /* Make an encrypted master key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001605 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001606 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001607 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001608 }
1609
1610 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001611 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001612
Ken Sumrall160b4d62013-04-22 12:15:39 -07001613 /* If any persistent data has been remembered, save it.
1614 * If none, create a valid empty table and save that.
1615 */
1616 if (!persist_data) {
1617 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1618 if (pdata) {
1619 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1620 persist_data = pdata;
1621 }
1622 }
1623 if (persist_data) {
1624 save_persistent_data();
1625 }
1626
1627 decrypt_master_key(passwd, crypt_ftr.salt, crypt_ftr.master_key, decrypted_master_key);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001628 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1629 "userdata");
1630
Ken Sumrall128626f2011-06-28 18:45:14 -07001631 /* The size of the userdata partition, and add in the vold volumes below */
1632 tot_encryption_size = crypt_ftr.fs_size;
1633
Ken Sumrall29d8da82011-05-18 17:20:07 -07001634 /* setup crypto mapping for all encryptable volumes handled by vold */
1635 for (i=0; i<num_vols; i++) {
1636 if (should_encrypt(&vol_list[i])) {
1637 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1638 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1639 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1640 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1641 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001642 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001643 }
1644 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001645
1646 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001647 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1648 /* Encrypt all encryptable volumes handled by vold */
1649 if (!rc) {
1650 for (i=0; i<num_vols; i++) {
1651 if (should_encrypt(&vol_list[i])) {
1652 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1653 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1654 }
1655 }
1656 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001657 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001658 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1659 &cur_encryption_done, tot_encryption_size);
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_inplace(vol_list[i].crypto_blkdev,
1665 vol_list[i].blk_dev,
1666 vol_list[i].crypt_ftr.fs_size,
1667 &cur_encryption_done, tot_encryption_size);
1668 }
1669 }
1670 }
1671 if (!rc) {
1672 /* The inplace routine never actually sets the progress to 100%
1673 * due to the round down nature of integer division, so set it here */
1674 property_set("vold.encrypt_progress", "100");
1675 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001676 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001677 /* Shouldn't happen */
1678 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001679 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001680 }
1681
1682 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001683 delete_crypto_blk_dev("userdata");
1684 for (i=0; i<num_vols; i++) {
1685 if (should_encrypt(&vol_list[i])) {
1686 delete_crypto_blk_dev(vol_list[i].label);
1687 }
1688 }
1689
1690 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001691
1692 if (! rc) {
1693 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001694
Ken Sumralld33d4172011-02-01 00:49:13 -08001695 /* Clear the encryption in progres flag in the footer */
1696 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001697 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001698
Ken Sumrall29d8da82011-05-18 17:20:07 -07001699 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumrallc290eaf2011-03-07 23:40:35 -08001700 android_reboot(ANDROID_RB_RESTART, 0, 0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001701 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001702 char value[PROPERTY_VALUE_MAX];
1703
Ken Sumrall319369a2012-06-27 16:30:18 -07001704 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001705 if (!strcmp(value, "1")) {
1706 /* wipe data if encryption failed */
1707 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1708 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001709 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001710 if (fd >= 0) {
1711 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1712 close(fd);
1713 } else {
1714 SLOGE("could not open /cache/recovery/command\n");
1715 }
1716 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
1717 } else {
1718 /* set property to trigger dialog */
1719 property_set("vold.encrypt_progress", "error_partially_encrypted");
1720 release_wake_lock(lockid);
1721 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001722 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001723 }
1724
Ken Sumrall3ed82362011-01-28 23:31:16 -08001725 /* hrm, the encrypt step claims success, but the reboot failed.
1726 * This should not happen.
1727 * Set the property and return. Hope the framework can deal with it.
1728 */
1729 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001730 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001731 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001732
1733error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001734 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001735 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001736 if (lockid[0]) {
1737 release_wake_lock(lockid);
1738 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001739 return -1;
1740
1741error_shutting_down:
1742 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1743 * but the framework is stopped and not restarted to show the error, so it's up to
1744 * vold to restart the system.
1745 */
1746 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumrallc290eaf2011-03-07 23:40:35 -08001747 android_reboot(ANDROID_RB_RESTART, 0, 0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001748
1749 /* shouldn't get here */
1750 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001751 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001752 if (lockid[0]) {
1753 release_wake_lock(lockid);
1754 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001755 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001756}
1757
Jason parks70a4b3f2011-01-28 10:10:47 -06001758int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001759{
1760 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001761 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001762
1763 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001764 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001765 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001766 return -1;
1767 }
1768
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001769 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001770 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001771 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001772 return -1;
1773 }
1774
Ken Sumrall160b4d62013-04-22 12:15:39 -07001775 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001776
Jason parks70a4b3f2011-01-28 10:10:47 -06001777 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001778 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001779
1780 return 0;
1781}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001782
1783static int persist_get_key(char *fieldname, char *value)
1784{
1785 unsigned int i;
1786
1787 if (persist_data == NULL) {
1788 return -1;
1789 }
1790 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1791 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1792 /* We found it! */
1793 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1794 return 0;
1795 }
1796 }
1797
1798 return -1;
1799}
1800
1801static int persist_set_key(char *fieldname, char *value, int encrypted)
1802{
1803 unsigned int i;
1804 unsigned int num;
1805 struct crypt_mnt_ftr crypt_ftr;
1806 unsigned int max_persistent_entries;
1807 unsigned int dsize;
1808
1809 if (persist_data == NULL) {
1810 return -1;
1811 }
1812
1813 /* If encrypted, use the values from the crypt_ftr, otherwise
1814 * use the values for the current spec.
1815 */
1816 if (encrypted) {
1817 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1818 return -1;
1819 }
1820 dsize = crypt_ftr.persist_data_size;
1821 } else {
1822 dsize = CRYPT_PERSIST_DATA_SIZE;
1823 }
1824 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1825 sizeof(struct crypt_persist_entry);
1826
1827 num = persist_data->persist_valid_entries;
1828
1829 for (i = 0; i < num; i++) {
1830 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1831 /* We found an existing entry, update it! */
1832 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1833 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1834 return 0;
1835 }
1836 }
1837
1838 /* We didn't find it, add it to the end, if there is room */
1839 if (persist_data->persist_valid_entries < max_persistent_entries) {
1840 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
1841 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
1842 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
1843 persist_data->persist_valid_entries++;
1844 return 0;
1845 }
1846
1847 return -1;
1848}
1849
1850/* Return the value of the specified field. */
1851int cryptfs_getfield(char *fieldname, char *value, int len)
1852{
1853 char temp_value[PROPERTY_VALUE_MAX];
1854 char real_blkdev[MAXPATHLEN];
1855 /* 0 is success, 1 is not encrypted,
1856 * -1 is value not set, -2 is any other error
1857 */
1858 int rc = -2;
1859
1860 if (persist_data == NULL) {
1861 load_persistent_data();
1862 if (persist_data == NULL) {
1863 SLOGE("Getfield error, cannot load persistent data");
1864 goto out;
1865 }
1866 }
1867
1868 if (!persist_get_key(fieldname, temp_value)) {
1869 /* We found it, copy it to the caller's buffer and return */
1870 strlcpy(value, temp_value, len);
1871 rc = 0;
1872 } else {
1873 /* Sadness, it's not there. Return the error */
1874 rc = -1;
1875 }
1876
1877out:
1878 return rc;
1879}
1880
1881/* Set the value of the specified field. */
1882int cryptfs_setfield(char *fieldname, char *value)
1883{
1884 struct crypt_persist_data stored_pdata;
1885 struct crypt_persist_data *pdata_p;
1886 struct crypt_mnt_ftr crypt_ftr;
1887 char encrypted_state[PROPERTY_VALUE_MAX];
1888 /* 0 is success, -1 is an error */
1889 int rc = -1;
1890 int encrypted = 0;
1891
1892 if (persist_data == NULL) {
1893 load_persistent_data();
1894 if (persist_data == NULL) {
1895 SLOGE("Setfield error, cannot load persistent data");
1896 goto out;
1897 }
1898 }
1899
1900 property_get("ro.crypto.state", encrypted_state, "");
1901 if (!strcmp(encrypted_state, "encrypted") ) {
1902 encrypted = 1;
1903 }
1904
1905 if (persist_set_key(fieldname, value, encrypted)) {
1906 goto out;
1907 }
1908
1909 /* If we are running encrypted, save the persistent data now */
1910 if (encrypted) {
1911 if (save_persistent_data()) {
1912 SLOGE("Setfield error, cannot save persistent data");
1913 goto out;
1914 }
1915 }
1916
1917 rc = 0;
1918
1919out:
1920 return rc;
1921}