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