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