blob: be6c476b82340c765850c5057a74bc70f96b6a11 [file] [log] [blame]
Dees_Troy51a0e822012-09-05 15:24:24 -04001/*
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>
36#include <openssl/sha.h>
37#include <errno.h>
38#include <cutils/android_reboot.h>
39#include <ext4.h>
40#include <linux/kdev_t.h>
41#include "../fs_mgr/include/fs_mgr.h"
42#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/android_reboot.h"
45#include "cutils/log.h"
46#include "cutils/properties.h"
47#include "hardware_legacy/power.h"
48//#include "VolumeManager.h"
49
50#define DM_CRYPT_BUF_SIZE 4096
51#define DATA_MNT_POINT "/data"
52
53#define HASH_COUNT 2000
54#define KEY_LEN_BYTES 16
55#define IV_LEN_BYTES 16
56
57#define KEY_IN_FOOTER "footer"
58
59#define EXT4_FS 1
60#define FAT_FS 2
61
62char *me = "cryptfs";
63
64static unsigned char saved_master_key[KEY_LEN_BYTES];
65static char *saved_data_blkdev;
66static char *saved_mount_point;
67static int master_key_saved = 0;
68#define FSTAB_PREFIX "/fstab."
69static char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
70
71static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
72{
73 memset(io, 0, dataSize);
74 io->data_size = dataSize;
75 io->data_start = sizeof(struct dm_ioctl);
76 io->version[0] = 4;
77 io->version[1] = 0;
78 io->version[2] = 0;
79 io->flags = flags;
80 if (name) {
81 strncpy(io->name, name, sizeof(io->name));
82 }
83}
84
85static unsigned int get_fs_size(char *dev)
86{
87 int fd, block_size;
88 struct ext4_super_block sb;
89 off64_t len;
90
91 if ((fd = open(dev, O_RDONLY)) < 0) {
92 SLOGE("Cannot open device to get filesystem size ");
93 return 0;
94 }
95
96 if (lseek64(fd, 1024, SEEK_SET) < 0) {
97 SLOGE("Cannot seek to superblock");
98 return 0;
99 }
100
101 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
102 SLOGE("Cannot read superblock");
103 return 0;
104 }
105
106 close(fd);
107
108 block_size = 1024 << sb.s_log_block_size;
109 /* compute length in bytes */
110 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
111
112 /* return length in sectors */
113 return (unsigned int) (len / 512);
114}
115
116static unsigned int get_blkdev_size(int fd)
117{
118 unsigned int nr_sec;
119
120 if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
121 nr_sec = 0;
122 }
123
124 return nr_sec;
125}
126
127/* Get and cache the name of the fstab file so we don't
128 * keep talking over the socket to the property service.
129 */
130static char *get_fstab_filename(void)
131{
132 if (fstab_filename[0] == 0) {
133 strcpy(fstab_filename, FSTAB_PREFIX);
134 property_get("ro.hardware", fstab_filename + sizeof(FSTAB_PREFIX) - 1, "");
135 }
136
137 return fstab_filename;
138}
139
140/* key or salt can be NULL, in which case just skip writing that value. Useful to
141 * update the failed mount count but not change the key.
142 */
143static int put_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
144 unsigned char *key, unsigned char *salt)
145{
146 int fd;
147 unsigned int nr_sec, cnt;
148 off64_t off;
149 int rc = -1;
150 char *fname;
151 char key_loc[PROPERTY_VALUE_MAX];
152 struct stat statbuf;
153
154 fs_mgr_get_crypt_info(get_fstab_filename(), key_loc, 0, sizeof(key_loc));
155
156 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
157 fname = real_blk_name;
158 if ( (fd = open(fname, O_RDWR)) < 0) {
159 SLOGE("Cannot open real block device %s\n", fname);
160 return -1;
161 }
162
163 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
164 SLOGE("Cannot get size of block device %s\n", fname);
165 goto errout;
166 }
167
168 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
169 * encryption info footer and key, and plenty of bytes to spare for future
170 * growth.
171 */
172 off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
173
174 if (lseek64(fd, off, SEEK_SET) == -1) {
175 SLOGE("Cannot seek to real block device footer\n");
176 goto errout;
177 }
178 } else if (key_loc[0] == '/') {
179 fname = key_loc;
180 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
181 SLOGE("Cannot open footer file %s\n", fname);
182 return -1;
183 }
184 } else {
185 SLOGE("Unexpected value for crypto key location\n");
186 return -1;;
187 }
188
189 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
190 SLOGE("Cannot write real block device footer\n");
191 goto errout;
192 }
193
194 if (key) {
195 if (crypt_ftr->keysize != KEY_LEN_BYTES) {
196 SLOGE("Keysize of %d bits not supported for real block device %s\n",
197 crypt_ftr->keysize*8, fname);
198 goto errout;
199 }
200
201 if ( (cnt = write(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
202 SLOGE("Cannot write key for real block device %s\n", fname);
203 goto errout;
204 }
205 }
206
207 if (salt) {
208 /* Compute the offset from the last write to the salt */
209 off = KEY_TO_SALT_PADDING;
210 if (! key)
211 off += crypt_ftr->keysize;
212
213 if (lseek64(fd, off, SEEK_CUR) == -1) {
214 SLOGE("Cannot seek to real block device salt \n");
215 goto errout;
216 }
217
218 if ( (cnt = write(fd, salt, SALT_LEN)) != SALT_LEN) {
219 SLOGE("Cannot write salt for real block device %s\n", fname);
220 goto errout;
221 }
222 }
223
224 fstat(fd, &statbuf);
225 /* If the keys are kept on a raw block device, do not try to truncate it. */
226 if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
227 if (ftruncate(fd, 0x4000)) {
228 SLOGE("Cannot set footer file size\n", fname);
229 goto errout;
230 }
231 }
232
233 /* Success! */
234 rc = 0;
235
236errout:
237 close(fd);
238 return rc;
239
240}
241
242static int get_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
243 unsigned char *key, unsigned char *salt)
244{
245 int fd;
246 unsigned int nr_sec, cnt;
247 off64_t off;
248 int rc = -1;
249 char key_loc[PROPERTY_VALUE_MAX];
250 char *fname;
251 struct stat statbuf;
252
253 fs_mgr_get_crypt_info(get_fstab_filename(), key_loc, 0, sizeof(key_loc));
254
255 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
256 fname = real_blk_name;
257 if ( (fd = open(fname, O_RDONLY)) < 0) {
258 SLOGE("Cannot open real block device %s\n", fname);
259 return -1;
260 }
261
262 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
263 SLOGE("Cannot get size of block device %s\n", fname);
264 goto errout;
265 }
266
267 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
268 * encryption info footer and key, and plenty of bytes to spare for future
269 * growth.
270 */
271 off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
272
273 if (lseek64(fd, off, SEEK_SET) == -1) {
274 SLOGE("Cannot seek to real block device footer\n");
275 goto errout;
276 }
277 } else if (key_loc[0] == '/') {
278 fname = key_loc;
279 if ( (fd = open(fname, O_RDONLY)) < 0) {
280 SLOGE("Cannot open footer file %s\n", fname);
281 return -1;
282 }
283
284 /* Make sure it's 16 Kbytes in length */
285 fstat(fd, &statbuf);
286 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
287 SLOGE("footer file %s is not the expected size!\n", fname);
288 goto errout;
289 }
290 } else {
291 SLOGE("Unexpected value for crypto key location\n");
292 return -1;;
293 }
294
295 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
296 SLOGE("Cannot read real block device footer\n");
297 goto errout;
298 }
299
300 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
301 SLOGE("Bad magic for real block device %s\n", fname);
302 goto errout;
303 }
304
305 if (crypt_ftr->major_version != 1) {
306 SLOGE("Cannot understand major version %d real block device footer\n",
307 crypt_ftr->major_version);
308 goto errout;
309 }
310
311 if (crypt_ftr->minor_version != 0) {
312 SLOGW("Warning: crypto footer minor version %d, expected 0, continuing...\n",
313 crypt_ftr->minor_version);
314 }
315
316 if (crypt_ftr->ftr_size > sizeof(struct crypt_mnt_ftr)) {
317 /* the footer size is bigger than we expected.
318 * Skip to it's stated end so we can read the key.
319 */
Dees_Troya13d74f2013-03-24 08:54:55 -0500320 if (lseek64(fd, crypt_ftr->ftr_size - sizeof(struct crypt_mnt_ftr), SEEK_CUR) == -1) {
Dees_Troy51a0e822012-09-05 15:24:24 -0400321 SLOGE("Cannot seek to start of key\n");
322 goto errout;
323 }
324 }
325
326 if (crypt_ftr->keysize != KEY_LEN_BYTES) {
327 SLOGE("Keysize of %d bits not supported for real block device %s\n",
328 crypt_ftr->keysize * 8, fname);
329 goto errout;
330 }
331
332 if ( (cnt = read(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
333 SLOGE("Cannot read key for real block device %s\n", fname);
334 goto errout;
335 }
336
337 if (lseek64(fd, KEY_TO_SALT_PADDING, SEEK_CUR) == -1) {
338 SLOGE("Cannot seek to real block device salt\n");
339 goto errout;
340 }
341
342 if ( (cnt = read(fd, salt, SALT_LEN)) != SALT_LEN) {
343 SLOGE("Cannot read salt for real block device %s\n", fname);
344 goto errout;
345 }
346
347 /* Success! */
348 rc = 0;
349
350errout:
351 close(fd);
352 return rc;
353}
354
355/* Convert a binary key of specified length into an ascii hex string equivalent,
356 * without the leading 0x and with null termination
357 */
358void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
359 char *master_key_ascii)
360{
361 unsigned int i, a;
362 unsigned char nibble;
363
364 for (i=0, a=0; i<keysize; i++, a+=2) {
365 /* For each byte, write out two ascii hex digits */
366 nibble = (master_key[i] >> 4) & 0xf;
367 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
368
369 nibble = master_key[i] & 0xf;
370 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
371 }
372
373 /* Add the null termination */
374 master_key_ascii[a] = '\0';
375
376}
377
378static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
379 char *real_blk_name, char *crypto_blk_name, const char *name)
380{
381 char buffer[DM_CRYPT_BUF_SIZE];
382 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
383 char *crypt_params;
384 struct dm_ioctl *io;
385 struct dm_target_spec *tgt;
386 unsigned int minor;
387 int fd;
388 int retval = -1;
389
390 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
391 SLOGE("Cannot open device-mapper\n");
392 goto errout;
393 }
394
395 io = (struct dm_ioctl *) buffer;
396
397 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
398 if (ioctl(fd, DM_DEV_CREATE, io)) {
399 SLOGE("Cannot create dm-crypt device\n");
400 goto errout;
401 }
402
403 /* Get the device status, in particular, the name of it's device file */
404 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
405 if (ioctl(fd, DM_DEV_STATUS, io)) {
406 SLOGE("Cannot retrieve dm-crypt device status\n");
407 goto errout;
408 }
409 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
410 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
411
412 /* Load the mapping table for this device */
413 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
414
415 ioctl_init(io, 4096, name, 0);
416 io->target_count = 1;
417 tgt->status = 0;
418 tgt->sector_start = 0;
419 tgt->length = crypt_ftr->fs_size;
420 strcpy(tgt->target_type, "crypt");
421
422 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
423 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
424 sprintf(crypt_params, "%s %s 0 %s 0", crypt_ftr->crypto_type_name,
425 master_key_ascii, real_blk_name);
426 crypt_params += strlen(crypt_params) + 1;
427 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
428 tgt->next = crypt_params - buffer;
429
430 if (ioctl(fd, DM_TABLE_LOAD, io)) {
431 SLOGE("Cannot load dm-crypt mapping table.\n");
432 goto errout;
433 }
434
435 /* Resume this device to activate it */
436 ioctl_init(io, 4096, name, 0);
437
438 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
439 SLOGE("Cannot resume the dm-crypt device\n");
440 goto errout;
441 }
442
443 /* We made it here with no errors. Woot! */
444 retval = 0;
445
446errout:
447 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
448
449 return retval;
450}
451
452static int delete_crypto_blk_dev(char *name)
453{
454 int fd;
455 char buffer[DM_CRYPT_BUF_SIZE];
456 struct dm_ioctl *io;
457 int retval = -1;
458
459 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
460 SLOGE("Cannot open device-mapper\n");
461 goto errout;
462 }
463
464 io = (struct dm_ioctl *) buffer;
465
466 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
467 if (ioctl(fd, DM_DEV_REMOVE, io)) {
468 SLOGE("Cannot remove dm-crypt device\n");
469 goto errout;
470 }
471
472 /* We made it here with no errors. Woot! */
473 retval = 0;
474
475errout:
476 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
477
478 return retval;
479
480}
481
482static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey)
483{
484 /* Turn the password into a key and IV that can decrypt the master key */
485 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
486 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
487}
488
489static int encrypt_master_key(char *passwd, unsigned char *salt,
490 unsigned char *decrypted_master_key,
491 unsigned char *encrypted_master_key)
492{
493 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
494 EVP_CIPHER_CTX e_ctx;
495 int encrypted_len, final_len;
496
497 /* Turn the password into a key and IV that can decrypt the master key */
498 pbkdf2(passwd, salt, ikey);
499
500 /* Initialize the decryption engine */
501 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
502 SLOGE("EVP_EncryptInit failed\n");
503 return -1;
504 }
505 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
506
507 /* Encrypt the master key */
508 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
509 decrypted_master_key, KEY_LEN_BYTES)) {
510 SLOGE("EVP_EncryptUpdate failed\n");
511 return -1;
512 }
513 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
514 SLOGE("EVP_EncryptFinal failed\n");
515 return -1;
516 }
517
518 if (encrypted_len + final_len != KEY_LEN_BYTES) {
519 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
520 return -1;
521 } else {
522 return 0;
523 }
524}
525
526static int decrypt_master_key(char *passwd, unsigned char *salt,
527 unsigned char *encrypted_master_key,
528 unsigned char *decrypted_master_key)
529{
530 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
531 EVP_CIPHER_CTX d_ctx;
532 int decrypted_len, final_len;
533
534 /* Turn the password into a key and IV that can decrypt the master key */
535 pbkdf2(passwd, salt, ikey);
536
537 /* Initialize the decryption engine */
538 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
539 return -1;
540 }
541 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
542 /* Decrypt the master key */
543 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
544 encrypted_master_key, KEY_LEN_BYTES)) {
545 return -1;
546 }
547 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
548 return -1;
549 }
550
551 if (decrypted_len + final_len != KEY_LEN_BYTES) {
552 return -1;
553 } else {
554 return 0;
555 }
556}
557
558static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt)
559{
560 int fd;
561 unsigned char key_buf[KEY_LEN_BYTES];
562 EVP_CIPHER_CTX e_ctx;
563 int encrypted_len, final_len;
564
565 /* Get some random bits for a key */
566 fd = open("/dev/urandom", O_RDONLY);
567 read(fd, key_buf, sizeof(key_buf));
568 read(fd, salt, SALT_LEN);
569 close(fd);
570
571 /* Now encrypt it with the password */
572 return encrypt_master_key(passwd, salt, key_buf, master_key);
573}
574
575static int wait_and_unmount(char *mountpoint)
576{
577 int i, rc;
578#define WAIT_UNMOUNT_COUNT 20
579
580 /* Now umount the tmpfs filesystem */
581 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
582 if (umount(mountpoint)) {
583 if (errno == EINVAL) {
584 /* EINVAL is returned if the directory is not a mountpoint,
585 * i.e. there is no filesystem mounted there. So just get out.
586 */
587 break;
588 }
589 sleep(1);
590 i++;
591 } else {
592 break;
593 }
594 }
595
596 if (i < WAIT_UNMOUNT_COUNT) {
597 SLOGD("unmounting %s succeeded\n", mountpoint);
598 rc = 0;
599 } else {
600 SLOGE("unmounting %s failed\n", mountpoint);
601 rc = -1;
602 }
603
604 return rc;
605}
606
607#define DATA_PREP_TIMEOUT 100
608static int prep_data_fs(void)
609{
610 int i;
611
612 /* Do the prep of the /data filesystem */
613 property_set("vold.post_fs_data_done", "0");
614 property_set("vold.decrypt", "trigger_post_fs_data");
615 SLOGD("Just triggered post_fs_data\n");
616
617 /* Wait a max of 25 seconds, hopefully it takes much less */
618 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
619 char p[PROPERTY_VALUE_MAX];
620
621 property_get("vold.post_fs_data_done", p, "0");
622 if (*p == '1') {
623 break;
624 } else {
625 usleep(250000);
626 }
627 }
628 if (i == DATA_PREP_TIMEOUT) {
629 /* Ugh, we failed to prep /data in time. Bail. */
630 return -1;
631 } else {
632 SLOGD("post_fs_data done\n");
633 return 0;
634 }
635}
636
637int cryptfs_restart(void)
638{
639 char fs_type[32];
640 char real_blkdev[MAXPATHLEN];
641 char crypto_blkdev[MAXPATHLEN];
642 char fs_options[256];
643 unsigned long mnt_flags;
644 struct stat statbuf;
645 int rc = -1, i;
646 static int restart_successful = 0;
647
648 /* Validate that it's OK to call this routine */
649 if (! master_key_saved) {
650 SLOGE("Encrypted filesystem not validated, aborting");
651 return -1;
652 }
653
654 if (restart_successful) {
655 SLOGE("System already restarted with encrypted disk, aborting");
656 return -1;
657 }
658
659 /* Here is where we shut down the framework. The init scripts
660 * start all services in one of three classes: core, main or late_start.
661 * On boot, we start core and main. Now, we stop main, but not core,
662 * as core includes vold and a few other really important things that
663 * we need to keep running. Once main has stopped, we should be able
664 * to umount the tmpfs /data, then mount the encrypted /data.
665 * We then restart the class main, and also the class late_start.
666 * At the moment, I've only put a few things in late_start that I know
667 * are not needed to bring up the framework, and that also cause problems
668 * with unmounting the tmpfs /data, but I hope to add add more services
669 * to the late_start class as we optimize this to decrease the delay
670 * till the user is asked for the password to the filesystem.
671 */
672
673 /* The init files are setup to stop the class main when vold.decrypt is
674 * set to trigger_reset_main.
675 */
676 property_set("vold.decrypt", "trigger_reset_main");
677 SLOGD("Just asked init to shut down class main\n");
678
679 /* Now that the framework is shutdown, we should be able to umount()
680 * the tmpfs filesystem, and mount the real one.
681 */
682
683 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
684 if (strlen(crypto_blkdev) == 0) {
685 SLOGE("fs_crypto_blkdev not set\n");
686 return -1;
687 }
688
689 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
690 /* If that succeeded, then mount the decrypted filesystem */
691 fs_mgr_do_mount(get_fstab_filename(), DATA_MNT_POINT, crypto_blkdev, 0);
692
693 property_set("vold.decrypt", "trigger_load_persist_props");
694 /* Create necessary paths on /data */
695 if (prep_data_fs()) {
696 return -1;
697 }
698
699 /* startup service classes main and late_start */
700 property_set("vold.decrypt", "trigger_restart_framework");
701 SLOGD("Just triggered restart_framework\n");
702
703 /* Give it a few moments to get started */
704 sleep(1);
705 }
706
707 if (rc == 0) {
708 restart_successful = 1;
709 }
710
711 return rc;
712}
713
714static int do_crypto_complete(char *mount_point)
715{
716 struct crypt_mnt_ftr crypt_ftr;
717 unsigned char encrypted_master_key[32];
718 unsigned char salt[SALT_LEN];
719 char real_blkdev[MAXPATHLEN];
720 char encrypted_state[PROPERTY_VALUE_MAX];
721 char key_loc[PROPERTY_VALUE_MAX];
722
723 property_get("ro.crypto.state", encrypted_state, "");
724 if (strcmp(encrypted_state, "encrypted") ) {
725 SLOGE("not running with encryption, aborting");
726 return 1;
727 }
728
729 fs_mgr_get_crypt_info(get_fstab_filename(), 0, real_blkdev, sizeof(real_blkdev));
730
731 if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
732 fs_mgr_get_crypt_info(get_fstab_filename(), key_loc, 0, sizeof(key_loc));
733
734 /*
735 * Only report this error if key_loc is a file and it exists.
736 * If the device was never encrypted, and /data is not mountable for
737 * some reason, returning 1 should prevent the UI from presenting the
738 * a "enter password" screen, or worse, a "press button to wipe the
739 * device" screen.
740 */
741 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
742 SLOGE("master key file does not exist, aborting");
743 return 1;
744 } else {
745 SLOGE("Error getting crypt footer and key\n");
746 return -1;
747 }
748 }
749
750 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
751 SLOGE("Encryption process didn't finish successfully\n");
752 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
753 * and give the user an option to wipe the disk */
754 }
755
756 /* We passed the test! We shall diminish, and return to the west */
757 return 0;
758}
759
760static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
761{
762 struct crypt_mnt_ftr crypt_ftr;
763 /* Allocate enough space for a 256 bit key, but we may use less */
764 unsigned char encrypted_master_key[32], decrypted_master_key[32];
765 unsigned char salt[SALT_LEN];
766 char crypto_blkdev[MAXPATHLEN];
767 char real_blkdev[MAXPATHLEN];
768 char tmp_mount_point[64];
769 unsigned int orig_failed_decrypt_count;
770 char encrypted_state[PROPERTY_VALUE_MAX];
771 int rc;
772
773 property_get("ro.crypto.state", encrypted_state, "");
774 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
775 SLOGE("encrypted fs already validated or not running with encryption, aborting");
776 return -1;
777 }
778
779 fs_mgr_get_crypt_info(get_fstab_filename(), 0, real_blkdev, sizeof(real_blkdev));
780
781 if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
782 SLOGE("Error getting crypt footer and key\n");
783 return -1;
784 }
785
786 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
787 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
788
789 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
790 decrypt_master_key(passwd, salt, encrypted_master_key, decrypted_master_key);
791 }
792
793 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
794 real_blkdev, crypto_blkdev, label)) {
795 SLOGE("Error creating decrypted block device\n");
796 return -1;
797 }
798
799 /* If init detects an encrypted filesystme, it writes a file for each such
800 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
801 * files and passes that data to me */
802 /* Create a tmp mount point to try mounting the decryptd fs
803 * Since we're here, the mount_point should be a tmpfs filesystem, so make
804 * a directory in it to test mount the decrypted filesystem.
805 */
806 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
807 mkdir(tmp_mount_point, 0755);
808 if (fs_mgr_do_mount(get_fstab_filename(), DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
809 SLOGE("Error temp mounting decrypted block device\n");
810 delete_crypto_blk_dev(label);
811 crypt_ftr.failed_decrypt_count++;
812 } else {
813 /* Success, so just umount and we'll mount it properly when we restart
814 * the framework.
815 */
816 umount(tmp_mount_point);
817 crypt_ftr.failed_decrypt_count = 0;
818 }
819
820 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
821 put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0, 0);
822 }
823
824 if (crypt_ftr.failed_decrypt_count) {
825 /* We failed to mount the device, so return an error */
826 rc = crypt_ftr.failed_decrypt_count;
827
828 } else {
829 /* Woot! Success! Save the name of the crypto block device
830 * so we can mount it when restarting the framework.
831 */
832 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
833
834 /* Also save a the master key so we can reencrypted the key
835 * the key when we want to change the password on it.
836 */
837 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
838 saved_data_blkdev = strdup(real_blkdev);
839 saved_mount_point = strdup(mount_point);
840 master_key_saved = 1;
841 rc = 0;
842 }
843
844 return rc;
845}
846
847/* Called by vold when it wants to undo the crypto mapping of a volume it
848 * manages. This is usually in response to a factory reset, when we want
849 * to undo the crypto mapping so the volume is formatted in the clear.
850 */
851int cryptfs_revert_volume(const char *label)
852{
853 return delete_crypto_blk_dev((char *)label);
854}
855
856/*
857 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
858 * Setup a dm-crypt mapping, use the saved master key from
859 * setting up the /data mapping, and return the new device path.
860 */
861int cryptfs_setup_volume(const char *label, int major, int minor,
862 char *crypto_sys_path, unsigned int max_path,
863 int *new_major, int *new_minor)
864{
865 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
866 struct crypt_mnt_ftr sd_crypt_ftr;
867 unsigned char key[32], salt[32];
868 struct stat statbuf;
869 int nr_sec, fd;
870
871 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
872
873 /* Just want the footer, but gotta get it all */
874 get_crypt_ftr_and_key(saved_data_blkdev, &sd_crypt_ftr, key, salt);
875
876 /* Update the fs_size field to be the size of the volume */
877 fd = open(real_blkdev, O_RDONLY);
878 nr_sec = get_blkdev_size(fd);
879 close(fd);
880 if (nr_sec == 0) {
881 SLOGE("Cannot get size of volume %s\n", real_blkdev);
882 return -1;
883 }
884
885 sd_crypt_ftr.fs_size = nr_sec;
886 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
887 crypto_blkdev, label);
888
889 stat(crypto_blkdev, &statbuf);
890 *new_major = MAJOR(statbuf.st_rdev);
891 *new_minor = MINOR(statbuf.st_rdev);
892
893 /* Create path to sys entry for this block device */
894 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
895
896 return 0;
897}
898
899int cryptfs_crypto_complete(void)
900{
901 return do_crypto_complete("/data");
902}
903
904int cryptfs_check_passwd(char *passwd)
905{
906 int rc = -1;
907
908 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
909
910 return rc;
911}
912
913int cryptfs_verify_passwd(char *passwd)
914{
915 struct crypt_mnt_ftr crypt_ftr;
916 /* Allocate enough space for a 256 bit key, but we may use less */
917 unsigned char encrypted_master_key[32], decrypted_master_key[32];
918 unsigned char salt[SALT_LEN];
919 char real_blkdev[MAXPATHLEN];
920 char encrypted_state[PROPERTY_VALUE_MAX];
921 int rc;
922
923 property_get("ro.crypto.state", encrypted_state, "");
924 if (strcmp(encrypted_state, "encrypted") ) {
925 SLOGE("device not encrypted, aborting");
926 return -2;
927 }
928
929 if (!master_key_saved) {
930 SLOGE("encrypted fs not yet mounted, aborting");
931 return -1;
932 }
933
934 if (!saved_mount_point) {
935 SLOGE("encrypted fs failed to save mount point, aborting");
936 return -1;
937 }
938
939 fs_mgr_get_crypt_info(get_fstab_filename(), 0, real_blkdev, sizeof(real_blkdev));
940
941 if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
942 SLOGE("Error getting crypt footer and key\n");
943 return -1;
944 }
945
946 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
947 /* If the device has no password, then just say the password is valid */
948 rc = 0;
949 } else {
950 decrypt_master_key(passwd, salt, encrypted_master_key, decrypted_master_key);
951 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
952 /* They match, the password is correct */
953 rc = 0;
954 } else {
955 /* If incorrect, sleep for a bit to prevent dictionary attacks */
956 sleep(1);
957 rc = 1;
958 }
959 }
960
961 return rc;
962}
963
964/* Initialize a crypt_mnt_ftr structure. The keysize is
965 * defaulted to 16 bytes, and the filesystem size to 0.
966 * Presumably, at a minimum, the caller will update the
967 * filesystem size and crypto_type_name after calling this function.
968 */
969static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
970{
971 ftr->magic = CRYPT_MNT_MAGIC;
972 ftr->major_version = 1;
973 ftr->minor_version = 0;
974 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
975 ftr->flags = 0;
976 ftr->keysize = KEY_LEN_BYTES;
977 ftr->spare1 = 0;
978 ftr->fs_size = 0;
979 ftr->failed_decrypt_count = 0;
980 ftr->crypto_type_name[0] = '\0';
981}
982
983static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
984{
985 char cmdline[256];
986 int rc = -1;
987
988 if (type == EXT4_FS) {
989 snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
990 size * 512, crypto_blkdev);
991 SLOGI("Making empty filesystem with command %s\n", cmdline);
992 } else if (type== FAT_FS) {
993 snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
994 size, crypto_blkdev);
995 SLOGI("Making empty filesystem with command %s\n", cmdline);
996 } else {
997 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
998 return -1;
999 }
1000
1001 if (system(cmdline)) {
1002 SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
1003 } else {
1004 SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
1005 rc = 0;
1006 }
1007
1008 return rc;
1009}
1010
1011static inline int unix_read(int fd, void* buff, int len)
1012{
1013 int ret;
1014 do { ret = read(fd, buff, len); } while (ret < 0 && errno == EINTR);
1015 return ret;
1016}
1017
1018static inline int unix_write(int fd, const void* buff, int len)
1019{
1020 int ret;
1021 do { ret = write(fd, buff, len); } while (ret < 0 && errno == EINTR);
1022 return ret;
1023}
1024
1025#define CRYPT_INPLACE_BUFSIZE 4096
1026#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
1027static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1028 off64_t *size_already_done, off64_t tot_size)
1029{
1030 int realfd, cryptofd;
1031 char *buf[CRYPT_INPLACE_BUFSIZE];
1032 int rc = -1;
1033 off64_t numblocks, i, remainder;
1034 off64_t one_pct, cur_pct, new_pct;
1035 off64_t blocks_already_done, tot_numblocks;
1036
1037 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1038 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1039 return -1;
1040 }
1041
1042 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1043 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1044 close(realfd);
1045 return -1;
1046 }
1047
1048 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1049 * The size passed in is the number of 512 byte sectors in the filesystem.
1050 * So compute the number of whole 4K blocks we should read/write,
1051 * and the remainder.
1052 */
1053 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1054 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
1055 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1056 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1057
1058 SLOGE("Encrypting filesystem in place...");
1059
1060 one_pct = tot_numblocks / 100;
1061 cur_pct = 0;
1062 /* process the majority of the filesystem in blocks */
1063 for (i=0; i<numblocks; i++) {
1064 new_pct = (i + blocks_already_done) / one_pct;
1065 if (new_pct > cur_pct) {
1066 char buf[8];
1067
1068 cur_pct = new_pct;
1069 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1070 property_set("vold.encrypt_progress", buf);
1071 }
1072 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1073 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1074 goto errout;
1075 }
1076 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1077 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1078 goto errout;
1079 }
1080 }
1081
1082 /* Do any remaining sectors */
1083 for (i=0; i<remainder; i++) {
1084 if (unix_read(realfd, buf, 512) <= 0) {
1085 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1086 goto errout;
1087 }
1088 if (unix_write(cryptofd, buf, 512) <= 0) {
1089 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1090 goto errout;
1091 }
1092 }
1093
1094 *size_already_done += size;
1095 rc = 0;
1096
1097errout:
1098 close(realfd);
1099 close(cryptofd);
1100
1101 return rc;
1102}
1103
1104#define CRYPTO_ENABLE_WIPE 1
1105#define CRYPTO_ENABLE_INPLACE 2
1106
1107#define FRAMEWORK_BOOT_WAIT 60
1108
1109static inline int should_encrypt(struct volume_info *volume)
1110{
1111 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1112 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1113}
1114
1115int cryptfs_enable(char *howarg, char *passwd)
1116{
1117 // Code removed because it needs other parts of vold that aren't needed for decryption
1118 return -1;
1119}
1120
1121int cryptfs_changepw(char *newpw)
1122{
1123 struct crypt_mnt_ftr crypt_ftr;
1124 unsigned char encrypted_master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
1125 unsigned char salt[SALT_LEN];
1126 char real_blkdev[MAXPATHLEN];
1127
1128 /* This is only allowed after we've successfully decrypted the master key */
1129 if (! master_key_saved) {
1130 SLOGE("Key not saved, aborting");
1131 return -1;
1132 }
1133
1134 fs_mgr_get_crypt_info(get_fstab_filename(), 0, real_blkdev, sizeof(real_blkdev));
1135 if (strlen(real_blkdev) == 0) {
1136 SLOGE("Can't find real blkdev");
1137 return -1;
1138 }
1139
1140 /* get key */
1141 if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
1142 SLOGE("Error getting crypt footer and key");
1143 return -1;
1144 }
1145
1146 encrypt_master_key(newpw, salt, saved_master_key, encrypted_master_key);
1147
1148 /* save the key */
1149 put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt);
1150
1151 return 0;
1152}