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 <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     */
320    if (lseek(fd, crypt_ftr->ftr_size - sizeof(struct crypt_mnt_ftr),  SEEK_CUR) == -1) {
321      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    int how = 0;
1118    char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
1119    unsigned long nr_sec;
1120    unsigned char master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
1121    unsigned char salt[SALT_LEN];
1122    int rc=-1, fd, i, ret;
1123    struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
1124    char tmpfs_options[PROPERTY_VALUE_MAX];
1125    char encrypted_state[PROPERTY_VALUE_MAX];
1126    char lockid[32] = { 0 };
1127    char key_loc[PROPERTY_VALUE_MAX];
1128    char fuse_sdcard[PROPERTY_VALUE_MAX];
1129    char *sd_mnt_point;
1130    char sd_blk_dev[256] = { 0 };
1131    int num_vols;
1132    struct volume_info *vol_list = 0;
1133    off64_t cur_encryption_done=0, tot_encryption_size=0;
1134
1135    property_get("ro.crypto.state", encrypted_state, "");
1136    if (strcmp(encrypted_state, "unencrypted")) {
1137        SLOGE("Device is already running encrypted, aborting");
1138        goto error_unencrypted;
1139    }
1140
1141    fs_mgr_get_crypt_info(get_fstab_filename(), key_loc, 0, sizeof(key_loc));
1142
1143    if (!strcmp(howarg, "wipe")) {
1144      how = CRYPTO_ENABLE_WIPE;
1145    } else if (! strcmp(howarg, "inplace")) {
1146      how = CRYPTO_ENABLE_INPLACE;
1147    } else {
1148      /* Shouldn't happen, as CommandListener vets the args */
1149      goto error_unencrypted;
1150    }
1151
1152    fs_mgr_get_crypt_info(get_fstab_filename(), 0, real_blkdev, sizeof(real_blkdev));
1153
1154    /* Get the size of the real block device */
1155    fd = open(real_blkdev, O_RDONLY);
1156    if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1157        SLOGE("Cannot get size of block device %s\n", real_blkdev);
1158        goto error_unencrypted;
1159    }
1160    close(fd);
1161
1162    /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
1163    if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
1164        unsigned int fs_size_sec, max_fs_size_sec;
1165
1166        fs_size_sec = get_fs_size(real_blkdev);
1167        max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1168
1169        if (fs_size_sec > max_fs_size_sec) {
1170            SLOGE("Orig filesystem overlaps crypto footer region.  Cannot encrypt in place.");
1171            goto error_unencrypted;
1172        }
1173    }
1174
1175    /* Get a wakelock as this may take a while, and we don't want the
1176     * device to sleep on us.  We'll grab a partial wakelock, and if the UI
1177     * wants to keep the screen on, it can grab a full wakelock.
1178     */
1179    snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
1180    acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1181
1182     /* Get the sdcard mount point */
1183     sd_mnt_point = getenv("EXTERNAL_STORAGE");
1184     if (! sd_mnt_point) {
1185         sd_mnt_point = "/mnt/sdcard";
1186     }
1187
1188    num_vols=vold_getNumDirectVolumes();
1189    vol_list = malloc(sizeof(struct volume_info) * num_vols);
1190    vold_getDirectVolumeList(vol_list);
1191
1192    for (i=0; i<num_vols; i++) {
1193        if (should_encrypt(&vol_list[i])) {
1194            fd = open(vol_list[i].blk_dev, O_RDONLY);
1195            if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1196                SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1197                goto error_unencrypted;
1198            }
1199            close(fd);
1200
1201            ret=vold_disableVol(vol_list[i].label);
1202            if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1203                /* -2 is returned when the device exists but is not currently mounted.
1204                 * ignore the error and continue. */
1205                SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1206                goto error_unencrypted;
1207            }
1208        }
1209    }
1210
1211    /* The init files are setup to stop the class main and late start when
1212     * vold sets trigger_shutdown_framework.
1213     */
1214    property_set("vold.decrypt", "trigger_shutdown_framework");
1215    SLOGD("Just asked init to shut down class main\n");
1216
1217    if (vold_unmountAllAsecs()) {
1218        /* Just report the error.  If any are left mounted,
1219         * umounting /data below will fail and handle the error.
1220         */
1221        SLOGE("Error unmounting internal asecs");
1222    }
1223
1224    property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1225    if (!strcmp(fuse_sdcard, "true")) {
1226        /* This is a device using the fuse layer to emulate the sdcard semantics
1227         * on top of the userdata partition.  vold does not manage it, it is managed
1228         * by the sdcard service.  The sdcard service was killed by the property trigger
1229         * above, so just unmount it now.  We must do this _AFTER_ killing the framework,
1230         * unlike the case for vold managed devices above.
1231         */
1232        if (wait_and_unmount(sd_mnt_point)) {
1233            goto error_shutting_down;
1234        }
1235    }
1236
1237    /* Now unmount the /data partition. */
1238    if (wait_and_unmount(DATA_MNT_POINT)) {
1239        goto error_shutting_down;
1240    }
1241
1242    /* Do extra work for a better UX when doing the long inplace encryption */
1243    if (how == CRYPTO_ENABLE_INPLACE) {
1244        /* Now that /data is unmounted, we need to mount a tmpfs
1245         * /data, set a property saying we're doing inplace encryption,
1246         * and restart the framework.
1247         */
1248        if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1249            goto error_shutting_down;
1250        }
1251        /* Tells the framework that inplace encryption is starting */
1252        property_set("vold.encrypt_progress", "0");
1253
1254        /* restart the framework. */
1255        /* Create necessary paths on /data */
1256        if (prep_data_fs()) {
1257            goto error_shutting_down;
1258        }
1259
1260        /* startup service classes main and late_start */
1261        property_set("vold.decrypt", "trigger_restart_min_framework");
1262        SLOGD("Just triggered restart_min_framework\n");
1263
1264        /* OK, the framework is restarted and will soon be showing a
1265         * progress bar.  Time to setup an encrypted mapping, and
1266         * either write a new filesystem, or encrypt in place updating
1267         * the progress bar as we work.
1268         */
1269    }
1270
1271    /* Start the actual work of making an encrypted filesystem */
1272    /* Initialize a crypt_mnt_ftr for the partition */
1273    cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
1274    if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1275        crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1276    } else {
1277        crypt_ftr.fs_size = nr_sec;
1278    }
1279    crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
1280    strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1281
1282    /* Make an encrypted master key */
1283    if (create_encrypted_random_key(passwd, master_key, salt)) {
1284        SLOGE("Cannot create encrypted master key\n");
1285        goto error_unencrypted;
1286    }
1287
1288    /* Write the key to the end of the partition */
1289    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, master_key, salt);
1290
1291    decrypt_master_key(passwd, salt, master_key, decrypted_master_key);
1292    create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1293                          "userdata");
1294
1295    /* The size of the userdata partition, and add in the vold volumes below */
1296    tot_encryption_size = crypt_ftr.fs_size;
1297
1298    /* setup crypto mapping for all encryptable volumes handled by vold */
1299    for (i=0; i<num_vols; i++) {
1300        if (should_encrypt(&vol_list[i])) {
1301            vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1302            vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1303            create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1304                                  vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1305                                  vol_list[i].label);
1306            tot_encryption_size += vol_list[i].size;
1307        }
1308    }
1309
1310    if (how == CRYPTO_ENABLE_WIPE) {
1311        rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1312        /* Encrypt all encryptable volumes handled by vold */
1313        if (!rc) {
1314            for (i=0; i<num_vols; i++) {
1315                if (should_encrypt(&vol_list[i])) {
1316                    rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1317                                             vol_list[i].crypt_ftr.fs_size, FAT_FS);
1318                }
1319            }
1320        }
1321    } else if (how == CRYPTO_ENABLE_INPLACE) {
1322        rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1323                                    &cur_encryption_done, tot_encryption_size);
1324        /* Encrypt all encryptable volumes handled by vold */
1325        if (!rc) {
1326            for (i=0; i<num_vols; i++) {
1327                if (should_encrypt(&vol_list[i])) {
1328                    rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1329                                                vol_list[i].blk_dev,
1330                                                vol_list[i].crypt_ftr.fs_size,
1331                                                &cur_encryption_done, tot_encryption_size);
1332                }
1333            }
1334        }
1335        if (!rc) {
1336            /* The inplace routine never actually sets the progress to 100%
1337             * due to the round down nature of integer division, so set it here */
1338            property_set("vold.encrypt_progress", "100");
1339        }
1340    } else {
1341        /* Shouldn't happen */
1342        SLOGE("cryptfs_enable: internal error, unknown option\n");
1343        goto error_unencrypted;
1344    }
1345
1346    /* Undo the dm-crypt mapping whether we succeed or not */
1347    delete_crypto_blk_dev("userdata");
1348    for (i=0; i<num_vols; i++) {
1349        if (should_encrypt(&vol_list[i])) {
1350            delete_crypto_blk_dev(vol_list[i].label);
1351        }
1352    }
1353
1354    free(vol_list);
1355
1356    if (! rc) {
1357        /* Success */
1358
1359        /* Clear the encryption in progres flag in the footer */
1360        crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
1361        put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0, 0);
1362
1363        sleep(2); /* Give the UI a chance to show 100% progress */
1364        android_reboot(ANDROID_RB_RESTART, 0, 0);
1365    } else {
1366        char value[PROPERTY_VALUE_MAX];
1367
1368        property_get("ro.vold.wipe_on_cyrypt_fail", value, "0");
1369        if (!strcmp(value, "1")) {
1370            /* wipe data if encryption failed */
1371            SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1372            mkdir("/cache/recovery", 0700);
1373            int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC);
1374            if (fd >= 0) {
1375                write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1376                close(fd);
1377            } else {
1378                SLOGE("could not open /cache/recovery/command\n");
1379            }
1380            android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
1381        } else {
1382            /* set property to trigger dialog */
1383            property_set("vold.encrypt_progress", "error_partially_encrypted");
1384            release_wake_lock(lockid);
1385        }
1386        return -1;
1387    }
1388
1389    /* hrm, the encrypt step claims success, but the reboot failed.
1390     * This should not happen.
1391     * Set the property and return.  Hope the framework can deal with it.
1392     */
1393    property_set("vold.encrypt_progress", "error_reboot_failed");
1394    release_wake_lock(lockid);
1395    return rc;
1396
1397error_unencrypted:
1398    free(vol_list);
1399    property_set("vold.encrypt_progress", "error_not_encrypted");
1400    if (lockid[0]) {
1401        release_wake_lock(lockid);
1402    }
1403    return -1;
1404
1405error_shutting_down:
1406    /* we failed, and have not encrypted anthing, so the users's data is still intact,
1407     * but the framework is stopped and not restarted to show the error, so it's up to
1408     * vold to restart the system.
1409     */
1410    SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
1411    android_reboot(ANDROID_RB_RESTART, 0, 0);
1412
1413    /* shouldn't get here */
1414    property_set("vold.encrypt_progress", "error_shutting_down");
1415    free(vol_list);
1416    if (lockid[0]) {
1417        release_wake_lock(lockid);
1418    }
1419    return -1;
1420}
1421
1422int cryptfs_changepw(char *newpw)
1423{
1424    struct crypt_mnt_ftr crypt_ftr;
1425    unsigned char encrypted_master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
1426    unsigned char salt[SALT_LEN];
1427    char real_blkdev[MAXPATHLEN];
1428
1429    /* This is only allowed after we've successfully decrypted the master key */
1430    if (! master_key_saved) {
1431        SLOGE("Key not saved, aborting");
1432        return -1;
1433    }
1434
1435    fs_mgr_get_crypt_info(get_fstab_filename(), 0, real_blkdev, sizeof(real_blkdev));
1436    if (strlen(real_blkdev) == 0) {
1437        SLOGE("Can't find real blkdev");
1438        return -1;
1439    }
1440
1441    /* get key */
1442    if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
1443      SLOGE("Error getting crypt footer and key");
1444      return -1;
1445    }
1446
1447    encrypt_master_key(newpw, salt, saved_master_key, encrypted_master_key);
1448
1449    /* save the key */
1450    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt);
1451
1452    return 0;
1453}
1454