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