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