cryptfs.c revision 6864b7ec94a57b73c300457955d86dc604aeddf5
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);  // Only for debugging, prints the master key!
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 20
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
485int cryptfs_restart(void)
486{
487    char fs_type[32];
488    char real_blkdev[MAXPATHLEN];
489    char crypto_blkdev[MAXPATHLEN];
490    char fs_options[256];
491    unsigned long mnt_flags;
492    struct stat statbuf;
493    int rc = -1, i;
494#define DATA_PREP_TIMEOUT 100
495
496    /* Here is where we shut down the framework.  The init scripts
497     * start all services in one of three classes: core, main or late_start.
498     * On boot, we start core and main.  Now, we stop main, but not core,
499     * as core includes vold and a few other really important things that
500     * we need to keep running.  Once main has stopped, we should be able
501     * to umount the tmpfs /data, then mount the encrypted /data.
502     * We then restart the class main, and also the class late_start.
503     * At the moment, I've only put a few things in late_start that I know
504     * are not needed to bring up the framework, and that also cause problems
505     * with unmounting the tmpfs /data, but I hope to add add more services
506     * to the late_start class as we optimize this to decrease the delay
507     * till the user is asked for the password to the filesystem.
508     */
509
510    /* The init files are setup to stop the class main when vold.decrypt is
511     * set to trigger_reset_main.
512     */
513    property_set("vold.decrypt", "trigger_reset_main");
514    SLOGD("Just asked init to shut down class main\n");
515
516    /* Now that the framework is shutdown, we should be able to umount()
517     * the tmpfs filesystem, and mount the real one.
518     */
519
520    property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
521    if (strlen(crypto_blkdev) == 0) {
522        SLOGE("fs_crypto_blkdev not set\n");
523        return -1;
524    }
525
526    if (! get_orig_mount_parms("/data", fs_type, real_blkdev, &mnt_flags, fs_options)) {
527        SLOGD("Just got orig mount parms\n");
528
529        if (! (rc = wait_and_unmount("/data")) ) {
530            /* If that succeeded, then mount the decrypted filesystem */
531            mount(crypto_blkdev, "/data", fs_type, mnt_flags, fs_options);
532
533            /* Do the prep of the /data filesystem */
534            property_set("vold.post_fs_data_done", "0");
535            property_set("vold.decrypt", "trigger_post_fs_data");
536            SLOGD("Just triggered post_fs_data\n");
537
538            /* Wait a max of 25 seconds, hopefully it takes much less */
539            for (i=0; i<DATA_PREP_TIMEOUT; i++) {
540                char p[16];;
541
542                property_get("vold.post_fs_data_done", p, "0");
543                if (*p == '1') {
544                    break;
545                } else {
546                    usleep(250000);
547                }
548            }
549            if (i == DATA_PREP_TIMEOUT) {
550                /* Ugh, we failed to prep /data in time.  Bail. */
551                return -1;
552            }
553
554            /* startup service classes main and late_start */
555            property_set("vold.decrypt", "trigger_restart_framework");
556            SLOGD("Just triggered restart_framework\n");
557
558            /* Give it a few moments to get started */
559            sleep(1);
560        }
561    }
562
563    return rc;
564}
565
566static int test_mount_encrypted_fs(char *passwd, char *mount_point)
567{
568  struct crypt_mnt_ftr crypt_ftr;
569  /* Allocate enough space for a 256 bit key, but we may use less */
570  unsigned char encrypted_master_key[32], decrypted_master_key[32];
571  char crypto_blkdev[MAXPATHLEN];
572  char real_blkdev[MAXPATHLEN];
573  char fs_type[32];
574  char fs_options[256];
575  char tmp_mount_point[64];
576  unsigned long mnt_flags;
577  unsigned int orig_failed_decrypt_count;
578  int rc;
579
580  if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
581    SLOGE("Error reading original mount parms for mount point %s\n", mount_point);
582    return -1;
583  }
584
585  if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key)) {
586    SLOGE("Error getting crypt footer and key\n");
587    return -1;
588  }
589  SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
590  orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
591
592  if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
593    decrypt_master_key(passwd, encrypted_master_key, decrypted_master_key);
594  }
595
596  if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
597                               real_blkdev, crypto_blkdev)) {
598    SLOGE("Error creating decrypted block device\n");
599    return -1;
600  }
601
602  /* If init detects an encrypted filesystme, it writes a file for each such
603   * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
604   * files and passes that data to me */
605  /* Create a tmp mount point to try mounting the decryptd fs
606   * Since we're here, the mount_point should be a tmpfs filesystem, so make
607   * a directory in it to test mount the decrypted filesystem.
608   */
609  sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
610  mkdir(tmp_mount_point, 0755);
611  if ( mount(crypto_blkdev, tmp_mount_point, "ext4", MS_RDONLY, "") ) {
612    SLOGE("Error temp mounting decrypted block device\n");
613    delete_crypto_blk_dev(crypto_blkdev);
614    crypt_ftr.failed_decrypt_count++;
615  } else {
616    /* Success, so just umount and we'll mount it properly when we restart
617     * the framework.
618     */
619    umount(tmp_mount_point);
620    crypt_ftr.failed_decrypt_count  = 0;
621  }
622
623  if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
624    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0);
625  }
626
627  if (crypt_ftr.failed_decrypt_count) {
628    /* We failed to mount the device, so return an error */
629    rc = crypt_ftr.failed_decrypt_count;
630
631  } else {
632    /* Woot!  Success!  Save the name of the crypto block device
633     * so we can mount it when restarting the framework.
634     */
635    property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
636    rc = 0;
637  }
638
639  return rc;
640}
641
642int cryptfs_check_passwd(char *passwd)
643{
644    int rc = -1;
645
646    rc = test_mount_encrypted_fs(passwd, "/data");
647
648    return rc;
649}
650
651/* Initialize a crypt_mnt_ftr structure.  The keysize is
652 * defaulted to 16 bytes, and the filesystem size to 0.
653 * Presumably, at a minimum, the caller will update the
654 * filesystem size and crypto_type_name after calling this function.
655 */
656static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
657{
658    ftr->magic = CRYPT_MNT_MAGIC;
659    ftr->major_version = 1;
660    ftr->minor_version = 0;
661    ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
662    ftr->flags = 0;
663    ftr->keysize = 16;
664    ftr->spare1 = 0;
665    ftr->fs_size = 0;
666    ftr->failed_decrypt_count = 0;
667    ftr->crypto_type_name[0] = '\0';
668}
669
670static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size)
671{
672    char cmdline[256];
673    int rc = -1;
674
675    snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
676             size * 512, crypto_blkdev);
677    SLOGI("Making empty filesystem with command %s\n", cmdline);
678    if (system(cmdline)) {
679      SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
680    } else {
681      SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
682      rc = 0;
683    }
684
685    return rc;
686}
687
688static inline int unix_read(int  fd, void*  buff, int  len)
689{
690    int  ret;
691    do { ret = read(fd, buff, len); } while (ret < 0 && errno == EINTR);
692    return ret;
693}
694
695static inline int unix_write(int  fd, const void*  buff, int  len)
696{
697    int  ret;
698    do { ret = write(fd, buff, len); } while (ret < 0 && errno == EINTR);
699    return ret;
700}
701
702#define CRYPT_INPLACE_BUFSIZE 4096
703#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
704static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size)
705{
706    int realfd, cryptofd;
707    char *buf[CRYPT_INPLACE_BUFSIZE];
708    int rc = -1;
709    off64_t numblocks, i, remainder;
710
711    if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
712        SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
713        return -1;
714    }
715
716    if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
717        SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
718        close(realfd);
719        return -1;
720    }
721
722    /* This is pretty much a simple loop of reading 4K, and writing 4K.
723     * The size passed in is the number of 512 byte sectors in the filesystem.
724     * So compute the number of whole 4K blocks we should read/write,
725     * and the remainder.
726     */
727    numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
728    remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
729
730    SLOGE("Encrypting filesystem in place...");
731
732    /* process the majority of the filesystem in blocks */
733    for (i=0; i<numblocks; i++) {
734        if ( ! (i % 65536)) { //KEN
735            SLOGE("|"); //KEN
736        } //KEN
737        if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
738            SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
739            goto errout;
740        }
741        if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
742            SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
743            goto errout;
744        }
745    }
746
747    /* Do any remaining sectors */
748    for (i=0; i<remainder; i++) {
749        if (unix_read(realfd, buf, 512) <= 0) {
750            SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
751            goto errout;
752        }
753        if (unix_write(cryptofd, buf, 512) <= 0) {
754            SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
755            goto errout;
756        }
757    }
758
759    rc = 0;
760
761errout:
762    close(realfd);
763    close(cryptofd);
764
765    return rc;
766}
767
768#define CRYPTO_ENABLE_WIPE 1
769#define CRYPTO_ENABLE_INPLACE 2
770int cryptfs_enable(char *howarg, char *passwd)
771{
772    int how = 0;
773    char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
774    char fs_type[32], fs_options[256], mount_point[32];
775    unsigned long mnt_flags, nr_sec;
776    unsigned char master_key[16], decrypted_master_key[16];
777    int rc, fd;
778    struct crypt_mnt_ftr crypt_ftr;
779
780    if (!strcmp(howarg, "wipe")) {
781      how = CRYPTO_ENABLE_WIPE;
782    } else if (! strcmp(howarg, "inplace")) {
783      how = CRYPTO_ENABLE_INPLACE;
784    } else {
785      /* Shouldn't happen, as CommandListener vets the args */
786      return -1;
787    }
788
789    get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options);
790
791    /* The init files are setup to stop the class main and late start when
792     * set to 4.  They also unmount the fuse filesystem /mnt/sdcard on stingray.
793     */
794    property_set("vold.decrypt", "trigger_shutdown_framework");
795    SLOGD("Just asked init to shut down class main\n");
796
797    if (wait_and_unmount("/mnt/sdcard")) {
798        return -1;
799    }
800
801    /* Now unmount the /data partition. */
802    if (! (rc = wait_and_unmount("/data")) ) {
803        /* OK, we've unmounted /data, time to setup an encrypted
804         * mapping, and either write a new filesystem or encrypt
805         * in place.
806         */
807
808        fd = open(real_blkdev, O_RDONLY);
809        if ( (nr_sec = get_blkdev_size(fd)) == 0) {
810            SLOGE("Cannot get size of block device %s\n", real_blkdev);
811            return -1;
812        }
813        close(fd);
814
815        /* Initialize a crypt_mnt_ftr for the partition */
816        cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
817        crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
818        strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
819
820        /* Make an encrypted master key */
821        if (create_encrypted_random_key(passwd, master_key)) {
822            SLOGE("Cannot create encrypted master key\n");
823            return -1;
824        }
825
826        /* Write the key to the end of the partition */
827        put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, master_key);
828
829        decrypt_master_key(passwd, master_key, decrypted_master_key);
830        create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev);
831
832        if (how == CRYPTO_ENABLE_WIPE) {
833            rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size);
834        } else if (how == CRYPTO_ENABLE_INPLACE) {
835            rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size);
836        } else {
837            /* Shouldn't happen */
838            SLOGE("cryptfs_enable: internal error, unknown option\n");
839            return -1;
840        }
841
842        if (! rc) {
843            delete_crypto_blk_dev(crypto_blkdev);
844            sync();
845            reboot(LINUX_REBOOT_CMD_RESTART);
846        }
847    } else {
848        return -1;
849    }
850
851    return 0;
852}
853
854