cryptfs.c revision 0cc166385a7e1d3026bbcb62f094e419f779e872
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    static int restart_successful = 0;
532
533    /* Validate that it's OK to call this routine */
534    if (! key_sha1_saved) {
535        SLOGE("Encrypted filesystem not validated, aborting");
536        return -1;
537    }
538
539    if (restart_successful) {
540        SLOGE("System already restarted with encrypted disk, aborting");
541        return -1;
542    }
543
544    /* Here is where we shut down the framework.  The init scripts
545     * start all services in one of three classes: core, main or late_start.
546     * On boot, we start core and main.  Now, we stop main, but not core,
547     * as core includes vold and a few other really important things that
548     * we need to keep running.  Once main has stopped, we should be able
549     * to umount the tmpfs /data, then mount the encrypted /data.
550     * We then restart the class main, and also the class late_start.
551     * At the moment, I've only put a few things in late_start that I know
552     * are not needed to bring up the framework, and that also cause problems
553     * with unmounting the tmpfs /data, but I hope to add add more services
554     * to the late_start class as we optimize this to decrease the delay
555     * till the user is asked for the password to the filesystem.
556     */
557
558    /* The init files are setup to stop the class main when vold.decrypt is
559     * set to trigger_reset_main.
560     */
561    property_set("vold.decrypt", "trigger_reset_main");
562    SLOGD("Just asked init to shut down class main\n");
563
564    /* Now that the framework is shutdown, we should be able to umount()
565     * the tmpfs filesystem, and mount the real one.
566     */
567
568    property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
569    if (strlen(crypto_blkdev) == 0) {
570        SLOGE("fs_crypto_blkdev not set\n");
571        return -1;
572    }
573
574    if (! get_orig_mount_parms(DATA_MNT_POINT, fs_type, real_blkdev, &mnt_flags, fs_options)) {
575        SLOGD("Just got orig mount parms\n");
576
577        if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
578            /* If that succeeded, then mount the decrypted filesystem */
579            mount(crypto_blkdev, DATA_MNT_POINT, fs_type, mnt_flags, fs_options);
580
581            /* Create necessary paths on /data */
582            if (prep_data_fs()) {
583                return -1;
584            }
585
586            /* startup service classes main and late_start */
587            property_set("vold.decrypt", "trigger_restart_framework");
588            SLOGD("Just triggered restart_framework\n");
589
590            /* Give it a few moments to get started */
591            sleep(1);
592        }
593    }
594
595    if (rc == 0) {
596        restart_successful = 1;
597    }
598
599    return rc;
600}
601
602static int test_mount_encrypted_fs(char *passwd, char *mount_point)
603{
604  struct crypt_mnt_ftr crypt_ftr;
605  /* Allocate enough space for a 256 bit key, but we may use less */
606  unsigned char encrypted_master_key[32], decrypted_master_key[32];
607  char crypto_blkdev[MAXPATHLEN];
608  char real_blkdev[MAXPATHLEN];
609  char fs_type[32];
610  char fs_options[256];
611  char tmp_mount_point[64];
612  unsigned long mnt_flags;
613  unsigned int orig_failed_decrypt_count;
614  char encrypted_state[32];
615  int rc;
616
617  property_get("ro.crypto.state", encrypted_state, "");
618  if ( key_sha1_saved || strcmp(encrypted_state, "encrypted") ) {
619    SLOGE("encrypted fs already validated or not running with encryption, aborting");
620    return -1;
621  }
622
623  if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
624    SLOGE("Error reading original mount parms for mount point %s\n", mount_point);
625    return -1;
626  }
627
628  if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key)) {
629    SLOGE("Error getting crypt footer and key\n");
630    return -1;
631  }
632  SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
633  orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
634
635  if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
636    decrypt_master_key(passwd, encrypted_master_key, decrypted_master_key);
637  }
638
639  if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
640                               real_blkdev, crypto_blkdev)) {
641    SLOGE("Error creating decrypted block device\n");
642    return -1;
643  }
644
645  /* If init detects an encrypted filesystme, it writes a file for each such
646   * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
647   * files and passes that data to me */
648  /* Create a tmp mount point to try mounting the decryptd fs
649   * Since we're here, the mount_point should be a tmpfs filesystem, so make
650   * a directory in it to test mount the decrypted filesystem.
651   */
652  sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
653  mkdir(tmp_mount_point, 0755);
654  if ( mount(crypto_blkdev, tmp_mount_point, "ext4", MS_RDONLY, "") ) {
655    SLOGE("Error temp mounting decrypted block device\n");
656    delete_crypto_blk_dev(crypto_blkdev);
657    crypt_ftr.failed_decrypt_count++;
658  } else {
659    /* Success, so just umount and we'll mount it properly when we restart
660     * the framework.
661     */
662    umount(tmp_mount_point);
663    crypt_ftr.failed_decrypt_count  = 0;
664  }
665
666  if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
667    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0);
668  }
669
670  if (crypt_ftr.failed_decrypt_count) {
671    /* We failed to mount the device, so return an error */
672    rc = crypt_ftr.failed_decrypt_count;
673
674  } else {
675    /* Woot!  Success!  Save the name of the crypto block device
676     * so we can mount it when restarting the framework.
677     */
678    property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
679    /* Also save a SHA1 of the master key so we can know if we
680     * successfully decrypted the key when we want to change the
681     * password on it.
682     */
683    SHA1(decrypted_master_key, KEY_LEN_BYTES, saved_key_sha1);
684    key_sha1_saved = 1;
685    rc = 0;
686  }
687
688  return rc;
689}
690
691int cryptfs_check_passwd(char *passwd)
692{
693    int rc = -1;
694
695    rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT);
696
697    return rc;
698}
699
700/* Initialize a crypt_mnt_ftr structure.  The keysize is
701 * defaulted to 16 bytes, and the filesystem size to 0.
702 * Presumably, at a minimum, the caller will update the
703 * filesystem size and crypto_type_name after calling this function.
704 */
705static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
706{
707    ftr->magic = CRYPT_MNT_MAGIC;
708    ftr->major_version = 1;
709    ftr->minor_version = 0;
710    ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
711    ftr->flags = 0;
712    ftr->keysize = 16;
713    ftr->spare1 = 0;
714    ftr->fs_size = 0;
715    ftr->failed_decrypt_count = 0;
716    ftr->crypto_type_name[0] = '\0';
717}
718
719static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size)
720{
721    char cmdline[256];
722    int rc = -1;
723
724    snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
725             size * 512, crypto_blkdev);
726    SLOGI("Making empty filesystem with command %s\n", cmdline);
727    if (system(cmdline)) {
728      SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
729    } else {
730      SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
731      rc = 0;
732    }
733
734    return rc;
735}
736
737static inline int unix_read(int  fd, void*  buff, int  len)
738{
739    int  ret;
740    do { ret = read(fd, buff, len); } while (ret < 0 && errno == EINTR);
741    return ret;
742}
743
744static inline int unix_write(int  fd, const void*  buff, int  len)
745{
746    int  ret;
747    do { ret = write(fd, buff, len); } while (ret < 0 && errno == EINTR);
748    return ret;
749}
750
751#define CRYPT_INPLACE_BUFSIZE 4096
752#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
753static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size)
754{
755    int realfd, cryptofd;
756    char *buf[CRYPT_INPLACE_BUFSIZE];
757    int rc = -1;
758    off64_t numblocks, i, remainder;
759    off64_t one_pct, cur_pct, new_pct;
760
761    if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
762        SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
763        return -1;
764    }
765
766    if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
767        SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
768        close(realfd);
769        return -1;
770    }
771
772    /* This is pretty much a simple loop of reading 4K, and writing 4K.
773     * The size passed in is the number of 512 byte sectors in the filesystem.
774     * So compute the number of whole 4K blocks we should read/write,
775     * and the remainder.
776     */
777    numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
778    remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
779
780    SLOGE("Encrypting filesystem in place...");
781
782    one_pct = numblocks / 100;
783    cur_pct = 0;
784    /* process the majority of the filesystem in blocks */
785    for (i=0; i<numblocks; i++) {
786        new_pct = i / one_pct;
787        if (new_pct > cur_pct) {
788            char buf[8];
789
790            cur_pct = new_pct;
791            snprintf(buf, sizeof(buf), "%lld", cur_pct);
792            property_set("vold.encrypt_progress", buf);
793        }
794        if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
795            SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
796            goto errout;
797        }
798        if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
799            SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
800            goto errout;
801        }
802    }
803
804    /* Do any remaining sectors */
805    for (i=0; i<remainder; i++) {
806        if (unix_read(realfd, buf, 512) <= 0) {
807            SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
808            goto errout;
809        }
810        if (unix_write(cryptofd, buf, 512) <= 0) {
811            SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
812            goto errout;
813        }
814    }
815
816    property_set("vold.encrypt_progress", "100");
817
818    rc = 0;
819
820errout:
821    close(realfd);
822    close(cryptofd);
823
824    return rc;
825}
826
827#define CRYPTO_ENABLE_WIPE 1
828#define CRYPTO_ENABLE_INPLACE 2
829
830#define FRAMEWORK_BOOT_WAIT 60
831
832int cryptfs_enable(char *howarg, char *passwd)
833{
834    int how = 0;
835    char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
836    char fs_type[32], fs_options[256], mount_point[32];
837    unsigned long mnt_flags, nr_sec;
838    unsigned char master_key[16], decrypted_master_key[16];
839    int rc=-1, fd, i;
840    struct crypt_mnt_ftr crypt_ftr;
841    char tmpfs_options[80];
842    char encrypted_state[32];
843
844    property_get("ro.crypto.state", encrypted_state, "");
845    if (strcmp(encrypted_state, "unencrypted")) {
846        SLOGE("Device is already running encrypted, aborting");
847        return -1;
848    }
849
850    if (!strcmp(howarg, "wipe")) {
851      how = CRYPTO_ENABLE_WIPE;
852    } else if (! strcmp(howarg, "inplace")) {
853      how = CRYPTO_ENABLE_INPLACE;
854    } else {
855      /* Shouldn't happen, as CommandListener vets the args */
856      return -1;
857    }
858
859    get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options);
860
861    /* The init files are setup to stop the class main and late start when
862     * vold sets trigger_shutdown_framework.
863     */
864    property_set("vold.decrypt", "trigger_shutdown_framework");
865    SLOGD("Just asked init to shut down class main\n");
866
867    if (wait_and_unmount("/mnt/sdcard")) {
868        return -1;
869    }
870
871    /* Now unmount the /data partition. */
872    if (wait_and_unmount(DATA_MNT_POINT)) {
873        return -1;
874    }
875
876    /* Do extra work for a better UX when doing the long inplace encryption */
877    if (how == CRYPTO_ENABLE_INPLACE) {
878        /* Now that /data is unmounted, we need to mount a tmpfs
879         * /data, set a property saying we're doing inplace encryption,
880         * and restart the framework.
881         */
882        property_get("ro.crypto.tmpfs_options", tmpfs_options, "");
883        if (mount("tmpfs", DATA_MNT_POINT, "tmpfs", MS_NOATIME | MS_NOSUID | MS_NODEV,
884            tmpfs_options) < 0) {
885            return -1;
886        }
887        /* Tells the framework that inplace encryption is starting */
888        property_set("vold.encrypt_progress", "0");
889
890        /* restart the framework. */
891        /* Create necessary paths on /data */
892        if (prep_data_fs()) {
893            return -1;
894        }
895
896        /* startup service classes main and late_start */
897        property_set("vold.decrypt", "trigger_restart_min_framework");
898        SLOGD("Just triggered restart_min_framework\n");
899
900        /* OK, the framework is restarted and will soon be showing a
901         * progress bar.  Time to setup an encrypted mapping, and
902         * either write a new filesystem, or encrypt in place updating
903         * the progress bar as we work.
904         */
905    }
906
907    /* Start the actual work of making an encrypted filesystem */
908    fd = open(real_blkdev, O_RDONLY);
909    if ( (nr_sec = get_blkdev_size(fd)) == 0) {
910        SLOGE("Cannot get size of block device %s\n", real_blkdev);
911        return -1;
912    }
913    close(fd);
914
915    /* Initialize a crypt_mnt_ftr for the partition */
916    cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
917    crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
918    strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
919
920    /* Make an encrypted master key */
921    if (create_encrypted_random_key(passwd, master_key)) {
922        SLOGE("Cannot create encrypted master key\n");
923        return -1;
924    }
925
926    /* Write the key to the end of the partition */
927    put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, master_key);
928
929    decrypt_master_key(passwd, master_key, decrypted_master_key);
930    create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev);
931
932    if (how == CRYPTO_ENABLE_WIPE) {
933        rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size);
934    } else if (how == CRYPTO_ENABLE_INPLACE) {
935        rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size);
936    } else {
937        /* Shouldn't happen */
938        SLOGE("cryptfs_enable: internal error, unknown option\n");
939        return -1;
940    }
941
942    /* Undo the dm-crypt mapping whether we succeed or not */
943    delete_crypto_blk_dev(crypto_blkdev);
944
945    if (! rc) {
946        /* Success */
947        sleep(2); /* Give the UI a change to show 100% progress */
948        sync();
949        reboot(LINUX_REBOOT_CMD_RESTART);
950    }
951
952    /* Only returns on error */
953    return rc;
954}
955
956int cryptfs_changepw(char *oldpw, char *newpw)
957{
958    struct crypt_mnt_ftr crypt_ftr;
959    unsigned char encrypted_master_key[32], decrypted_master_key[32];
960    unsigned char new_key_sha1[20];
961    char real_blkdev[MAXPATHLEN];
962
963    /* This is only allowed after we've successfully decrypted the master key */
964    if (! key_sha1_saved) {
965        SLOGE("Key not saved, aborting");
966        return -1;
967    }
968
969    property_get("ro.crypto.fs_real_blkdev", real_blkdev, "");
970    if (strlen(real_blkdev) == 0) {
971        SLOGE("Can't find real blkdev");
972        return -1;
973    }
974
975    /* get key */
976    if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key)) {
977      SLOGE("Error getting crypt footer and key");
978      return -1;
979    }
980
981    /* decrypt key with old passwd */
982    decrypt_master_key(oldpw, encrypted_master_key, decrypted_master_key);
983
984    /* compute sha1 of decrypted key */
985    SHA1(decrypted_master_key, KEY_LEN_BYTES, new_key_sha1);
986
987    /* If computed sha1 and saved sha1 match, encrypt key with new passwd */
988    if (! memcmp(saved_key_sha1, new_key_sha1, sizeof(saved_key_sha1))) {
989        /* they match, it's safe to re-encrypt the key */
990        encrypt_master_key(newpw, decrypted_master_key, encrypted_master_key);
991
992        /* save the key */
993        put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key);
994    } else {
995        SLOGE("SHA1 mismatch");
996        return -1;
997    }
998
999    return 0;
1000}
1001
1002