cryptfs.c revision 8f869aa1bc685b505c58e97b4e11a9c7491a16f9
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 <errno.h>
37#include <sys/reboot.h>
38#include "cryptfs.h"
39#define LOG_TAG "Cryptfs"
40#include "cutils/log.h"
41#include "cutils/properties.h"
42
43#define DM_CRYPT_BUF_SIZE 4096
44
45char *me = "cryptfs";
46
47static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
48{
49    memset(io, 0, dataSize);
50    io->data_size = dataSize;
51    io->data_start = sizeof(struct dm_ioctl);
52    io->version[0] = 4;
53    io->version[1] = 0;
54    io->version[2] = 0;
55    io->flags = flags;
56    if (name) {
57        strncpy(io->name, name, sizeof(io->name));
58    }
59}
60
61static unsigned int get_blkdev_size(int fd)
62{
63  unsigned int nr_sec;
64
65  if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
66    nr_sec = 0;
67  }
68
69  return nr_sec;
70}
71
72/* key can be NULL, in which case just write out the footer.  Useful to
73 * update the failed mount count but not change the key.
74 */
75static int put_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
76                                  unsigned char *key)
77{
78  int fd;
79  unsigned int nr_sec, cnt;
80  off64_t off;
81  int rc = -1;
82
83  if ( (fd = open(real_blk_name, O_RDWR)) < 0) {
84    SLOGE("Cannot open real block device %s\n", real_blk_name);
85    return -1;
86  }
87
88  if ( (nr_sec = get_blkdev_size(fd)) == 0) {
89    SLOGE("Cannot get size of block device %s\n", real_blk_name);
90    goto errout;
91  }
92
93  /* If it's an encrypted Android partition, the last 16 Kbytes contain the
94   * encryption info footer and key, and plenty of bytes to spare for future
95   * growth.
96   */
97  off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
98
99  if (lseek64(fd, off, SEEK_SET) == -1) {
100    SLOGE("Cannot seek to real block device footer\n");
101    goto errout;
102  }
103
104  if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
105    SLOGE("Cannot write real block device footer\n");
106    goto errout;
107  }
108
109  if (key) {
110    if (crypt_ftr->keysize != 16) {
111      SLOGE("Keysize of %d bits not supported for real block device %s\n",
112            crypt_ftr->keysize * 8, real_blk_name);
113      goto errout;
114    }
115
116    if ( (cnt = write(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
117      SLOGE("Cannot write key for real block device %s\n", real_blk_name);
118      goto errout;
119    }
120  }
121
122  /* Success! */
123  rc = 0;
124
125errout:
126  close(fd);
127  return rc;
128
129}
130
131static int get_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
132                                  unsigned char *key)
133{
134  int fd;
135  unsigned int nr_sec, cnt;
136  off64_t off;
137  int rc = -1;
138
139  if ( (fd = open(real_blk_name, O_RDWR)) < 0) {
140    SLOGE("Cannot open real block device %s\n", real_blk_name);
141    return -1;
142  }
143
144  if ( (nr_sec = get_blkdev_size(fd)) == 0) {
145    SLOGE("Cannot get size of block device %s\n", real_blk_name);
146    goto errout;
147  }
148
149  /* If it's an encrypted Android partition, the last 16 Kbytes contain the
150   * encryption info footer and key, and plenty of bytes to spare for future
151   * growth.
152   */
153#if 1 /* The real location, use when the enable code works */
154  off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
155#else
156  /* For testing, I'm slapping a handbuild header after my 200 megabyte
157   * /data partition.  So my offset if 200 megabytes */
158  off = 200*1024*1024;
159#endif
160
161  if (lseek64(fd, off, SEEK_SET) == -1) {
162    SLOGE("Cannot seek to real block device footer\n");
163    goto errout;
164  }
165
166  if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
167    SLOGE("Cannot read real block device footer\n");
168    goto errout;
169  }
170
171  if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
172    SLOGE("Bad magic for real block device %s\n", real_blk_name);
173    goto errout;
174  }
175
176  if (crypt_ftr->major_version != 1) {
177    SLOGE("Cannot understand major version %d real block device footer\n",
178          crypt_ftr->major_version);
179    goto errout;
180  }
181
182  if (crypt_ftr->minor_version != 0) {
183    SLOGW("Warning: crypto footer minor version %d, expected 0, continuing...\n",
184          crypt_ftr->minor_version);
185  }
186
187  if (crypt_ftr->ftr_size > sizeof(struct crypt_mnt_ftr)) {
188    /* the footer size is bigger than we expected.
189     * Skip to it's stated end so we can read the key.
190     */
191    if (lseek(fd, crypt_ftr->ftr_size - sizeof(struct crypt_mnt_ftr),  SEEK_CUR) == -1) {
192      SLOGE("Cannot seek to start of key\n");
193      goto errout;
194    }
195  }
196
197  if (crypt_ftr->keysize != 16) {
198    SLOGE("Keysize of %d bits not supported for real block device %s\n",
199          crypt_ftr->keysize * 8, real_blk_name);
200    goto errout;
201  }
202
203  if ( (cnt = read(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
204    SLOGE("Cannot read key for real block device %s\n", real_blk_name);
205    goto errout;
206  }
207
208  /* Success! */
209  rc = 0;
210
211errout:
212  close(fd);
213  return rc;
214}
215
216/* Convert a binary key of specified length into an ascii hex string equivalent,
217 * without the leading 0x and with null termination
218 */
219void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
220                              char *master_key_ascii)
221{
222  unsigned int i, a;
223  unsigned char nibble;
224
225  for (i=0, a=0; i<keysize; i++, a+=2) {
226    /* For each byte, write out two ascii hex digits */
227    nibble = (master_key[i] >> 4) & 0xf;
228    master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
229
230    nibble = master_key[i] & 0xf;
231    master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
232  }
233
234  /* Add the null termination */
235  master_key_ascii[a] = '\0';
236
237}
238
239static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
240                                    char *real_blk_name, char *crypto_blk_name)
241{
242  char buffer[DM_CRYPT_BUF_SIZE];
243  char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
244  char *crypt_params;
245  struct dm_ioctl *io;
246  struct dm_target_spec *tgt;
247  unsigned int minor;
248  int fd;
249  int retval = -1;
250  char *name ="datadev"; /* FIX ME: Make me a parameter */
251
252  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
253    SLOGE("Cannot open device-mapper\n");
254    goto errout;
255  }
256
257  io = (struct dm_ioctl *) buffer;
258
259  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
260  if (ioctl(fd, DM_DEV_CREATE, io)) {
261    SLOGE("Cannot create dm-crypt device\n");
262    goto errout;
263  }
264
265  /* Get the device status, in particular, the name of it's device file */
266  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
267  if (ioctl(fd, DM_DEV_STATUS, io)) {
268    SLOGE("Cannot retrieve dm-crypt device status\n");
269    goto errout;
270  }
271  minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
272  snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
273
274  /* Load the mapping table for this device */
275  tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
276
277  ioctl_init(io, 4096, name, 0);
278  io->target_count = 1;
279  tgt->status = 0;
280  tgt->sector_start = 0;
281  tgt->length = crypt_ftr->fs_size;
282  strcpy(tgt->target_type, "crypt");
283
284  crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
285  convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
286  sprintf(crypt_params, "%s %s 0 %s 0", crypt_ftr->crypto_type_name,
287          master_key_ascii, real_blk_name);
288  SLOGD("crypt_params = %s\n", crypt_params);
289  crypt_params += strlen(crypt_params) + 1;
290  crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
291  tgt->next = crypt_params - buffer;
292
293  if (ioctl(fd, DM_TABLE_LOAD, io)) {
294      SLOGE("Cannot load dm-crypt mapping table.\n");
295      goto errout;
296  }
297
298  /* Resume this device to activate it */
299  ioctl_init(io, 4096, name, 0);
300
301  if (ioctl(fd, DM_DEV_SUSPEND, io)) {
302    SLOGE("Cannot resume the dm-crypt device\n");
303    goto errout;
304  }
305
306  /* We made it here with no errors.  Woot! */
307  retval = 0;
308
309errout:
310  close(fd);   /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
311
312  return retval;
313}
314
315static int delete_crypto_blk_dev(char *crypto_blkdev)
316{
317  int fd;
318  char buffer[DM_CRYPT_BUF_SIZE];
319  struct dm_ioctl *io;
320  char *name ="datadev"; /* FIX ME: Make me a paraameter */
321  int retval = -1;
322
323  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
324    SLOGE("Cannot open device-mapper\n");
325    goto errout;
326  }
327
328  io = (struct dm_ioctl *) buffer;
329
330  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
331  if (ioctl(fd, DM_DEV_REMOVE, io)) {
332    SLOGE("Cannot remove dm-crypt device\n");
333    goto errout;
334  }
335
336  /* We made it here with no errors.  Woot! */
337  retval = 0;
338
339errout:
340  close(fd);    /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
341
342  return retval;
343
344}
345
346/* If we need to debug this, look at Devmapper.cpp:dumpState(),
347 * It does DM_LIST_DEVICES, then iterates on each device and
348 * calls DM_DEV_STATUS.
349 */
350
351#define HASH_COUNT 2000
352#define KEY_LEN_BYTES 16
353#define IV_LEN_BYTES 16
354
355static int create_encrypted_random_key(char *passwd, unsigned char *master_key)
356{
357    int fd;
358    unsigned char buf[KEY_LEN_BYTES];
359    unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
360    unsigned char salt[32] = { 0 };
361    EVP_CIPHER_CTX e_ctx;
362    int encrypted_len, final_len;
363
364    /* Get some random bits for a key */
365    fd = open("/dev/urandom", O_RDONLY);
366    read(fd, buf, sizeof(buf));
367    close(fd);
368
369    /* Now encrypt it with the password */
370    /* To Do: Make a salt based on some immutable data about this device.
371     * IMEI, or MEID, or CPU serial number, or whatever we can find
372     */
373    /* Turn the password into a key and IV that can decrypt the master key */
374    PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, sizeof(salt),
375                           HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
376
377    /* Initialize the decryption engine */
378    if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
379        SLOGE("EVP_EncryptInit failed\n");
380        return -1;
381    }
382    EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
383    /* Encrypt the master key */
384    if (! EVP_EncryptUpdate(&e_ctx, master_key, &encrypted_len,
385                              buf, KEY_LEN_BYTES)) {
386        SLOGE("EVP_EncryptUpdate failed\n");
387        return -1;
388    }
389    if (! EVP_EncryptFinal(&e_ctx, master_key + encrypted_len, &final_len)) {
390        SLOGE("EVP_EncryptFinal failed\n");
391        return -1;
392    }
393
394    if (encrypted_len + final_len != KEY_LEN_BYTES) {
395        SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
396        return -1;
397    } else {
398        return 0;
399    }
400}
401
402static int decrypt_master_key(char *passwd, unsigned char *encrypted_master_key,
403                              unsigned char *decrypted_master_key)
404{
405  unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
406  unsigned char salt[32] = { 0 };
407  EVP_CIPHER_CTX d_ctx;
408  int decrypted_len, final_len;
409
410  /* To Do: Make a salt based on some immutable data about this device.
411   * IMEI, or MEID, or CPU serial number, or whatever we can find
412   */
413  /* Turn the password into a key and IV that can decrypt the master key */
414  PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, sizeof(salt),
415                         HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
416
417  /* Initialize the decryption engine */
418  if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
419    return -1;
420  }
421  EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
422  /* Decrypt the master key */
423  if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
424                            encrypted_master_key, KEY_LEN_BYTES)) {
425    return -1;
426  }
427  if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
428    return -1;
429  }
430
431  if (decrypted_len + final_len != KEY_LEN_BYTES) {
432    return -1;
433  } else {
434    return 0;
435  }
436}
437
438static int get_orig_mount_parms(char *mount_point, char *fs_type, char *real_blkdev,
439                                unsigned long *mnt_flags, char *fs_options)
440{
441  char mount_point2[32];
442  char fs_flags[32];
443
444  property_get("ro.crypto.fs_type", fs_type, "");
445  property_get("ro.crypto.fs_real_blkdev", real_blkdev, "");
446  property_get("ro.crypto.fs_mnt_point", mount_point2, "");
447  property_get("ro.crypto.fs_options", fs_options, "");
448  property_get("ro.crypto.fs_flags", fs_flags, "");
449  *mnt_flags = strtol(fs_flags, 0, 0);
450
451  if (strcmp(mount_point, mount_point2)) {
452    /* Consistency check.  These should match. If not, something odd happened. */
453    return -1;
454  }
455
456  return 0;
457}
458
459static int wait_and_unmount(char *mountpoint)
460{
461    int i, rc;
462#define WAIT_UNMOUNT_COUNT 100
463
464    /*  Now umount the tmpfs filesystem */
465    for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
466        if (umount(mountpoint)) {
467            sleep(1);
468            i++;
469        } else {
470          break;
471        }
472    }
473
474    if (i < WAIT_UNMOUNT_COUNT) {
475      SLOGD("unmounting %s succeeded\n", mountpoint);
476      rc = 0;
477    } else {
478      SLOGE("unmounting %s failed\n", mountpoint);
479      rc = -1;
480    }
481
482    return rc;
483}
484
485static int cryptfs_restart(char *crypto_blkdev)
486{
487    char fs_type[32];
488    char real_blkdev[MAXPATHLEN];
489    char fs_options[256];
490    unsigned long mnt_flags;
491    struct stat statbuf;
492    int rc = -1, i;
493#define DATA_PREP_TIMEOUT 100
494
495    /* Here is where we shut down the framework.  The init scripts
496     * start all services in one of three classes: core, main or late_start.
497     * On boot, we start core and main.  Now, we stop main, but not core,
498     * as core includes vold and a few other really important things that
499     * we need to keep running.  Once main has stopped, we should be able
500     * to umount the tmpfs /data, then mount the encrypted /data.
501     * We then restart the class main, and also the class late_start.
502     * At the moment, I've only put a few things in late_start that I know
503     * are not needed to bring up the framework, and that also cause problems
504     * with unmounting the tmpfs /data, but I hope to add add more services
505     * to the late_start class as we optimize this to decrease the delay
506     * till the user is asked for the password to the filesystem.
507     */
508
509    /* The init files are setup to stop the class main when vold.decrypt is
510     * set to trigger_reset_main.
511     */
512    property_set("vold.decrypt", "trigger_reset_main");
513    SLOGD("Just asked init to shut down class main\n");
514
515    /* Now that the framework is shutdown, we should be able to umount()
516     * the tmpfs filesystem, and mount the real one.
517     */
518
519    if (! get_orig_mount_parms("/data", fs_type, real_blkdev, &mnt_flags, fs_options)) {
520        SLOGD("Just got orig mount parms\n");
521
522        if (! (rc = wait_and_unmount("/data")) ) {
523            /* If that succeeded, then mount the decrypted filesystem */
524            mount(crypto_blkdev, "/data", fs_type, mnt_flags, fs_options);
525
526            /* Do the prep of the /data filesystem */
527            property_set("vold.post_fs_data_done", "0");
528            property_set("vold.decrypt", "trigger_post_fs_data");
529            SLOGD("Just triggered post_fs_data\n");
530
531            /* Wait a max of 25 seconds, hopefully it takes much less */
532            for (i=0; i<DATA_PREP_TIMEOUT; i++) {
533                char p[16];;
534
535                property_get("vold.post_fs_data_done", p, "0");
536                if (*p == '1') {
537                    break;
538                } else {
539                    usleep(250000);
540                }
541            }
542            if (i == DATA_PREP_TIMEOUT) {
543                /* Ugh, we failed to prep /data in time.  Bail. */
544                return -1;
545            }
546
547            /* startup service classes main and late_start */
548            property_set("vold.decrypt", "trigger_restart_framework");
549            SLOGD("Just triggered restart_framework\n");
550
551            /* Give it a few moments to get started */
552            sleep(1);
553        }
554    }
555
556    return rc;
557}
558
559static int test_mount_encrypted_fs(char *passwd, char *mount_point)
560{
561  struct crypt_mnt_ftr crypt_ftr;
562  /* Allocate enough space for a 256 bit key, but we may use less */
563  unsigned char encrypted_master_key[32], decrypted_master_key[32];
564  char crypto_blkdev[MAXPATHLEN];
565  char real_blkdev[MAXPATHLEN];
566  char fs_type[32];
567  char fs_options[256];
568  char tmp_mount_point[64];
569  unsigned long mnt_flags;
570  unsigned int orig_failed_decrypt_count;
571  int rc;
572
573  if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
574    SLOGE("Error reading original mount parms for mount point %s\n", mount_point);
575    return -1;
576  }
577
578  if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key)) {
579    SLOGE("Error getting crypt footer and key\n");
580    return -1;
581  }
582  SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
583  orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
584
585  if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
586    decrypt_master_key(passwd, encrypted_master_key, decrypted_master_key);
587  }
588
589  if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
590                               real_blkdev, crypto_blkdev)) {
591    SLOGE("Error creating decrypted block device\n");
592    return -1;
593  }
594
595  /* If init detects an encrypted filesystme, it writes a file for each such
596   * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
597   * files and passes that data to me */
598  /* Create a tmp mount point to try mounting the decryptd fs
599   * Since we're here, the mount_point should be a tmpfs filesystem, so make
600   * a directory in it to test mount the decrypted filesystem.
601   */
602  sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
603  mkdir(tmp_mount_point, 0755);
604  if ( mount(crypto_blkdev, tmp_mount_point, "ext4", MS_RDONLY, "") ) {
605    SLOGE("Error temp mounting decrypted block device\n");
606    delete_crypto_blk_dev(crypto_blkdev);
607    crypt_ftr.failed_decrypt_count++;
608  } else {
609    /* Success, so just umount and we'll mount it properly when we restart
610     * the framework.
611     */
612    umount(tmp_mount_point);
613    crypt_ftr.failed_decrypt_count  = 0;
614  }
615
616  if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
617    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0);
618  }
619
620  if (crypt_ftr.failed_decrypt_count) {
621    /* We failed to mount the device, so return an error */
622    rc = crypt_ftr.failed_decrypt_count;
623
624  } else {
625    /* Woot!  Success!  Time to do the magic of unmounting the tmpfs
626     * disk and mounting the encrypted one.
627     */
628    rc = cryptfs_restart(crypto_blkdev);
629  }
630
631  return rc;
632}
633
634int cryptfs_check_passwd(char *passwd)
635{
636    int rc = -1;
637
638    rc = test_mount_encrypted_fs(passwd, "/data");
639
640    return rc;
641}
642
643/* Initialize a crypt_mnt_ftr structure.  The keysize is
644 * defaulted to 16 bytes, and the filesystem size to 0.
645 * Presumably, at a minimum, the caller will update the
646 * filesystem size and crypto_type_name after calling this function.
647 */
648static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
649{
650    ftr->magic = CRYPT_MNT_MAGIC;
651    ftr->major_version = 1;
652    ftr->minor_version = 0;
653    ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
654    ftr->flags = 0;
655    ftr->keysize = 16;
656    ftr->spare1 = 0;
657    ftr->fs_size = 0;
658    ftr->failed_decrypt_count = 0;
659    ftr->crypto_type_name[0] = '\0';
660}
661
662static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size)
663{
664    char cmdline[256];
665    int rc = -1;
666
667    snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
668             size * 512, crypto_blkdev);
669    SLOGI("Making empty filesystem with command %s\n", cmdline);
670    if (system(cmdline)) {
671      SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
672    } else {
673      SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
674      rc = 0;
675    }
676
677    return rc;
678}
679
680static inline int unix_read(int  fd, void*  buff, int  len)
681{
682    int  ret;
683    do { ret = read(fd, buff, len); } while (ret < 0 && errno == EINTR);
684    return ret;
685}
686
687static inline int unix_write(int  fd, const void*  buff, int  len)
688{
689    int  ret;
690    do { ret = write(fd, buff, len); } while (ret < 0 && errno == EINTR);
691    return ret;
692}
693
694#define CRYPT_INPLACE_BUFSIZE 4096
695#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
696static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size)
697{
698    int realfd, cryptofd;
699    char *buf[CRYPT_INPLACE_BUFSIZE];
700    int rc = -1;
701    off64_t numblocks, i, remainder;
702
703    if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
704        SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
705        return -1;
706    }
707
708    if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
709        SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
710        close(realfd);
711        return -1;
712    }
713
714    /* This is pretty much a simple loop of reading 4K, and writing 4K.
715     * The size passed in is the number of 512 byte sectors in the filesystem.
716     * So compute the number of whole 4K blocks we should read/write,
717     * and the remainder.
718     */
719    numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
720    remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
721
722    SLOGE("Encrypting filesystem in place...");
723
724    /* process the majority of the filesystem in blocks */
725    for (i=0; i<numblocks; i++) {
726        if ( ! (i % 65536)) { //KEN
727            SLOGE("|"); //KEN
728        } //KEN
729        if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
730            SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
731            goto errout;
732        }
733        if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
734            SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
735            goto errout;
736        }
737    }
738
739    /* Do any remaining sectors */
740    for (i=0; i<remainder; i++) {
741        if (unix_read(realfd, buf, 512) <= 0) {
742            SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
743            goto errout;
744        }
745        if (unix_write(cryptofd, buf, 512) <= 0) {
746            SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
747            goto errout;
748        }
749    }
750
751    rc = 0;
752
753errout:
754    close(realfd);
755    close(cryptofd);
756
757    return rc;
758}
759
760#define CRYPTO_ENABLE_WIPE 1
761#define CRYPTO_ENABLE_INPLACE 2
762int cryptfs_enable(char *howarg, char *passwd)
763{
764    int how = 0;
765    char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
766    char fs_type[32], fs_options[256], mount_point[32];
767    unsigned long mnt_flags, nr_sec;
768    unsigned char master_key[16], decrypted_master_key[16];
769    int rc, fd;
770    struct crypt_mnt_ftr crypt_ftr;
771
772    if (!strcmp(howarg, "wipe")) {
773      how = CRYPTO_ENABLE_WIPE;
774    } else if (! strcmp(howarg, "inplace")) {
775      how = CRYPTO_ENABLE_INPLACE;
776    } else {
777      /* Shouldn't happen, as CommandListener vets the args */
778      return -1;
779    }
780
781    get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options);
782
783    /* The init files are setup to stop the class main and late start when
784     * set to 4.  They also unmount the fuse filesystem /mnt/sdcard on stingray.
785     */
786    property_set("vold.decrypt", "trigger_shutdown_framework");
787    SLOGD("Just asked init to shut down class main\n");
788
789    /* Temporary hack FIX ME!*/
790    sleep(30);
791    umount("/mnt/sdcard");
792
793    /* Now unmount the /data partition. */
794    if (! (rc = wait_and_unmount("/data")) ) {
795        /* OK, we've unmounted /data, time to setup an encrypted
796         * mapping, and either write a new filesystem or encrypt
797         * in place.
798         */
799
800        fd = open(real_blkdev, O_RDONLY);
801        if ( (nr_sec = get_blkdev_size(fd)) == 0) {
802            SLOGE("Cannot get size of block device %s\n", real_blkdev);
803            return -1;
804        }
805        close(fd);
806
807        /* Initialize a crypt_mnt_ftr for the partition */
808        cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
809        crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
810        strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
811
812        /* Make an encrypted master key */
813        if (create_encrypted_random_key(passwd, master_key)) {
814            SLOGE("Cannot create encrypted master key\n");
815            return -1;
816        }
817
818        /* Write the key to the end of the partition */
819        put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, master_key);
820
821        decrypt_master_key(passwd, master_key, decrypted_master_key);
822        create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev);
823
824        if (how == CRYPTO_ENABLE_WIPE) {
825            rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size);
826        } else if (how == CRYPTO_ENABLE_INPLACE) {
827            rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size);
828        } else {
829            /* Shouldn't happen */
830            SLOGE("cryptfs_enable: internal error, unknown option\n");
831            return -1;
832        }
833
834        if (! rc) {
835            delete_crypto_blk_dev(crypto_blkdev);
836            sync();
837            reboot(LINUX_REBOOT_CMD_RESTART);
838        }
839    } else {
840        return -1;
841    }
842
843    return 0;
844}
845
846