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