cryptfs.c revision 0b8b59719357fb80c330442787f7d5b1e332263b
1/*
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 "cryptfs.h"
42#define LOG_TAG "Cryptfs"
43#include "cutils/log.h"
44#include "cutils/properties.h"
45#include "hardware_legacy/power.h"
46#include "VolumeManager.h"
47
48#define DM_CRYPT_BUF_SIZE 4096
49#define DATA_MNT_POINT "/data"
50
51#define HASH_COUNT 2000
52#define KEY_LEN_BYTES 16
53#define IV_LEN_BYTES 16
54
55#define KEY_LOC_PROP   "ro.crypto.keyfile.userdata"
56#define KEY_IN_FOOTER  "footer"
57
58#define EXT4_FS 1
59#define FAT_FS 2
60
61char *me = "cryptfs";
62
63static unsigned char saved_master_key[KEY_LEN_BYTES];
64static char *saved_data_blkdev;
65static int  master_key_saved = 0;
66
67static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
68{
69    memset(io, 0, dataSize);
70    io->data_size = dataSize;
71    io->data_start = sizeof(struct dm_ioctl);
72    io->version[0] = 4;
73    io->version[1] = 0;
74    io->version[2] = 0;
75    io->flags = flags;
76    if (name) {
77        strncpy(io->name, name, sizeof(io->name));
78    }
79}
80
81static unsigned int get_fs_size(char *dev)
82{
83    int fd, block_size;
84    struct ext4_super_block sb;
85    off64_t len;
86
87    if ((fd = open(dev, O_RDONLY)) < 0) {
88        SLOGE("Cannot open device to get filesystem size ");
89        return 0;
90    }
91
92    if (lseek64(fd, 1024, SEEK_SET) < 0) {
93        SLOGE("Cannot seek to superblock");
94        return 0;
95    }
96
97    if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
98        SLOGE("Cannot read superblock");
99        return 0;
100    }
101
102    close(fd);
103
104    block_size = 1024 << sb.s_log_block_size;
105    /* compute length in bytes */
106    len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
107
108    /* return length in sectors */
109    return (unsigned int) (len / 512);
110}
111
112static unsigned int get_blkdev_size(int fd)
113{
114  unsigned int nr_sec;
115
116  if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
117    nr_sec = 0;
118  }
119
120  return nr_sec;
121}
122
123/* key or salt can be NULL, in which case just skip writing that value.  Useful to
124 * update the failed mount count but not change the key.
125 */
126static int put_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
127                                  unsigned char *key, unsigned char *salt)
128{
129  int fd;
130  unsigned int nr_sec, cnt;
131  off64_t off;
132  int rc = -1;
133  char *fname;
134  char key_loc[PROPERTY_VALUE_MAX];
135
136  property_get(KEY_LOC_PROP, key_loc, KEY_IN_FOOTER);
137
138  if (!strcmp(key_loc, KEY_IN_FOOTER)) {
139    fname = real_blk_name;
140    if ( (fd = open(fname, O_RDWR)) < 0) {
141      SLOGE("Cannot open real block device %s\n", fname);
142      return -1;
143    }
144
145    if ( (nr_sec = get_blkdev_size(fd)) == 0) {
146      SLOGE("Cannot get size of block device %s\n", fname);
147      goto errout;
148    }
149
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    off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
155
156    if (lseek64(fd, off, SEEK_SET) == -1) {
157      SLOGE("Cannot seek to real block device footer\n");
158      goto errout;
159    }
160  } else if (key_loc[0] == '/') {
161    fname = key_loc;
162    if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
163      SLOGE("Cannot open footer file %s\n", fname);
164      return -1;
165    }
166  } else {
167    SLOGE("Unexpected value for" KEY_LOC_PROP "\n");
168    return -1;;
169  }
170
171  if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
172    SLOGE("Cannot write real block device footer\n");
173    goto errout;
174  }
175
176  if (key) {
177    if (crypt_ftr->keysize != KEY_LEN_BYTES) {
178      SLOGE("Keysize of %d bits not supported for real block device %s\n",
179            crypt_ftr->keysize*8, fname);
180      goto errout;
181    }
182
183    if ( (cnt = write(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
184      SLOGE("Cannot write key for real block device %s\n", fname);
185      goto errout;
186    }
187  }
188
189  if (salt) {
190    /* Compute the offset from the last write to the salt */
191    off = KEY_TO_SALT_PADDING;
192    if (! key)
193      off += crypt_ftr->keysize;
194
195    if (lseek64(fd, off, SEEK_CUR) == -1) {
196      SLOGE("Cannot seek to real block device salt \n");
197      goto errout;
198    }
199
200    if ( (cnt = write(fd, salt, SALT_LEN)) != SALT_LEN) {
201      SLOGE("Cannot write salt for real block device %s\n", fname);
202      goto errout;
203    }
204  }
205
206  if (key_loc[0] == '/') {
207    if (ftruncate(fd, 0x4000)) {
208      SLOGE("Cannot set footer file sizen", fname);
209      goto errout;
210    }
211  }
212
213  /* Success! */
214  rc = 0;
215
216errout:
217  close(fd);
218  return rc;
219
220}
221
222static int get_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
223                                  unsigned char *key, unsigned char *salt)
224{
225  int fd;
226  unsigned int nr_sec, cnt;
227  off64_t off;
228  int rc = -1;
229  char key_loc[PROPERTY_VALUE_MAX];
230  char *fname;
231  struct stat statbuf;
232
233  property_get(KEY_LOC_PROP, key_loc, KEY_IN_FOOTER);
234
235  if (!strcmp(key_loc, KEY_IN_FOOTER)) {
236    fname = real_blk_name;
237    if ( (fd = open(fname, O_RDONLY)) < 0) {
238      SLOGE("Cannot open real block device %s\n", fname);
239      return -1;
240    }
241
242    if ( (nr_sec = get_blkdev_size(fd)) == 0) {
243      SLOGE("Cannot get size of block device %s\n", fname);
244      goto errout;
245    }
246
247    /* If it's an encrypted Android partition, the last 16 Kbytes contain the
248     * encryption info footer and key, and plenty of bytes to spare for future
249     * growth.
250     */
251    off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
252
253    if (lseek64(fd, off, SEEK_SET) == -1) {
254      SLOGE("Cannot seek to real block device footer\n");
255      goto errout;
256    }
257  } else if (key_loc[0] == '/') {
258    fname = key_loc;
259    if ( (fd = open(fname, O_RDONLY)) < 0) {
260      SLOGE("Cannot open footer file %s\n", fname);
261      return -1;
262    }
263
264    /* Make sure it's 16 Kbytes in length */
265    fstat(fd, &statbuf);
266    if (statbuf.st_size != 0x4000) {
267      SLOGE("footer file %s is not the expected size!\n", fname);
268      goto errout;
269    }
270  } else {
271    SLOGE("Unexpected value for" KEY_LOC_PROP "\n");
272    return -1;;
273  }
274
275  if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
276    SLOGE("Cannot read real block device footer\n");
277    goto errout;
278  }
279
280  if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
281    SLOGE("Bad magic for real block device %s\n", fname);
282    goto errout;
283  }
284
285  if (crypt_ftr->major_version != 1) {
286    SLOGE("Cannot understand major version %d real block device footer\n",
287          crypt_ftr->major_version);
288    goto errout;
289  }
290
291  if (crypt_ftr->minor_version != 0) {
292    SLOGW("Warning: crypto footer minor version %d, expected 0, continuing...\n",
293          crypt_ftr->minor_version);
294  }
295
296  if (crypt_ftr->ftr_size > sizeof(struct crypt_mnt_ftr)) {
297    /* the footer size is bigger than we expected.
298     * Skip to it's stated end so we can read the key.
299     */
300    if (lseek(fd, crypt_ftr->ftr_size - sizeof(struct crypt_mnt_ftr),  SEEK_CUR) == -1) {
301      SLOGE("Cannot seek to start of key\n");
302      goto errout;
303    }
304  }
305
306  if (crypt_ftr->keysize != KEY_LEN_BYTES) {
307    SLOGE("Keysize of %d bits not supported for real block device %s\n",
308          crypt_ftr->keysize * 8, fname);
309    goto errout;
310  }
311
312  if ( (cnt = read(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
313    SLOGE("Cannot read key for real block device %s\n", fname);
314    goto errout;
315  }
316
317  if (lseek64(fd, KEY_TO_SALT_PADDING, SEEK_CUR) == -1) {
318    SLOGE("Cannot seek to real block device salt\n");
319    goto errout;
320  }
321
322  if ( (cnt = read(fd, salt, SALT_LEN)) != SALT_LEN) {
323    SLOGE("Cannot read salt for real block device %s\n", fname);
324    goto errout;
325  }
326
327  /* Success! */
328  rc = 0;
329
330errout:
331  close(fd);
332  return rc;
333}
334
335/* Convert a binary key of specified length into an ascii hex string equivalent,
336 * without the leading 0x and with null termination
337 */
338void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
339                              char *master_key_ascii)
340{
341  unsigned int i, a;
342  unsigned char nibble;
343
344  for (i=0, a=0; i<keysize; i++, a+=2) {
345    /* For each byte, write out two ascii hex digits */
346    nibble = (master_key[i] >> 4) & 0xf;
347    master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
348
349    nibble = master_key[i] & 0xf;
350    master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
351  }
352
353  /* Add the null termination */
354  master_key_ascii[a] = '\0';
355
356}
357
358static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
359                                    char *real_blk_name, char *crypto_blk_name, const char *name)
360{
361  char buffer[DM_CRYPT_BUF_SIZE];
362  char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
363  char *crypt_params;
364  struct dm_ioctl *io;
365  struct dm_target_spec *tgt;
366  unsigned int minor;
367  int fd;
368  int retval = -1;
369
370  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
371    SLOGE("Cannot open device-mapper\n");
372    goto errout;
373  }
374
375  io = (struct dm_ioctl *) buffer;
376
377  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
378  if (ioctl(fd, DM_DEV_CREATE, io)) {
379    SLOGE("Cannot create dm-crypt device\n");
380    goto errout;
381  }
382
383  /* Get the device status, in particular, the name of it's device file */
384  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
385  if (ioctl(fd, DM_DEV_STATUS, io)) {
386    SLOGE("Cannot retrieve dm-crypt device status\n");
387    goto errout;
388  }
389  minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
390  snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
391
392  /* Load the mapping table for this device */
393  tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
394
395  ioctl_init(io, 4096, name, 0);
396  io->target_count = 1;
397  tgt->status = 0;
398  tgt->sector_start = 0;
399  tgt->length = crypt_ftr->fs_size;
400  strcpy(tgt->target_type, "crypt");
401
402  crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
403  convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
404  sprintf(crypt_params, "%s %s 0 %s 0", crypt_ftr->crypto_type_name,
405          master_key_ascii, real_blk_name);
406  crypt_params += strlen(crypt_params) + 1;
407  crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
408  tgt->next = crypt_params - buffer;
409
410  if (ioctl(fd, DM_TABLE_LOAD, io)) {
411      SLOGE("Cannot load dm-crypt mapping table.\n");
412      goto errout;
413  }
414
415  /* Resume this device to activate it */
416  ioctl_init(io, 4096, name, 0);
417
418  if (ioctl(fd, DM_DEV_SUSPEND, io)) {
419    SLOGE("Cannot resume the dm-crypt device\n");
420    goto errout;
421  }
422
423  /* We made it here with no errors.  Woot! */
424  retval = 0;
425
426errout:
427  close(fd);   /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
428
429  return retval;
430}
431
432static int delete_crypto_blk_dev(char *name)
433{
434  int fd;
435  char buffer[DM_CRYPT_BUF_SIZE];
436  struct dm_ioctl *io;
437  int retval = -1;
438
439  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
440    SLOGE("Cannot open device-mapper\n");
441    goto errout;
442  }
443
444  io = (struct dm_ioctl *) buffer;
445
446  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
447  if (ioctl(fd, DM_DEV_REMOVE, io)) {
448    SLOGE("Cannot remove dm-crypt device\n");
449    goto errout;
450  }
451
452  /* We made it here with no errors.  Woot! */
453  retval = 0;
454
455errout:
456  close(fd);    /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
457
458  return retval;
459
460}
461
462static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey)
463{
464    /* Turn the password into a key and IV that can decrypt the master key */
465    PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
466                           HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
467}
468
469static int encrypt_master_key(char *passwd, unsigned char *salt,
470                              unsigned char *decrypted_master_key,
471                              unsigned char *encrypted_master_key)
472{
473    unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
474    EVP_CIPHER_CTX e_ctx;
475    int encrypted_len, final_len;
476
477    /* Turn the password into a key and IV that can decrypt the master key */
478    pbkdf2(passwd, salt, ikey);
479
480    /* Initialize the decryption engine */
481    if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
482        SLOGE("EVP_EncryptInit failed\n");
483        return -1;
484    }
485    EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
486
487    /* Encrypt the master key */
488    if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
489                              decrypted_master_key, KEY_LEN_BYTES)) {
490        SLOGE("EVP_EncryptUpdate failed\n");
491        return -1;
492    }
493    if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
494        SLOGE("EVP_EncryptFinal failed\n");
495        return -1;
496    }
497
498    if (encrypted_len + final_len != KEY_LEN_BYTES) {
499        SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
500        return -1;
501    } else {
502        return 0;
503    }
504}
505
506static int decrypt_master_key(char *passwd, unsigned char *salt,
507                              unsigned char *encrypted_master_key,
508                              unsigned char *decrypted_master_key)
509{
510  unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
511  EVP_CIPHER_CTX d_ctx;
512  int decrypted_len, final_len;
513
514  /* Turn the password into a key and IV that can decrypt the master key */
515  pbkdf2(passwd, salt, ikey);
516
517  /* Initialize the decryption engine */
518  if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
519    return -1;
520  }
521  EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
522  /* Decrypt the master key */
523  if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
524                            encrypted_master_key, KEY_LEN_BYTES)) {
525    return -1;
526  }
527  if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
528    return -1;
529  }
530
531  if (decrypted_len + final_len != KEY_LEN_BYTES) {
532    return -1;
533  } else {
534    return 0;
535  }
536}
537
538static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt)
539{
540    int fd;
541    unsigned char key_buf[KEY_LEN_BYTES];
542    EVP_CIPHER_CTX e_ctx;
543    int encrypted_len, final_len;
544
545    /* Get some random bits for a key */
546    fd = open("/dev/urandom", O_RDONLY);
547    read(fd, key_buf, sizeof(key_buf));
548    read(fd, salt, SALT_LEN);
549    close(fd);
550
551    /* Now encrypt it with the password */
552    return encrypt_master_key(passwd, salt, key_buf, master_key);
553}
554
555static int get_orig_mount_parms(char *mount_point, char *fs_type, char *real_blkdev,
556                                unsigned long *mnt_flags, char *fs_options)
557{
558  char mount_point2[PROPERTY_VALUE_MAX];
559  char fs_flags[PROPERTY_VALUE_MAX];
560
561  property_get("ro.crypto.fs_type", fs_type, "");
562  property_get("ro.crypto.fs_real_blkdev", real_blkdev, "");
563  property_get("ro.crypto.fs_mnt_point", mount_point2, "");
564  property_get("ro.crypto.fs_options", fs_options, "");
565  property_get("ro.crypto.fs_flags", fs_flags, "");
566  *mnt_flags = strtol(fs_flags, 0, 0);
567
568  if (strcmp(mount_point, mount_point2)) {
569    /* Consistency check.  These should match. If not, something odd happened. */
570    return -1;
571  }
572
573  return 0;
574}
575
576static int wait_and_unmount(char *mountpoint)
577{
578    int i, rc;
579#define WAIT_UNMOUNT_COUNT 20
580
581    /*  Now umount the tmpfs filesystem */
582    for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
583        if (umount(mountpoint)) {
584            if (errno == EINVAL) {
585                /* EINVAL is returned if the directory is not a mountpoint,
586                 * i.e. there is no filesystem mounted there.  So just get out.
587                 */
588                break;
589            }
590            sleep(1);
591            i++;
592        } else {
593          break;
594        }
595    }
596
597    if (i < WAIT_UNMOUNT_COUNT) {
598      SLOGD("unmounting %s succeeded\n", mountpoint);
599      rc = 0;
600    } else {
601      SLOGE("unmounting %s failed\n", mountpoint);
602      rc = -1;
603    }
604
605    return rc;
606}
607
608#define DATA_PREP_TIMEOUT 100
609static int prep_data_fs(void)
610{
611    int i;
612
613    /* Do the prep of the /data filesystem */
614    property_set("vold.post_fs_data_done", "0");
615    property_set("vold.decrypt", "trigger_post_fs_data");
616    SLOGD("Just triggered post_fs_data\n");
617
618    /* Wait a max of 25 seconds, hopefully it takes much less */
619    for (i=0; i<DATA_PREP_TIMEOUT; i++) {
620        char p[PROPERTY_VALUE_MAX];
621
622        property_get("vold.post_fs_data_done", p, "0");
623        if (*p == '1') {
624            break;
625        } else {
626            usleep(250000);
627        }
628    }
629    if (i == DATA_PREP_TIMEOUT) {
630        /* Ugh, we failed to prep /data in time.  Bail. */
631        return -1;
632    } else {
633        SLOGD("post_fs_data done\n");
634        return 0;
635    }
636}
637
638int cryptfs_restart(void)
639{
640    char fs_type[32];
641    char real_blkdev[MAXPATHLEN];
642    char crypto_blkdev[MAXPATHLEN];
643    char fs_options[256];
644    unsigned long mnt_flags;
645    struct stat statbuf;
646    int rc = -1, i;
647    static int restart_successful = 0;
648
649    /* Validate that it's OK to call this routine */
650    if (! master_key_saved) {
651        SLOGE("Encrypted filesystem not validated, aborting");
652        return -1;
653    }
654
655    if (restart_successful) {
656        SLOGE("System already restarted with encrypted disk, aborting");
657        return -1;
658    }
659
660    /* Here is where we shut down the framework.  The init scripts
661     * start all services in one of three classes: core, main or late_start.
662     * On boot, we start core and main.  Now, we stop main, but not core,
663     * as core includes vold and a few other really important things that
664     * we need to keep running.  Once main has stopped, we should be able
665     * to umount the tmpfs /data, then mount the encrypted /data.
666     * We then restart the class main, and also the class late_start.
667     * At the moment, I've only put a few things in late_start that I know
668     * are not needed to bring up the framework, and that also cause problems
669     * with unmounting the tmpfs /data, but I hope to add add more services
670     * to the late_start class as we optimize this to decrease the delay
671     * till the user is asked for the password to the filesystem.
672     */
673
674    /* The init files are setup to stop the class main when vold.decrypt is
675     * set to trigger_reset_main.
676     */
677    property_set("vold.decrypt", "trigger_reset_main");
678    SLOGD("Just asked init to shut down class main\n");
679
680    /* Now that the framework is shutdown, we should be able to umount()
681     * the tmpfs filesystem, and mount the real one.
682     */
683
684    property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
685    if (strlen(crypto_blkdev) == 0) {
686        SLOGE("fs_crypto_blkdev not set\n");
687        return -1;
688    }
689
690    if (! get_orig_mount_parms(DATA_MNT_POINT, fs_type, real_blkdev, &mnt_flags, fs_options)) {
691        SLOGD("Just got orig mount parms\n");
692
693        if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
694            /* If that succeeded, then mount the decrypted filesystem */
695            mount(crypto_blkdev, DATA_MNT_POINT, fs_type, mnt_flags, fs_options);
696
697            property_set("vold.decrypt", "trigger_load_persist_props");
698            /* Create necessary paths on /data */
699            if (prep_data_fs()) {
700                return -1;
701            }
702
703            /* startup service classes main and late_start */
704            property_set("vold.decrypt", "trigger_restart_framework");
705            SLOGD("Just triggered restart_framework\n");
706
707            /* Give it a few moments to get started */
708            sleep(1);
709        }
710    }
711
712    if (rc == 0) {
713        restart_successful = 1;
714    }
715
716    return rc;
717}
718
719static int do_crypto_complete(char *mount_point)
720{
721  struct crypt_mnt_ftr crypt_ftr;
722  unsigned char encrypted_master_key[32];
723  unsigned char salt[SALT_LEN];
724  char real_blkdev[MAXPATHLEN];
725  char fs_type[PROPERTY_VALUE_MAX];
726  char fs_options[PROPERTY_VALUE_MAX];
727  unsigned long mnt_flags;
728  char encrypted_state[PROPERTY_VALUE_MAX];
729
730  property_get("ro.crypto.state", encrypted_state, "");
731  if (strcmp(encrypted_state, "encrypted") ) {
732    SLOGE("not running with encryption, aborting");
733    return 1;
734  }
735
736  if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
737    SLOGE("Error reading original mount parms for mount point %s\n", mount_point);
738    return -1;
739  }
740
741  if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
742    SLOGE("Error getting crypt footer and key\n");
743    return -1;
744  }
745
746  if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
747    SLOGE("Encryption process didn't finish successfully\n");
748    return -2;  /* -2 is the clue to the UI that there is no usable data on the disk,
749                 * and give the user an option to wipe the disk */
750  }
751
752  /* We passed the test! We shall diminish, and return to the west */
753  return 0;
754}
755
756static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
757{
758  struct crypt_mnt_ftr crypt_ftr;
759  /* Allocate enough space for a 256 bit key, but we may use less */
760  unsigned char encrypted_master_key[32], decrypted_master_key[32];
761  unsigned char salt[SALT_LEN];
762  char crypto_blkdev[MAXPATHLEN];
763  char real_blkdev[MAXPATHLEN];
764  char fs_type[PROPERTY_VALUE_MAX];
765  char fs_options[PROPERTY_VALUE_MAX];
766  char tmp_mount_point[64];
767  unsigned long mnt_flags;
768  unsigned int orig_failed_decrypt_count;
769  char encrypted_state[PROPERTY_VALUE_MAX];
770  int rc;
771
772  property_get("ro.crypto.state", encrypted_state, "");
773  if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
774    SLOGE("encrypted fs already validated or not running with encryption, aborting");
775    return -1;
776  }
777
778  if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
779    SLOGE("Error reading original mount parms for mount point %s\n", mount_point);
780    return -1;
781  }
782
783  if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
784    SLOGE("Error getting crypt footer and key\n");
785    return -1;
786  }
787
788  SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
789  orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
790
791  if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
792    decrypt_master_key(passwd, salt, encrypted_master_key, decrypted_master_key);
793  }
794
795  if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
796                               real_blkdev, crypto_blkdev, label)) {
797    SLOGE("Error creating decrypted block device\n");
798    return -1;
799  }
800
801  /* If init detects an encrypted filesystme, it writes a file for each such
802   * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
803   * files and passes that data to me */
804  /* Create a tmp mount point to try mounting the decryptd fs
805   * Since we're here, the mount_point should be a tmpfs filesystem, so make
806   * a directory in it to test mount the decrypted filesystem.
807   */
808  sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
809  mkdir(tmp_mount_point, 0755);
810  if ( mount(crypto_blkdev, tmp_mount_point, "ext4", MS_RDONLY, "") ) {
811    SLOGE("Error temp mounting decrypted block device\n");
812    delete_crypto_blk_dev(label);
813    crypt_ftr.failed_decrypt_count++;
814  } else {
815    /* Success, so just umount and we'll mount it properly when we restart
816     * the framework.
817     */
818    umount(tmp_mount_point);
819    crypt_ftr.failed_decrypt_count  = 0;
820  }
821
822  if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
823    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0, 0);
824  }
825
826  if (crypt_ftr.failed_decrypt_count) {
827    /* We failed to mount the device, so return an error */
828    rc = crypt_ftr.failed_decrypt_count;
829
830  } else {
831    /* Woot!  Success!  Save the name of the crypto block device
832     * so we can mount it when restarting the framework.
833     */
834    property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
835
836    /* Also save a the master key so we can reencrypted the key
837     * the key when we want to change the password on it.
838     */
839    memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
840    saved_data_blkdev = strdup(real_blkdev);
841    master_key_saved = 1;
842    rc = 0;
843  }
844
845  return rc;
846}
847
848/* Called by vold when it wants to undo the crypto mapping of a volume it
849 * manages.  This is usually in response to a factory reset, when we want
850 * to undo the crypto mapping so the volume is formatted in the clear.
851 */
852int cryptfs_revert_volume(const char *label)
853{
854    return delete_crypto_blk_dev((char *)label);
855}
856
857/*
858 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
859 * Setup a dm-crypt mapping, use the saved master key from
860 * setting up the /data mapping, and return the new device path.
861 */
862int cryptfs_setup_volume(const char *label, int major, int minor,
863                         char *crypto_sys_path, unsigned int max_path,
864                         int *new_major, int *new_minor)
865{
866    char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
867    struct crypt_mnt_ftr sd_crypt_ftr;
868    unsigned char key[32], salt[32];
869    struct stat statbuf;
870    int nr_sec, fd;
871
872    sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
873
874    /* Just want the footer, but gotta get it all */
875    get_crypt_ftr_and_key(saved_data_blkdev, &sd_crypt_ftr, key, salt);
876
877    /* Update the fs_size field to be the size of the volume */
878    fd = open(real_blkdev, O_RDONLY);
879    nr_sec = get_blkdev_size(fd);
880    close(fd);
881    if (nr_sec == 0) {
882        SLOGE("Cannot get size of volume %s\n", real_blkdev);
883        return -1;
884    }
885
886    sd_crypt_ftr.fs_size = nr_sec;
887    create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
888                          crypto_blkdev, label);
889
890    stat(crypto_blkdev, &statbuf);
891    *new_major = MAJOR(statbuf.st_rdev);
892    *new_minor = MINOR(statbuf.st_rdev);
893
894    /* Create path to sys entry for this block device */
895    snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
896
897    return 0;
898}
899
900int cryptfs_crypto_complete(void)
901{
902  return do_crypto_complete("/data");
903}
904
905int cryptfs_check_passwd(char *passwd)
906{
907    int rc = -1;
908
909    rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
910
911    return rc;
912}
913
914/* Initialize a crypt_mnt_ftr structure.  The keysize is
915 * defaulted to 16 bytes, and the filesystem size to 0.
916 * Presumably, at a minimum, the caller will update the
917 * filesystem size and crypto_type_name after calling this function.
918 */
919static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
920{
921    ftr->magic = CRYPT_MNT_MAGIC;
922    ftr->major_version = 1;
923    ftr->minor_version = 0;
924    ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
925    ftr->flags = 0;
926    ftr->keysize = KEY_LEN_BYTES;
927    ftr->spare1 = 0;
928    ftr->fs_size = 0;
929    ftr->failed_decrypt_count = 0;
930    ftr->crypto_type_name[0] = '\0';
931}
932
933static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
934{
935    char cmdline[256];
936    int rc = -1;
937
938    if (type == EXT4_FS) {
939        snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
940                 size * 512, crypto_blkdev);
941        SLOGI("Making empty filesystem with command %s\n", cmdline);
942    } else if (type== FAT_FS) {
943        snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
944                 size, crypto_blkdev);
945        SLOGI("Making empty filesystem with command %s\n", cmdline);
946    } else {
947        SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
948        return -1;
949    }
950
951    if (system(cmdline)) {
952      SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
953    } else {
954      SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
955      rc = 0;
956    }
957
958    return rc;
959}
960
961static inline int unix_read(int  fd, void*  buff, int  len)
962{
963    int  ret;
964    do { ret = read(fd, buff, len); } while (ret < 0 && errno == EINTR);
965    return ret;
966}
967
968static inline int unix_write(int  fd, const void*  buff, int  len)
969{
970    int  ret;
971    do { ret = write(fd, buff, len); } while (ret < 0 && errno == EINTR);
972    return ret;
973}
974
975#define CRYPT_INPLACE_BUFSIZE 4096
976#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
977static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
978                                  off64_t *size_already_done, off64_t tot_size)
979{
980    int realfd, cryptofd;
981    char *buf[CRYPT_INPLACE_BUFSIZE];
982    int rc = -1;
983    off64_t numblocks, i, remainder;
984    off64_t one_pct, cur_pct, new_pct;
985    off64_t blocks_already_done, tot_numblocks;
986
987    if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
988        SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
989        return -1;
990    }
991
992    if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
993        SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
994        close(realfd);
995        return -1;
996    }
997
998    /* This is pretty much a simple loop of reading 4K, and writing 4K.
999     * The size passed in is the number of 512 byte sectors in the filesystem.
1000     * So compute the number of whole 4K blocks we should read/write,
1001     * and the remainder.
1002     */
1003    numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1004    remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
1005    tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1006    blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1007
1008    SLOGE("Encrypting filesystem in place...");
1009
1010    one_pct = tot_numblocks / 100;
1011    cur_pct = 0;
1012    /* process the majority of the filesystem in blocks */
1013    for (i=0; i<numblocks; i++) {
1014        new_pct = (i + blocks_already_done) / one_pct;
1015        if (new_pct > cur_pct) {
1016            char buf[8];
1017
1018            cur_pct = new_pct;
1019            snprintf(buf, sizeof(buf), "%lld", cur_pct);
1020            property_set("vold.encrypt_progress", buf);
1021        }
1022        if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1023            SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1024            goto errout;
1025        }
1026        if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1027            SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1028            goto errout;
1029        }
1030    }
1031
1032    /* Do any remaining sectors */
1033    for (i=0; i<remainder; i++) {
1034        if (unix_read(realfd, buf, 512) <= 0) {
1035            SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1036            goto errout;
1037        }
1038        if (unix_write(cryptofd, buf, 512) <= 0) {
1039            SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1040            goto errout;
1041        }
1042    }
1043
1044    *size_already_done += size;
1045    rc = 0;
1046
1047errout:
1048    close(realfd);
1049    close(cryptofd);
1050
1051    return rc;
1052}
1053
1054#define CRYPTO_ENABLE_WIPE 1
1055#define CRYPTO_ENABLE_INPLACE 2
1056
1057#define FRAMEWORK_BOOT_WAIT 60
1058
1059static inline int should_encrypt(struct volume_info *volume)
1060{
1061    return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1062            (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1063}
1064
1065int cryptfs_enable(char *howarg, char *passwd)
1066{
1067    int how = 0;
1068    char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
1069    char fs_type[PROPERTY_VALUE_MAX], fs_options[PROPERTY_VALUE_MAX],
1070         mount_point[PROPERTY_VALUE_MAX];
1071    unsigned long mnt_flags, nr_sec;
1072    unsigned char master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
1073    unsigned char salt[SALT_LEN];
1074    int rc=-1, fd, i, ret;
1075    struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
1076    char tmpfs_options[PROPERTY_VALUE_MAX];
1077    char encrypted_state[PROPERTY_VALUE_MAX];
1078    char lockid[32] = { 0 };
1079    char key_loc[PROPERTY_VALUE_MAX];
1080    char fuse_sdcard[PROPERTY_VALUE_MAX];
1081    char *sd_mnt_point;
1082    char sd_blk_dev[256] = { 0 };
1083    int num_vols;
1084    struct volume_info *vol_list = 0;
1085    off64_t cur_encryption_done=0, tot_encryption_size=0;
1086
1087    property_get("ro.crypto.state", encrypted_state, "");
1088    if (strcmp(encrypted_state, "unencrypted")) {
1089        SLOGE("Device is already running encrypted, aborting");
1090        goto error_unencrypted;
1091    }
1092
1093    property_get(KEY_LOC_PROP, key_loc, KEY_IN_FOOTER);
1094
1095    if (!strcmp(howarg, "wipe")) {
1096      how = CRYPTO_ENABLE_WIPE;
1097    } else if (! strcmp(howarg, "inplace")) {
1098      how = CRYPTO_ENABLE_INPLACE;
1099    } else {
1100      /* Shouldn't happen, as CommandListener vets the args */
1101      goto error_unencrypted;
1102    }
1103
1104    get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options);
1105
1106    /* Get the size of the real block device */
1107    fd = open(real_blkdev, O_RDONLY);
1108    if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1109        SLOGE("Cannot get size of block device %s\n", real_blkdev);
1110        goto error_unencrypted;
1111    }
1112    close(fd);
1113
1114    /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
1115    if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
1116        unsigned int fs_size_sec, max_fs_size_sec;
1117
1118        fs_size_sec = get_fs_size(real_blkdev);
1119        max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1120
1121        if (fs_size_sec > max_fs_size_sec) {
1122            SLOGE("Orig filesystem overlaps crypto footer region.  Cannot encrypt in place.");
1123            goto error_unencrypted;
1124        }
1125    }
1126
1127    /* Get a wakelock as this may take a while, and we don't want the
1128     * device to sleep on us.  We'll grab a partial wakelock, and if the UI
1129     * wants to keep the screen on, it can grab a full wakelock.
1130     */
1131    snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
1132    acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1133
1134     /* Get the sdcard mount point */
1135     sd_mnt_point = getenv("EXTERNAL_STORAGE");
1136     if (! sd_mnt_point) {
1137         sd_mnt_point = "/mnt/sdcard";
1138     }
1139
1140    num_vols=vold_getNumDirectVolumes();
1141    vol_list = malloc(sizeof(struct volume_info) * num_vols);
1142    vold_getDirectVolumeList(vol_list);
1143
1144    for (i=0; i<num_vols; i++) {
1145        if (should_encrypt(&vol_list[i])) {
1146            fd = open(vol_list[i].blk_dev, O_RDONLY);
1147            if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1148                SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1149                goto error_unencrypted;
1150            }
1151            close(fd);
1152
1153            ret=vold_disableVol(vol_list[i].label);
1154            if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1155                /* -2 is returned when the device exists but is not currently mounted.
1156                 * ignore the error and continue. */
1157                SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1158                goto error_unencrypted;
1159            }
1160        }
1161    }
1162
1163    /* The init files are setup to stop the class main and late start when
1164     * vold sets trigger_shutdown_framework.
1165     */
1166    property_set("vold.decrypt", "trigger_shutdown_framework");
1167    SLOGD("Just asked init to shut down class main\n");
1168
1169    property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1170    if (!strcmp(fuse_sdcard, "true")) {
1171        /* This is a device using the fuse layer to emulate the sdcard semantics
1172         * on top of the userdata partition.  vold does not manage it, it is managed
1173         * by the sdcard service.  The sdcard service was killed by the property trigger
1174         * above, so just unmount it now.  We must do this _AFTER_ killing the framework,
1175         * unlike the case for vold managed devices above.
1176         */
1177        if (wait_and_unmount(sd_mnt_point)) {
1178            goto error_shutting_down;
1179        }
1180    }
1181
1182    /* Now unmount the /data partition. */
1183    if (wait_and_unmount(DATA_MNT_POINT)) {
1184        goto error_shutting_down;
1185    }
1186
1187    /* Do extra work for a better UX when doing the long inplace encryption */
1188    if (how == CRYPTO_ENABLE_INPLACE) {
1189        /* Now that /data is unmounted, we need to mount a tmpfs
1190         * /data, set a property saying we're doing inplace encryption,
1191         * and restart the framework.
1192         */
1193        property_get("ro.crypto.tmpfs_options", tmpfs_options, "");
1194        if (mount("tmpfs", DATA_MNT_POINT, "tmpfs", MS_NOATIME | MS_NOSUID | MS_NODEV,
1195            tmpfs_options) < 0) {
1196            goto error_shutting_down;
1197        }
1198        /* Tells the framework that inplace encryption is starting */
1199        property_set("vold.encrypt_progress", "0");
1200
1201        /* restart the framework. */
1202        /* Create necessary paths on /data */
1203        if (prep_data_fs()) {
1204            goto error_shutting_down;
1205        }
1206
1207        /* startup service classes main and late_start */
1208        property_set("vold.decrypt", "trigger_restart_min_framework");
1209        SLOGD("Just triggered restart_min_framework\n");
1210
1211        /* OK, the framework is restarted and will soon be showing a
1212         * progress bar.  Time to setup an encrypted mapping, and
1213         * either write a new filesystem, or encrypt in place updating
1214         * the progress bar as we work.
1215         */
1216    }
1217
1218    /* Start the actual work of making an encrypted filesystem */
1219    /* Initialize a crypt_mnt_ftr for the partition */
1220    cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
1221    if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1222        crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1223    } else {
1224        crypt_ftr.fs_size = nr_sec;
1225    }
1226    crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
1227    strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1228
1229    /* Make an encrypted master key */
1230    if (create_encrypted_random_key(passwd, master_key, salt)) {
1231        SLOGE("Cannot create encrypted master key\n");
1232        goto error_unencrypted;
1233    }
1234
1235    /* Write the key to the end of the partition */
1236    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, master_key, salt);
1237
1238    decrypt_master_key(passwd, salt, master_key, decrypted_master_key);
1239    create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1240                          "userdata");
1241
1242    /* The size of the userdata partition, and add in the vold volumes below */
1243    tot_encryption_size = crypt_ftr.fs_size;
1244
1245    /* setup crypto mapping for all encryptable volumes handled by vold */
1246    for (i=0; i<num_vols; i++) {
1247        if (should_encrypt(&vol_list[i])) {
1248            vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1249            vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1250            create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1251                                  vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1252                                  vol_list[i].label);
1253            tot_encryption_size += vol_list[i].size;
1254        }
1255    }
1256
1257    if (how == CRYPTO_ENABLE_WIPE) {
1258        rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1259        /* Encrypt all encryptable volumes handled by vold */
1260        if (!rc) {
1261            for (i=0; i<num_vols; i++) {
1262                if (should_encrypt(&vol_list[i])) {
1263                    rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1264                                             vol_list[i].crypt_ftr.fs_size, FAT_FS);
1265                }
1266            }
1267        }
1268    } else if (how == CRYPTO_ENABLE_INPLACE) {
1269        rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1270                                    &cur_encryption_done, tot_encryption_size);
1271        /* Encrypt all encryptable volumes handled by vold */
1272        if (!rc) {
1273            for (i=0; i<num_vols; i++) {
1274                if (should_encrypt(&vol_list[i])) {
1275                    rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1276                                                vol_list[i].blk_dev,
1277                                                vol_list[i].crypt_ftr.fs_size,
1278                                                &cur_encryption_done, tot_encryption_size);
1279                }
1280            }
1281        }
1282        if (!rc) {
1283            /* The inplace routine never actually sets the progress to 100%
1284             * due to the round down nature of integer division, so set it here */
1285            property_set("vold.encrypt_progress", "100");
1286        }
1287    } else {
1288        /* Shouldn't happen */
1289        SLOGE("cryptfs_enable: internal error, unknown option\n");
1290        goto error_unencrypted;
1291    }
1292
1293    /* Undo the dm-crypt mapping whether we succeed or not */
1294    delete_crypto_blk_dev("userdata");
1295    for (i=0; i<num_vols; i++) {
1296        if (should_encrypt(&vol_list[i])) {
1297            delete_crypto_blk_dev(vol_list[i].label);
1298        }
1299    }
1300
1301    free(vol_list);
1302
1303    if (! rc) {
1304        /* Success */
1305
1306        /* Clear the encryption in progres flag in the footer */
1307        crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
1308        put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0, 0);
1309
1310        sleep(2); /* Give the UI a chance to show 100% progress */
1311        android_reboot(ANDROID_RB_RESTART, 0, 0);
1312    } else {
1313        property_set("vold.encrypt_progress", "error_partially_encrypted");
1314        release_wake_lock(lockid);
1315        return -1;
1316    }
1317
1318    /* hrm, the encrypt step claims success, but the reboot failed.
1319     * This should not happen.
1320     * Set the property and return.  Hope the framework can deal with it.
1321     */
1322    property_set("vold.encrypt_progress", "error_reboot_failed");
1323    release_wake_lock(lockid);
1324    return rc;
1325
1326error_unencrypted:
1327    free(vol_list);
1328    property_set("vold.encrypt_progress", "error_not_encrypted");
1329    if (lockid[0]) {
1330        release_wake_lock(lockid);
1331    }
1332    return -1;
1333
1334error_shutting_down:
1335    /* we failed, and have not encrypted anthing, so the users's data is still intact,
1336     * but the framework is stopped and not restarted to show the error, so it's up to
1337     * vold to restart the system.
1338     */
1339    SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
1340    android_reboot(ANDROID_RB_RESTART, 0, 0);
1341
1342    /* shouldn't get here */
1343    property_set("vold.encrypt_progress", "error_shutting_down");
1344    free(vol_list);
1345    if (lockid[0]) {
1346        release_wake_lock(lockid);
1347    }
1348    return -1;
1349}
1350
1351int cryptfs_changepw(char *newpw)
1352{
1353    struct crypt_mnt_ftr crypt_ftr;
1354    unsigned char encrypted_master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
1355    unsigned char salt[SALT_LEN];
1356    char real_blkdev[MAXPATHLEN];
1357
1358    /* This is only allowed after we've successfully decrypted the master key */
1359    if (! master_key_saved) {
1360        SLOGE("Key not saved, aborting");
1361        return -1;
1362    }
1363
1364    property_get("ro.crypto.fs_real_blkdev", real_blkdev, "");
1365    if (strlen(real_blkdev) == 0) {
1366        SLOGE("Can't find real blkdev");
1367        return -1;
1368    }
1369
1370    /* get key */
1371    if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
1372      SLOGE("Error getting crypt footer and key");
1373      return -1;
1374    }
1375
1376    encrypt_master_key(newpw, salt, saved_master_key, encrypted_master_key);
1377
1378    /* save the key */
1379    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt);
1380
1381    return 0;
1382}
1383