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