cryptfs.c revision e87440703663f5ee326326f6438f3b00ea315623
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 or salt can be NULL, in which case just skip writing that value.  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, unsigned char *salt)
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  if (salt) {
128    /* Compute the offset for start of the crypt footer */
129    off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
130    /* Add in the length of the footer, key and padding */
131    off += sizeof(struct crypt_mnt_ftr) + crypt_ftr->keysize + KEY_TO_SALT_PADDING;
132
133    if (lseek64(fd, off, SEEK_SET) == -1) {
134      SLOGE("Cannot seek to real block device salt \n");
135      goto errout;
136    }
137
138    if ( (cnt = write(fd, salt, SALT_LEN)) != SALT_LEN) {
139      SLOGE("Cannot write salt for real block device %s\n", real_blk_name);
140      goto errout;
141    }
142  }
143
144  /* Success! */
145  rc = 0;
146
147errout:
148  close(fd);
149  return rc;
150
151}
152
153static int get_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
154                                  unsigned char *key, unsigned char *salt)
155{
156  int fd;
157  unsigned int nr_sec, cnt;
158  off64_t off;
159  int rc = -1;
160
161  if ( (fd = open(real_blk_name, O_RDWR)) < 0) {
162    SLOGE("Cannot open real block device %s\n", real_blk_name);
163    return -1;
164  }
165
166  if ( (nr_sec = get_blkdev_size(fd)) == 0) {
167    SLOGE("Cannot get size of block device %s\n", real_blk_name);
168    goto errout;
169  }
170
171  /* If it's an encrypted Android partition, the last 16 Kbytes contain the
172   * encryption info footer and key, and plenty of bytes to spare for future
173   * growth.
174   */
175  off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
176
177  if (lseek64(fd, off, SEEK_SET) == -1) {
178    SLOGE("Cannot seek to real block device footer\n");
179    goto errout;
180  }
181
182  if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
183    SLOGE("Cannot read real block device footer\n");
184    goto errout;
185  }
186
187  if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
188    SLOGE("Bad magic for real block device %s\n", real_blk_name);
189    goto errout;
190  }
191
192  if (crypt_ftr->major_version != 1) {
193    SLOGE("Cannot understand major version %d real block device footer\n",
194          crypt_ftr->major_version);
195    goto errout;
196  }
197
198  if (crypt_ftr->minor_version != 0) {
199    SLOGW("Warning: crypto footer minor version %d, expected 0, continuing...\n",
200          crypt_ftr->minor_version);
201  }
202
203  if (crypt_ftr->ftr_size > sizeof(struct crypt_mnt_ftr)) {
204    /* the footer size is bigger than we expected.
205     * Skip to it's stated end so we can read the key.
206     */
207    if (lseek(fd, crypt_ftr->ftr_size - sizeof(struct crypt_mnt_ftr),  SEEK_CUR) == -1) {
208      SLOGE("Cannot seek to start of key\n");
209      goto errout;
210    }
211  }
212
213  if (crypt_ftr->keysize != 16) {
214    SLOGE("Keysize of %d bits not supported for real block device %s\n",
215          crypt_ftr->keysize * 8, real_blk_name);
216    goto errout;
217  }
218
219  if ( (cnt = read(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
220    SLOGE("Cannot read key for real block device %s\n", real_blk_name);
221    goto errout;
222  }
223
224  if (lseek64(fd, KEY_TO_SALT_PADDING, SEEK_CUR) == -1) {
225    SLOGE("Cannot seek to real block device salt\n");
226    goto errout;
227  }
228
229  if ( (cnt = read(fd, salt, SALT_LEN)) != SALT_LEN) {
230    SLOGE("Cannot read salt for real block device %s\n", real_blk_name);
231    goto errout;
232  }
233
234  /* Success! */
235  rc = 0;
236
237errout:
238  close(fd);
239  return rc;
240}
241
242/* Convert a binary key of specified length into an ascii hex string equivalent,
243 * without the leading 0x and with null termination
244 */
245void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
246                              char *master_key_ascii)
247{
248  unsigned int i, a;
249  unsigned char nibble;
250
251  for (i=0, a=0; i<keysize; i++, a+=2) {
252    /* For each byte, write out two ascii hex digits */
253    nibble = (master_key[i] >> 4) & 0xf;
254    master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
255
256    nibble = master_key[i] & 0xf;
257    master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
258  }
259
260  /* Add the null termination */
261  master_key_ascii[a] = '\0';
262
263}
264
265static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
266                                    char *real_blk_name, char *crypto_blk_name)
267{
268  char buffer[DM_CRYPT_BUF_SIZE];
269  char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
270  char *crypt_params;
271  struct dm_ioctl *io;
272  struct dm_target_spec *tgt;
273  unsigned int minor;
274  int fd;
275  int retval = -1;
276  char *name ="datadev"; /* FIX ME: Make me a parameter */
277
278  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
279    SLOGE("Cannot open device-mapper\n");
280    goto errout;
281  }
282
283  io = (struct dm_ioctl *) buffer;
284
285  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
286  if (ioctl(fd, DM_DEV_CREATE, io)) {
287    SLOGE("Cannot create dm-crypt device\n");
288    goto errout;
289  }
290
291  /* Get the device status, in particular, the name of it's device file */
292  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
293  if (ioctl(fd, DM_DEV_STATUS, io)) {
294    SLOGE("Cannot retrieve dm-crypt device status\n");
295    goto errout;
296  }
297  minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
298  snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
299
300  /* Load the mapping table for this device */
301  tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
302
303  ioctl_init(io, 4096, name, 0);
304  io->target_count = 1;
305  tgt->status = 0;
306  tgt->sector_start = 0;
307  tgt->length = crypt_ftr->fs_size;
308  strcpy(tgt->target_type, "crypt");
309
310  crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
311  convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
312  sprintf(crypt_params, "%s %s 0 %s 0", crypt_ftr->crypto_type_name,
313          master_key_ascii, real_blk_name);
314  crypt_params += strlen(crypt_params) + 1;
315  crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
316  tgt->next = crypt_params - buffer;
317
318  if (ioctl(fd, DM_TABLE_LOAD, io)) {
319      SLOGE("Cannot load dm-crypt mapping table.\n");
320      goto errout;
321  }
322
323  /* Resume this device to activate it */
324  ioctl_init(io, 4096, name, 0);
325
326  if (ioctl(fd, DM_DEV_SUSPEND, io)) {
327    SLOGE("Cannot resume the dm-crypt device\n");
328    goto errout;
329  }
330
331  /* We made it here with no errors.  Woot! */
332  retval = 0;
333
334errout:
335  close(fd);   /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
336
337  return retval;
338}
339
340static int delete_crypto_blk_dev(char *crypto_blkdev)
341{
342  int fd;
343  char buffer[DM_CRYPT_BUF_SIZE];
344  struct dm_ioctl *io;
345  char *name ="datadev"; /* FIX ME: Make me a paraameter */
346  int retval = -1;
347
348  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
349    SLOGE("Cannot open device-mapper\n");
350    goto errout;
351  }
352
353  io = (struct dm_ioctl *) buffer;
354
355  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
356  if (ioctl(fd, DM_DEV_REMOVE, io)) {
357    SLOGE("Cannot remove dm-crypt device\n");
358    goto errout;
359  }
360
361  /* We made it here with no errors.  Woot! */
362  retval = 0;
363
364errout:
365  close(fd);    /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
366
367  return retval;
368
369}
370
371#define HASH_COUNT 2000
372#define KEY_LEN_BYTES 16
373#define IV_LEN_BYTES 16
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 (! key_sha1_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 ( key_sha1_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    /* Also save a SHA1 of the master key so we can know if we
704     * successfully decrypted the key when we want to change the
705     * password on it.
706     */
707    SHA1(decrypted_master_key, KEY_LEN_BYTES, saved_key_sha1);
708    key_sha1_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 = 16;
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[16], decrypted_master_key[16];
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 *oldpw, char *newpw)
982{
983    struct crypt_mnt_ftr crypt_ftr;
984    unsigned char encrypted_master_key[32], decrypted_master_key[32];
985    unsigned char salt[SALT_LEN];
986    unsigned char new_key_sha1[20];
987    char real_blkdev[MAXPATHLEN];
988
989    /* This is only allowed after we've successfully decrypted the master key */
990    if (! key_sha1_saved) {
991        SLOGE("Key not saved, aborting");
992        return -1;
993    }
994
995    property_get("ro.crypto.fs_real_blkdev", real_blkdev, "");
996    if (strlen(real_blkdev) == 0) {
997        SLOGE("Can't find real blkdev");
998        return -1;
999    }
1000
1001    /* get key */
1002    if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
1003      SLOGE("Error getting crypt footer and key");
1004      return -1;
1005    }
1006
1007    /* decrypt key with old passwd */
1008    decrypt_master_key(oldpw, salt, encrypted_master_key, decrypted_master_key);
1009
1010    /* compute sha1 of decrypted key */
1011    SHA1(decrypted_master_key, KEY_LEN_BYTES, new_key_sha1);
1012
1013    /* If computed sha1 and saved sha1 match, encrypt key with new passwd */
1014    if (! memcmp(saved_key_sha1, new_key_sha1, sizeof(saved_key_sha1))) {
1015        /* they match, it's safe to re-encrypt the key */
1016        encrypt_master_key(newpw, salt, decrypted_master_key, encrypted_master_key);
1017
1018        /* save the key */
1019        put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, 0);
1020    } else {
1021        SLOGE("SHA1 mismatch");
1022        return -1;
1023    }
1024
1025    return 0;
1026}
1027
1028