cryptfs.c revision 73d7a02dc6e18b4c0a6f29e8f89b432c1b6cc808
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/wait.h>
25#include <sys/stat.h>
26#include <ctype.h>
27#include <fcntl.h>
28#include <unistd.h>
29#include <stdio.h>
30#include <sys/ioctl.h>
31#include <linux/dm-ioctl.h>
32#include <libgen.h>
33#include <stdlib.h>
34#include <sys/param.h>
35#include <string.h>
36#include <sys/mount.h>
37#include <openssl/evp.h>
38#include <errno.h>
39#include <ext4.h>
40#include <linux/kdev_t.h>
41#include <fs_mgr.h>
42#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
46#include "cutils/android_reboot.h"
47#include "hardware_legacy/power.h"
48#include <logwrap/logwrap.h>
49#include "VolumeManager.h"
50#include "VoldUtil.h"
51#include "crypto_scrypt.h"
52#include "ext4_utils.h"
53#include "CheckBattery.h"
54
55#include <hardware/keymaster.h>
56
57#define UNUSED __attribute__((unused))
58
59#define UNUSED __attribute__((unused))
60
61#define DM_CRYPT_BUF_SIZE 4096
62
63#define HASH_COUNT 2000
64#define KEY_LEN_BYTES 16
65#define IV_LEN_BYTES 16
66
67#define KEY_IN_FOOTER  "footer"
68
69// "default_password" encoded into hex (d=0x64 etc)
70#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
71
72#define EXT4_FS 1
73#define FAT_FS 2
74
75#define TABLE_LOAD_RETRIES 10
76
77#define RSA_DEFAULT_KEY_SIZE 2048
78#define RSA_DEFAULT_EXPONENT 0x10001
79
80char *me = "cryptfs";
81
82static unsigned char saved_master_key[KEY_LEN_BYTES];
83static char *saved_mount_point;
84static int  master_key_saved = 0;
85static struct crypt_persist_data *persist_data = NULL;
86
87static int keymaster_init(keymaster_device_t **keymaster_dev)
88{
89    int rc;
90
91    const hw_module_t* mod;
92    rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
93    if (rc) {
94        ALOGE("could not find any keystore module");
95        goto out;
96    }
97
98    rc = keymaster_open(mod, keymaster_dev);
99    if (rc) {
100        ALOGE("could not open keymaster device in %s (%s)",
101            KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
102        goto out;
103    }
104
105    return 0;
106
107out:
108    *keymaster_dev = NULL;
109    return rc;
110}
111
112/* Should we use keymaster? */
113static int keymaster_check_compatibility()
114{
115    keymaster_device_t *keymaster_dev = 0;
116    int rc = 0;
117
118    if (keymaster_init(&keymaster_dev)) {
119        SLOGE("Failed to init keymaster");
120        rc = -1;
121        goto out;
122    }
123
124    SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
125
126    if (keymaster_dev->common.module->module_api_version
127            < KEYMASTER_MODULE_API_VERSION_0_3) {
128        rc = 0;
129        goto out;
130    }
131
132    if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
133        rc = 1;
134    }
135
136out:
137    keymaster_close(keymaster_dev);
138    return rc;
139}
140
141/* Create a new keymaster key and store it in this footer */
142static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
143{
144    uint8_t* key = 0;
145    keymaster_device_t *keymaster_dev = 0;
146
147    if (keymaster_init(&keymaster_dev)) {
148        SLOGE("Failed to init keymaster");
149        return -1;
150    }
151
152    int rc = 0;
153
154    keymaster_rsa_keygen_params_t params;
155    memset(&params, '\0', sizeof(params));
156    params.public_exponent = RSA_DEFAULT_EXPONENT;
157    params.modulus_size = RSA_DEFAULT_KEY_SIZE;
158
159    size_t key_size;
160    if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
161                                        &key, &key_size)) {
162        SLOGE("Failed to generate keypair");
163        rc = -1;
164        goto out;
165    }
166
167    if (key_size > KEYMASTER_BLOB_SIZE) {
168        SLOGE("Keymaster key too large for crypto footer");
169        rc = -1;
170        goto out;
171    }
172
173    memcpy(ftr->keymaster_blob, key, key_size);
174    ftr->keymaster_blob_size = key_size;
175
176out:
177    keymaster_close(keymaster_dev);
178    free(key);
179    return rc;
180}
181
182/* This signs the given object using the keymaster key */
183static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
184                                 const unsigned char *object,
185                                 const size_t object_size,
186                                 unsigned char **signature,
187                                 size_t *signature_size)
188{
189    int rc = 0;
190    keymaster_device_t *keymaster_dev = 0;
191    if (keymaster_init(&keymaster_dev)) {
192        SLOGE("Failed to init keymaster");
193        return -1;
194    }
195
196    /* We currently set the digest type to DIGEST_NONE because it's the
197     * only supported value for keymaster. A similar issue exists with
198     * PADDING_NONE. Long term both of these should likely change.
199     */
200    keymaster_rsa_sign_params_t params;
201    params.digest_type = DIGEST_NONE;
202    params.padding_type = PADDING_NONE;
203
204    rc = keymaster_dev->sign_data(keymaster_dev,
205                                  &params,
206                                  ftr->keymaster_blob,
207                                  ftr->keymaster_blob_size,
208                                  object,
209                                  object_size,
210                                  signature,
211                                  signature_size);
212
213    keymaster_close(keymaster_dev);
214    return rc;
215}
216
217/* Store password when userdata is successfully decrypted and mounted.
218 * Cleared by cryptfs_clear_password
219 *
220 * To avoid a double prompt at boot, we need to store the CryptKeeper
221 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
222 * Since the entire framework is torn down and rebuilt after encryption,
223 * we have to use a daemon or similar to store the password. Since vold
224 * is secured against IPC except from system processes, it seems a reasonable
225 * place to store this.
226 *
227 * password should be cleared once it has been used.
228 *
229 * password is aged out after password_max_age_seconds seconds.
230 */
231static char* password = 0;
232static int password_expiry_time = 0;
233static const int password_max_age_seconds = 60;
234
235extern struct fstab *fstab;
236
237enum RebootType {reboot, recovery, shutdown};
238static void cryptfs_reboot(enum RebootType rt)
239{
240  switch(rt) {
241      case reboot:
242          property_set(ANDROID_RB_PROPERTY, "reboot");
243          break;
244
245      case recovery:
246          property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
247          break;
248
249      case shutdown:
250          property_set(ANDROID_RB_PROPERTY, "shutdown");
251          break;
252    }
253
254    sleep(20);
255
256    /* Shouldn't get here, reboot should happen before sleep times out */
257    return;
258}
259
260static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
261{
262    memset(io, 0, dataSize);
263    io->data_size = dataSize;
264    io->data_start = sizeof(struct dm_ioctl);
265    io->version[0] = 4;
266    io->version[1] = 0;
267    io->version[2] = 0;
268    io->flags = flags;
269    if (name) {
270        strncpy(io->name, name, sizeof(io->name));
271    }
272}
273
274/**
275 * Gets the default device scrypt parameters for key derivation time tuning.
276 * The parameters should lead to about one second derivation time for the
277 * given device.
278 */
279static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
280    const int default_params[] = SCRYPT_DEFAULTS;
281    int params[] = SCRYPT_DEFAULTS;
282    char paramstr[PROPERTY_VALUE_MAX];
283    char *token;
284    char *saveptr;
285    int i;
286
287    property_get(SCRYPT_PROP, paramstr, "");
288    if (paramstr[0] != '\0') {
289        /*
290         * The token we're looking for should be three integers separated by
291         * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
292         */
293        for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
294                token != NULL && i < 3;
295                i++, token = strtok_r(NULL, ":", &saveptr)) {
296            char *endptr;
297            params[i] = strtol(token, &endptr, 10);
298
299            /*
300             * Check that there was a valid number and it's 8-bit. If not,
301             * break out and the end check will take the default values.
302             */
303            if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
304                break;
305            }
306        }
307
308        /*
309         * If there were not enough tokens or a token was malformed (not an
310         * integer), it will end up here and the default parameters can be
311         * taken.
312         */
313        if ((i != 3) || (token != NULL)) {
314            SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
315            memcpy(params, default_params, sizeof(params));
316        }
317    }
318
319    ftr->N_factor = params[0];
320    ftr->r_factor = params[1];
321    ftr->p_factor = params[2];
322}
323
324static unsigned int get_fs_size(char *dev)
325{
326    int fd, block_size;
327    struct ext4_super_block sb;
328    off64_t len;
329
330    if ((fd = open(dev, O_RDONLY)) < 0) {
331        SLOGE("Cannot open device to get filesystem size ");
332        return 0;
333    }
334
335    if (lseek64(fd, 1024, SEEK_SET) < 0) {
336        SLOGE("Cannot seek to superblock");
337        return 0;
338    }
339
340    if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
341        SLOGE("Cannot read superblock");
342        return 0;
343    }
344
345    close(fd);
346
347    block_size = 1024 << sb.s_log_block_size;
348    /* compute length in bytes */
349    len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
350
351    /* return length in sectors */
352    return (unsigned int) (len / 512);
353}
354
355static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
356{
357  static int cached_data = 0;
358  static off64_t cached_off = 0;
359  static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
360  int fd;
361  char key_loc[PROPERTY_VALUE_MAX];
362  char real_blkdev[PROPERTY_VALUE_MAX];
363  unsigned int nr_sec;
364  int rc = -1;
365
366  if (!cached_data) {
367    fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
368
369    if (!strcmp(key_loc, KEY_IN_FOOTER)) {
370      if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
371        SLOGE("Cannot open real block device %s\n", real_blkdev);
372        return -1;
373      }
374
375      if ((nr_sec = get_blkdev_size(fd))) {
376        /* If it's an encrypted Android partition, the last 16 Kbytes contain the
377         * encryption info footer and key, and plenty of bytes to spare for future
378         * growth.
379         */
380        strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
381        cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
382        cached_data = 1;
383      } else {
384        SLOGE("Cannot get size of block device %s\n", real_blkdev);
385      }
386      close(fd);
387    } else {
388      strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
389      cached_off = 0;
390      cached_data = 1;
391    }
392  }
393
394  if (cached_data) {
395    if (metadata_fname) {
396        *metadata_fname = cached_metadata_fname;
397    }
398    if (off) {
399        *off = cached_off;
400    }
401    rc = 0;
402  }
403
404  return rc;
405}
406
407/* key or salt can be NULL, in which case just skip writing that value.  Useful to
408 * update the failed mount count but not change the key.
409 */
410static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
411{
412  int fd;
413  unsigned int nr_sec, cnt;
414  /* starting_off is set to the SEEK_SET offset
415   * where the crypto structure starts
416   */
417  off64_t starting_off;
418  int rc = -1;
419  char *fname = NULL;
420  struct stat statbuf;
421
422  if (get_crypt_ftr_info(&fname, &starting_off)) {
423    SLOGE("Unable to get crypt_ftr_info\n");
424    return -1;
425  }
426  if (fname[0] != '/') {
427    SLOGE("Unexpected value for crypto key location\n");
428    return -1;
429  }
430  if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
431    SLOGE("Cannot open footer file %s for put\n", fname);
432    return -1;
433  }
434
435  /* Seek to the start of the crypt footer */
436  if (lseek64(fd, starting_off, SEEK_SET) == -1) {
437    SLOGE("Cannot seek to real block device footer\n");
438    goto errout;
439  }
440
441  if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
442    SLOGE("Cannot write real block device footer\n");
443    goto errout;
444  }
445
446  fstat(fd, &statbuf);
447  /* If the keys are kept on a raw block device, do not try to truncate it. */
448  if (S_ISREG(statbuf.st_mode)) {
449    if (ftruncate(fd, 0x4000)) {
450      SLOGE("Cannot set footer file size\n");
451      goto errout;
452    }
453  }
454
455  /* Success! */
456  rc = 0;
457
458errout:
459  close(fd);
460  return rc;
461
462}
463
464static inline int unix_read(int  fd, void*  buff, int  len)
465{
466    return TEMP_FAILURE_RETRY(read(fd, buff, len));
467}
468
469static inline int unix_write(int  fd, const void*  buff, int  len)
470{
471    return TEMP_FAILURE_RETRY(write(fd, buff, len));
472}
473
474static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
475{
476    memset(pdata, 0, len);
477    pdata->persist_magic = PERSIST_DATA_MAGIC;
478    pdata->persist_valid_entries = 0;
479}
480
481/* A routine to update the passed in crypt_ftr to the lastest version.
482 * fd is open read/write on the device that holds the crypto footer and persistent
483 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
484 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
485 */
486static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
487{
488    int orig_major = crypt_ftr->major_version;
489    int orig_minor = crypt_ftr->minor_version;
490
491    if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
492        struct crypt_persist_data *pdata;
493        off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
494
495        SLOGW("upgrading crypto footer to 1.1");
496
497        pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
498        if (pdata == NULL) {
499            SLOGE("Cannot allocate persisent data\n");
500            return;
501        }
502        memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
503
504        /* Need to initialize the persistent data area */
505        if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
506            SLOGE("Cannot seek to persisent data offset\n");
507            return;
508        }
509        /* Write all zeros to the first copy, making it invalid */
510        unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
511
512        /* Write a valid but empty structure to the second copy */
513        init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
514        unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
515
516        /* Update the footer */
517        crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
518        crypt_ftr->persist_data_offset[0] = pdata_offset;
519        crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
520        crypt_ftr->minor_version = 1;
521    }
522
523    if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
524        SLOGW("upgrading crypto footer to 1.2");
525        /* But keep the old kdf_type.
526         * It will get updated later to KDF_SCRYPT after the password has been verified.
527         */
528        crypt_ftr->kdf_type = KDF_PBKDF2;
529        get_device_scrypt_params(crypt_ftr);
530        crypt_ftr->minor_version = 2;
531    }
532
533    if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
534        SLOGW("upgrading crypto footer to 1.3");
535        crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
536        crypt_ftr->minor_version = 3;
537    }
538
539    if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
540        if (lseek64(fd, offset, SEEK_SET) == -1) {
541            SLOGE("Cannot seek to crypt footer\n");
542            return;
543        }
544        unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
545    }
546}
547
548
549static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
550{
551  int fd;
552  unsigned int nr_sec, cnt;
553  off64_t starting_off;
554  int rc = -1;
555  char *fname = NULL;
556  struct stat statbuf;
557
558  if (get_crypt_ftr_info(&fname, &starting_off)) {
559    SLOGE("Unable to get crypt_ftr_info\n");
560    return -1;
561  }
562  if (fname[0] != '/') {
563    SLOGE("Unexpected value for crypto key location\n");
564    return -1;
565  }
566  if ( (fd = open(fname, O_RDWR)) < 0) {
567    SLOGE("Cannot open footer file %s for get\n", fname);
568    return -1;
569  }
570
571  /* Make sure it's 16 Kbytes in length */
572  fstat(fd, &statbuf);
573  if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
574    SLOGE("footer file %s is not the expected size!\n", fname);
575    goto errout;
576  }
577
578  /* Seek to the start of the crypt footer */
579  if (lseek64(fd, starting_off, SEEK_SET) == -1) {
580    SLOGE("Cannot seek to real block device footer\n");
581    goto errout;
582  }
583
584  if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
585    SLOGE("Cannot read real block device footer\n");
586    goto errout;
587  }
588
589  if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
590    SLOGE("Bad magic for real block device %s\n", fname);
591    goto errout;
592  }
593
594  if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
595    SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
596          crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
597    goto errout;
598  }
599
600  if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
601    SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
602          crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
603  }
604
605  /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
606   * copy on disk before returning.
607   */
608  if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
609    upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
610  }
611
612  /* Success! */
613  rc = 0;
614
615errout:
616  close(fd);
617  return rc;
618}
619
620static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
621{
622    if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
623        crypt_ftr->persist_data_offset[1]) {
624        SLOGE("Crypt_ftr persist data regions overlap");
625        return -1;
626    }
627
628    if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
629        SLOGE("Crypt_ftr persist data region 0 starts after region 1");
630        return -1;
631    }
632
633    if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
634        (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
635        CRYPT_FOOTER_OFFSET) {
636        SLOGE("Persistent data extends past crypto footer");
637        return -1;
638    }
639
640    return 0;
641}
642
643static int load_persistent_data(void)
644{
645    struct crypt_mnt_ftr crypt_ftr;
646    struct crypt_persist_data *pdata = NULL;
647    char encrypted_state[PROPERTY_VALUE_MAX];
648    char *fname;
649    int found = 0;
650    int fd;
651    int ret;
652    int i;
653
654    if (persist_data) {
655        /* Nothing to do, we've already loaded or initialized it */
656        return 0;
657    }
658
659
660    /* If not encrypted, just allocate an empty table and initialize it */
661    property_get("ro.crypto.state", encrypted_state, "");
662    if (strcmp(encrypted_state, "encrypted") ) {
663        pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
664        if (pdata) {
665            init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
666            persist_data = pdata;
667            return 0;
668        }
669        return -1;
670    }
671
672    if(get_crypt_ftr_and_key(&crypt_ftr)) {
673        return -1;
674    }
675
676    if ((crypt_ftr.major_version < 1)
677        || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
678        SLOGE("Crypt_ftr version doesn't support persistent data");
679        return -1;
680    }
681
682    if (get_crypt_ftr_info(&fname, NULL)) {
683        return -1;
684    }
685
686    ret = validate_persistent_data_storage(&crypt_ftr);
687    if (ret) {
688        return -1;
689    }
690
691    fd = open(fname, O_RDONLY);
692    if (fd < 0) {
693        SLOGE("Cannot open %s metadata file", fname);
694        return -1;
695    }
696
697    if (persist_data == NULL) {
698        pdata = malloc(crypt_ftr.persist_data_size);
699        if (pdata == NULL) {
700            SLOGE("Cannot allocate memory for persistent data");
701            goto err;
702        }
703    }
704
705    for (i = 0; i < 2; i++) {
706        if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
707            SLOGE("Cannot seek to read persistent data on %s", fname);
708            goto err2;
709        }
710        if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
711            SLOGE("Error reading persistent data on iteration %d", i);
712            goto err2;
713        }
714        if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
715            found = 1;
716            break;
717        }
718    }
719
720    if (!found) {
721        SLOGI("Could not find valid persistent data, creating");
722        init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
723    }
724
725    /* Success */
726    persist_data = pdata;
727    close(fd);
728    return 0;
729
730err2:
731    free(pdata);
732
733err:
734    close(fd);
735    return -1;
736}
737
738static int save_persistent_data(void)
739{
740    struct crypt_mnt_ftr crypt_ftr;
741    struct crypt_persist_data *pdata;
742    char *fname;
743    off64_t write_offset;
744    off64_t erase_offset;
745    int found = 0;
746    int fd;
747    int ret;
748
749    if (persist_data == NULL) {
750        SLOGE("No persistent data to save");
751        return -1;
752    }
753
754    if(get_crypt_ftr_and_key(&crypt_ftr)) {
755        return -1;
756    }
757
758    if ((crypt_ftr.major_version < 1)
759        || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
760        SLOGE("Crypt_ftr version doesn't support persistent data");
761        return -1;
762    }
763
764    ret = validate_persistent_data_storage(&crypt_ftr);
765    if (ret) {
766        return -1;
767    }
768
769    if (get_crypt_ftr_info(&fname, NULL)) {
770        return -1;
771    }
772
773    fd = open(fname, O_RDWR);
774    if (fd < 0) {
775        SLOGE("Cannot open %s metadata file", fname);
776        return -1;
777    }
778
779    pdata = malloc(crypt_ftr.persist_data_size);
780    if (pdata == NULL) {
781        SLOGE("Cannot allocate persistant data");
782        goto err;
783    }
784
785    if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
786        SLOGE("Cannot seek to read persistent data on %s", fname);
787        goto err2;
788    }
789
790    if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
791            SLOGE("Error reading persistent data before save");
792            goto err2;
793    }
794
795    if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
796        /* The first copy is the curent valid copy, so write to
797         * the second copy and erase this one */
798       write_offset = crypt_ftr.persist_data_offset[1];
799       erase_offset = crypt_ftr.persist_data_offset[0];
800    } else {
801        /* The second copy must be the valid copy, so write to
802         * the first copy, and erase the second */
803       write_offset = crypt_ftr.persist_data_offset[0];
804       erase_offset = crypt_ftr.persist_data_offset[1];
805    }
806
807    /* Write the new copy first, if successful, then erase the old copy */
808    if (lseek(fd, write_offset, SEEK_SET) < 0) {
809        SLOGE("Cannot seek to write persistent data");
810        goto err2;
811    }
812    if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
813        (int) crypt_ftr.persist_data_size) {
814        if (lseek(fd, erase_offset, SEEK_SET) < 0) {
815            SLOGE("Cannot seek to erase previous persistent data");
816            goto err2;
817        }
818        fsync(fd);
819        memset(pdata, 0, crypt_ftr.persist_data_size);
820        if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
821            (int) crypt_ftr.persist_data_size) {
822            SLOGE("Cannot write to erase previous persistent data");
823            goto err2;
824        }
825        fsync(fd);
826    } else {
827        SLOGE("Cannot write to save persistent data");
828        goto err2;
829    }
830
831    /* Success */
832    free(pdata);
833    close(fd);
834    return 0;
835
836err2:
837    free(pdata);
838err:
839    close(fd);
840    return -1;
841}
842
843static int hexdigit (char c)
844{
845    if (c >= '0' && c <= '9') return c - '0';
846    c = tolower(c);
847    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
848    return -1;
849}
850
851static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
852                                               unsigned int* out_keysize)
853{
854    unsigned int i;
855    *out_keysize = 0;
856
857    size_t size = strlen (master_key_ascii);
858    if (size % 2) {
859        SLOGE("Trying to convert ascii string of odd length");
860        return NULL;
861    }
862
863    unsigned char* master_key = (unsigned char*) malloc(size / 2);
864    if (master_key == 0) {
865        SLOGE("Cannot allocate");
866        return NULL;
867    }
868
869    for (i = 0; i < size; i += 2) {
870        int high_nibble = hexdigit (master_key_ascii[i]);
871        int low_nibble = hexdigit (master_key_ascii[i + 1]);
872
873        if(high_nibble < 0 || low_nibble < 0) {
874            SLOGE("Invalid hex string");
875            free (master_key);
876            return NULL;
877        }
878
879        master_key[*out_keysize] = high_nibble * 16 + low_nibble;
880        (*out_keysize)++;
881    }
882
883    return master_key;
884}
885
886/* Convert a binary key of specified length into an ascii hex string equivalent,
887 * without the leading 0x and with null termination
888 */
889static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
890                              char *master_key_ascii)
891{
892  unsigned int i, a;
893  unsigned char nibble;
894
895  for (i=0, a=0; i<keysize; i++, a+=2) {
896    /* For each byte, write out two ascii hex digits */
897    nibble = (master_key[i] >> 4) & 0xf;
898    master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
899
900    nibble = master_key[i] & 0xf;
901    master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
902  }
903
904  /* Add the null termination */
905  master_key_ascii[a] = '\0';
906
907}
908
909static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
910                                     char *real_blk_name, const char *name, int fd,
911                                     char *extra_params)
912{
913  char buffer[DM_CRYPT_BUF_SIZE];
914  struct dm_ioctl *io;
915  struct dm_target_spec *tgt;
916  char *crypt_params;
917  char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
918  int i;
919
920  io = (struct dm_ioctl *) buffer;
921
922  /* Load the mapping table for this device */
923  tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
924
925  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
926  io->target_count = 1;
927  tgt->status = 0;
928  tgt->sector_start = 0;
929  tgt->length = crypt_ftr->fs_size;
930  strcpy(tgt->target_type, "crypt");
931
932  crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
933  convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
934  sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
935          master_key_ascii, real_blk_name, extra_params);
936  crypt_params += strlen(crypt_params) + 1;
937  crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
938  tgt->next = crypt_params - buffer;
939
940  for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
941    if (! ioctl(fd, DM_TABLE_LOAD, io)) {
942      break;
943    }
944    usleep(500000);
945  }
946
947  if (i == TABLE_LOAD_RETRIES) {
948    /* We failed to load the table, return an error */
949    return -1;
950  } else {
951    return i + 1;
952  }
953}
954
955
956static int get_dm_crypt_version(int fd, const char *name,  int *version)
957{
958    char buffer[DM_CRYPT_BUF_SIZE];
959    struct dm_ioctl *io;
960    struct dm_target_versions *v;
961    int i;
962
963    io = (struct dm_ioctl *) buffer;
964
965    ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
966
967    if (ioctl(fd, DM_LIST_VERSIONS, io)) {
968        return -1;
969    }
970
971    /* Iterate over the returned versions, looking for name of "crypt".
972     * When found, get and return the version.
973     */
974    v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
975    while (v->next) {
976        if (! strcmp(v->name, "crypt")) {
977            /* We found the crypt driver, return the version, and get out */
978            version[0] = v->version[0];
979            version[1] = v->version[1];
980            version[2] = v->version[2];
981            return 0;
982        }
983        v = (struct dm_target_versions *)(((char *)v) + v->next);
984    }
985
986    return -1;
987}
988
989static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
990                                    char *real_blk_name, char *crypto_blk_name, const char *name)
991{
992  char buffer[DM_CRYPT_BUF_SIZE];
993  char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
994  char *crypt_params;
995  struct dm_ioctl *io;
996  struct dm_target_spec *tgt;
997  unsigned int minor;
998  int fd;
999  int i;
1000  int retval = -1;
1001  int version[3];
1002  char *extra_params;
1003  int load_count;
1004
1005  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1006    SLOGE("Cannot open device-mapper\n");
1007    goto errout;
1008  }
1009
1010  io = (struct dm_ioctl *) buffer;
1011
1012  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1013  if (ioctl(fd, DM_DEV_CREATE, io)) {
1014    SLOGE("Cannot create dm-crypt device\n");
1015    goto errout;
1016  }
1017
1018  /* Get the device status, in particular, the name of it's device file */
1019  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1020  if (ioctl(fd, DM_DEV_STATUS, io)) {
1021    SLOGE("Cannot retrieve dm-crypt device status\n");
1022    goto errout;
1023  }
1024  minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1025  snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1026
1027  extra_params = "";
1028  if (! get_dm_crypt_version(fd, name, version)) {
1029      /* Support for allow_discards was added in version 1.11.0 */
1030      if ((version[0] >= 2) ||
1031          ((version[0] == 1) && (version[1] >= 11))) {
1032          extra_params = "1 allow_discards";
1033          SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1034      }
1035  }
1036
1037  load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1038                                         fd, extra_params);
1039  if (load_count < 0) {
1040      SLOGE("Cannot load dm-crypt mapping table.\n");
1041      goto errout;
1042  } else if (load_count > 1) {
1043      SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1044  }
1045
1046  /* Resume this device to activate it */
1047  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1048
1049  if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1050    SLOGE("Cannot resume the dm-crypt device\n");
1051    goto errout;
1052  }
1053
1054  /* We made it here with no errors.  Woot! */
1055  retval = 0;
1056
1057errout:
1058  close(fd);   /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1059
1060  return retval;
1061}
1062
1063static int delete_crypto_blk_dev(char *name)
1064{
1065  int fd;
1066  char buffer[DM_CRYPT_BUF_SIZE];
1067  struct dm_ioctl *io;
1068  int retval = -1;
1069
1070  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1071    SLOGE("Cannot open device-mapper\n");
1072    goto errout;
1073  }
1074
1075  io = (struct dm_ioctl *) buffer;
1076
1077  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1078  if (ioctl(fd, DM_DEV_REMOVE, io)) {
1079    SLOGE("Cannot remove dm-crypt device\n");
1080    goto errout;
1081  }
1082
1083  /* We made it here with no errors.  Woot! */
1084  retval = 0;
1085
1086errout:
1087  close(fd);    /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1088
1089  return retval;
1090
1091}
1092
1093static int pbkdf2(const char *passwd, const unsigned char *salt,
1094                  unsigned char *ikey, void *params UNUSED)
1095{
1096    SLOGI("Using pbkdf2 for cryptfs KDF");
1097
1098    /* Turn the password into a key and IV that can decrypt the master key */
1099    unsigned int keysize;
1100    char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1101    if (!master_key) return -1;
1102    PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
1103                           HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
1104
1105    memset(master_key, 0, keysize);
1106    free (master_key);
1107    return 0;
1108}
1109
1110static int scrypt(const char *passwd, const unsigned char *salt,
1111                  unsigned char *ikey, void *params)
1112{
1113    SLOGI("Using scrypt for cryptfs KDF");
1114
1115    struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1116
1117    int N = 1 << ftr->N_factor;
1118    int r = 1 << ftr->r_factor;
1119    int p = 1 << ftr->p_factor;
1120
1121    /* Turn the password into a key and IV that can decrypt the master key */
1122    unsigned int keysize;
1123    unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1124    if (!master_key) return -1;
1125    crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
1126            KEY_LEN_BYTES + IV_LEN_BYTES);
1127
1128    memset(master_key, 0, keysize);
1129    free (master_key);
1130    return 0;
1131}
1132
1133static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1134                            unsigned char *ikey, void *params)
1135{
1136    SLOGI("Using scrypt with keymaster for cryptfs KDF");
1137
1138    int rc;
1139    unsigned int key_size;
1140    size_t signature_size;
1141    unsigned char* signature;
1142    struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1143
1144    int N = 1 << ftr->N_factor;
1145    int r = 1 << ftr->r_factor;
1146    int p = 1 << ftr->p_factor;
1147
1148    unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1149    if (!master_key) {
1150        SLOGE("Failed to convert passwd from hex");
1151        return -1;
1152    }
1153
1154    rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1155                       N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1156    memset(master_key, 0, key_size);
1157    free(master_key);
1158
1159    if (rc) {
1160        SLOGE("scrypt failed");
1161        return -1;
1162    }
1163
1164    if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1165                 &signature, &signature_size)) {
1166        SLOGE("Signing failed");
1167        return -1;
1168    }
1169
1170    rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1171                       N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1172    free(signature);
1173
1174    if (rc) {
1175        SLOGE("scrypt failed");
1176        return -1;
1177    }
1178
1179    return 0;
1180}
1181
1182static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1183                              const unsigned char *decrypted_master_key,
1184                              unsigned char *encrypted_master_key,
1185                              struct crypt_mnt_ftr *crypt_ftr)
1186{
1187    unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1188    EVP_CIPHER_CTX e_ctx;
1189    int encrypted_len, final_len;
1190
1191    /* Turn the password into a key and IV that can decrypt the master key */
1192    get_device_scrypt_params(crypt_ftr);
1193
1194    switch (crypt_ftr->kdf_type) {
1195    case KDF_SCRYPT_KEYMASTER:
1196        if (keymaster_create_key(crypt_ftr)) {
1197            SLOGE("keymaster_create_key failed");
1198            return -1;
1199        }
1200
1201        if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1202            SLOGE("scrypt failed");
1203            return -1;
1204        }
1205        break;
1206
1207    case KDF_SCRYPT:
1208        if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1209            SLOGE("scrypt failed");
1210            return -1;
1211        }
1212        break;
1213
1214    default:
1215        SLOGE("Invalid kdf_type");
1216        return -1;
1217    }
1218
1219    /* Initialize the decryption engine */
1220    if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1221        SLOGE("EVP_EncryptInit failed\n");
1222        return -1;
1223    }
1224    EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
1225
1226    /* Encrypt the master key */
1227    if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1228                              decrypted_master_key, KEY_LEN_BYTES)) {
1229        SLOGE("EVP_EncryptUpdate failed\n");
1230        return -1;
1231    }
1232    if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
1233        SLOGE("EVP_EncryptFinal failed\n");
1234        return -1;
1235    }
1236
1237    if (encrypted_len + final_len != KEY_LEN_BYTES) {
1238        SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1239        return -1;
1240    }
1241
1242    return 0;
1243}
1244
1245static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
1246                              unsigned char *encrypted_master_key,
1247                              unsigned char *decrypted_master_key,
1248                              kdf_func kdf, void *kdf_params)
1249{
1250  unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1251  EVP_CIPHER_CTX d_ctx;
1252  int decrypted_len, final_len;
1253
1254  /* Turn the password into a key and IV that can decrypt the master key */
1255  if (kdf(passwd, salt, ikey, kdf_params)) {
1256    SLOGE("kdf failed");
1257    return -1;
1258  }
1259
1260  /* Initialize the decryption engine */
1261  if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1262    return -1;
1263  }
1264  EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1265  /* Decrypt the master key */
1266  if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1267                            encrypted_master_key, KEY_LEN_BYTES)) {
1268    return -1;
1269  }
1270  if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1271    return -1;
1272  }
1273
1274  if (decrypted_len + final_len != KEY_LEN_BYTES) {
1275    return -1;
1276  } else {
1277    return 0;
1278  }
1279}
1280
1281static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
1282{
1283    if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1284        *kdf = scrypt_keymaster;
1285        *kdf_params = ftr;
1286    } else if (ftr->kdf_type == KDF_SCRYPT) {
1287        *kdf = scrypt;
1288        *kdf_params = ftr;
1289    } else {
1290        *kdf = pbkdf2;
1291        *kdf_params = NULL;
1292    }
1293}
1294
1295static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
1296        struct crypt_mnt_ftr *crypt_ftr)
1297{
1298    kdf_func kdf;
1299    void *kdf_params;
1300    int ret;
1301
1302    get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1303    ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
1304            kdf_params);
1305    if (ret != 0) {
1306        SLOGW("failure decrypting master key");
1307    }
1308
1309    return ret;
1310}
1311
1312static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1313        struct crypt_mnt_ftr *crypt_ftr) {
1314    int fd;
1315    unsigned char key_buf[KEY_LEN_BYTES];
1316    EVP_CIPHER_CTX e_ctx;
1317    int encrypted_len, final_len;
1318
1319    /* Get some random bits for a key */
1320    fd = open("/dev/urandom", O_RDONLY);
1321    read(fd, key_buf, sizeof(key_buf));
1322    read(fd, salt, SALT_LEN);
1323    close(fd);
1324
1325    /* Now encrypt it with the password */
1326    return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
1327}
1328
1329static int wait_and_unmount(char *mountpoint)
1330{
1331    int i, rc;
1332#define WAIT_UNMOUNT_COUNT 20
1333
1334    /*  Now umount the tmpfs filesystem */
1335    for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1336        if (umount(mountpoint)) {
1337            if (errno == EINVAL) {
1338                /* EINVAL is returned if the directory is not a mountpoint,
1339                 * i.e. there is no filesystem mounted there.  So just get out.
1340                 */
1341                break;
1342            }
1343            sleep(1);
1344            i++;
1345        } else {
1346          break;
1347        }
1348    }
1349
1350    if (i < WAIT_UNMOUNT_COUNT) {
1351      SLOGD("unmounting %s succeeded\n", mountpoint);
1352      rc = 0;
1353    } else {
1354      SLOGE("unmounting %s failed\n", mountpoint);
1355      rc = -1;
1356    }
1357
1358    return rc;
1359}
1360
1361#define DATA_PREP_TIMEOUT 200
1362static int prep_data_fs(void)
1363{
1364    int i;
1365
1366    /* Do the prep of the /data filesystem */
1367    property_set("vold.post_fs_data_done", "0");
1368    property_set("vold.decrypt", "trigger_post_fs_data");
1369    SLOGD("Just triggered post_fs_data\n");
1370
1371    /* Wait a max of 50 seconds, hopefully it takes much less */
1372    for (i=0; i<DATA_PREP_TIMEOUT; i++) {
1373        char p[PROPERTY_VALUE_MAX];
1374
1375        property_get("vold.post_fs_data_done", p, "0");
1376        if (*p == '1') {
1377            break;
1378        } else {
1379            usleep(250000);
1380        }
1381    }
1382    if (i == DATA_PREP_TIMEOUT) {
1383        /* Ugh, we failed to prep /data in time.  Bail. */
1384        SLOGE("post_fs_data timed out!\n");
1385        return -1;
1386    } else {
1387        SLOGD("post_fs_data done\n");
1388        return 0;
1389    }
1390}
1391
1392static int cryptfs_restart_internal(int restart_main)
1393{
1394    char fs_type[32];
1395    char real_blkdev[MAXPATHLEN];
1396    char crypto_blkdev[MAXPATHLEN];
1397    char fs_options[256];
1398    unsigned long mnt_flags;
1399    struct stat statbuf;
1400    int rc = -1, i;
1401    static int restart_successful = 0;
1402
1403    /* Validate that it's OK to call this routine */
1404    if (! master_key_saved) {
1405        SLOGE("Encrypted filesystem not validated, aborting");
1406        return -1;
1407    }
1408
1409    if (restart_successful) {
1410        SLOGE("System already restarted with encrypted disk, aborting");
1411        return -1;
1412    }
1413
1414    if (restart_main) {
1415        /* Here is where we shut down the framework.  The init scripts
1416         * start all services in one of three classes: core, main or late_start.
1417         * On boot, we start core and main.  Now, we stop main, but not core,
1418         * as core includes vold and a few other really important things that
1419         * we need to keep running.  Once main has stopped, we should be able
1420         * to umount the tmpfs /data, then mount the encrypted /data.
1421         * We then restart the class main, and also the class late_start.
1422         * At the moment, I've only put a few things in late_start that I know
1423         * are not needed to bring up the framework, and that also cause problems
1424         * with unmounting the tmpfs /data, but I hope to add add more services
1425         * to the late_start class as we optimize this to decrease the delay
1426         * till the user is asked for the password to the filesystem.
1427         */
1428
1429        /* The init files are setup to stop the class main when vold.decrypt is
1430         * set to trigger_reset_main.
1431         */
1432        property_set("vold.decrypt", "trigger_reset_main");
1433        SLOGD("Just asked init to shut down class main\n");
1434
1435        /* Ugh, shutting down the framework is not synchronous, so until it
1436         * can be fixed, this horrible hack will wait a moment for it all to
1437         * shut down before proceeding.  Without it, some devices cannot
1438         * restart the graphics services.
1439         */
1440        sleep(2);
1441    }
1442
1443    /* Now that the framework is shutdown, we should be able to umount()
1444     * the tmpfs filesystem, and mount the real one.
1445     */
1446
1447    property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1448    if (strlen(crypto_blkdev) == 0) {
1449        SLOGE("fs_crypto_blkdev not set\n");
1450        return -1;
1451    }
1452
1453    if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1454        /* If ro.crypto.readonly is set to 1, mount the decrypted
1455         * filesystem readonly.  This is used when /data is mounted by
1456         * recovery mode.
1457         */
1458        char ro_prop[PROPERTY_VALUE_MAX];
1459        property_get("ro.crypto.readonly", ro_prop, "");
1460        if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1461            struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1462            rec->flags |= MS_RDONLY;
1463        }
1464
1465        /* If that succeeded, then mount the decrypted filesystem */
1466        fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
1467
1468        property_set("vold.decrypt", "trigger_load_persist_props");
1469        /* Create necessary paths on /data */
1470        if (prep_data_fs()) {
1471            return -1;
1472        }
1473
1474        /* startup service classes main and late_start */
1475        property_set("vold.decrypt", "trigger_restart_framework");
1476        SLOGD("Just triggered restart_framework\n");
1477
1478        /* Give it a few moments to get started */
1479        sleep(1);
1480    }
1481
1482    if (rc == 0) {
1483        restart_successful = 1;
1484    }
1485
1486    return rc;
1487}
1488
1489int cryptfs_restart(void)
1490{
1491    /* Call internal implementation forcing a restart of main service group */
1492    return cryptfs_restart_internal(1);
1493}
1494
1495static int do_crypto_complete(char *mount_point UNUSED)
1496{
1497  struct crypt_mnt_ftr crypt_ftr;
1498  char encrypted_state[PROPERTY_VALUE_MAX];
1499  char key_loc[PROPERTY_VALUE_MAX];
1500
1501  property_get("ro.crypto.state", encrypted_state, "");
1502  if (strcmp(encrypted_state, "encrypted") ) {
1503    SLOGE("not running with encryption, aborting");
1504    return 1;
1505  }
1506
1507  if (get_crypt_ftr_and_key(&crypt_ftr)) {
1508    fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
1509
1510    /*
1511     * Only report this error if key_loc is a file and it exists.
1512     * If the device was never encrypted, and /data is not mountable for
1513     * some reason, returning 1 should prevent the UI from presenting the
1514     * a "enter password" screen, or worse, a "press button to wipe the
1515     * device" screen.
1516     */
1517    if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1518      SLOGE("master key file does not exist, aborting");
1519      return 1;
1520    } else {
1521      SLOGE("Error getting crypt footer and key\n");
1522      return -1;
1523    }
1524  }
1525
1526  if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1527    SLOGE("Encryption process didn't finish successfully\n");
1528    return -2;  /* -2 is the clue to the UI that there is no usable data on the disk,
1529                 * and give the user an option to wipe the disk */
1530  }
1531
1532  /* We passed the test! We shall diminish, and return to the west */
1533  return 0;
1534}
1535
1536static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1537                                   char *passwd, char *mount_point, char *label)
1538{
1539  /* Allocate enough space for a 256 bit key, but we may use less */
1540  unsigned char decrypted_master_key[32];
1541  char crypto_blkdev[MAXPATHLEN];
1542  char real_blkdev[MAXPATHLEN];
1543  char tmp_mount_point[64];
1544  unsigned int orig_failed_decrypt_count;
1545  int rc;
1546  kdf_func kdf;
1547  void *kdf_params;
1548  int use_keymaster = 0;
1549  int upgrade = 0;
1550
1551  SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1552  orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
1553
1554  if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1555    if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
1556      SLOGE("Failed to decrypt master key\n");
1557      return -1;
1558    }
1559  }
1560
1561  fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1562
1563  if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1564                            real_blkdev, crypto_blkdev, label)) {
1565    SLOGE("Error creating decrypted block device\n");
1566    return -1;
1567  }
1568
1569  /* If init detects an encrypted filesystem, it writes a file for each such
1570   * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1571   * files and passes that data to me */
1572  /* Create a tmp mount point to try mounting the decryptd fs
1573   * Since we're here, the mount_point should be a tmpfs filesystem, so make
1574   * a directory in it to test mount the decrypted filesystem.
1575   */
1576  sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1577  mkdir(tmp_mount_point, 0755);
1578  if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1579    SLOGE("Error temp mounting decrypted block device\n");
1580    delete_crypto_blk_dev(label);
1581    crypt_ftr->failed_decrypt_count++;
1582  } else {
1583    /* Success, so just umount and we'll mount it properly when we restart
1584     * the framework.
1585     */
1586    umount(tmp_mount_point);
1587    crypt_ftr->failed_decrypt_count  = 0;
1588  }
1589
1590  if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1591    put_crypt_ftr_and_key(crypt_ftr);
1592  }
1593
1594  if (crypt_ftr->failed_decrypt_count) {
1595    /* We failed to mount the device, so return an error */
1596    rc = crypt_ftr->failed_decrypt_count;
1597
1598  } else {
1599    /* Woot!  Success!  Save the name of the crypto block device
1600     * so we can mount it when restarting the framework.
1601     */
1602    property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1603
1604    /* Also save a the master key so we can reencrypted the key
1605     * the key when we want to change the password on it.
1606     */
1607    memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
1608    saved_mount_point = strdup(mount_point);
1609    master_key_saved = 1;
1610    SLOGD("%s(): Master key saved\n", __FUNCTION__);
1611    rc = 0;
1612
1613    /*
1614     * Upgrade if we're not using the latest KDF.
1615     */
1616    use_keymaster = keymaster_check_compatibility();
1617    if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1618        // Don't allow downgrade to KDF_SCRYPT
1619    } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1620        crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1621        upgrade = 1;
1622    } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1623        crypt_ftr->kdf_type = KDF_SCRYPT;
1624        upgrade = 1;
1625    }
1626
1627    if (upgrade) {
1628        rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1629                                crypt_ftr->master_key, crypt_ftr);
1630        if (!rc) {
1631            rc = put_crypt_ftr_and_key(crypt_ftr);
1632        }
1633        SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1634    }
1635  }
1636
1637  return rc;
1638}
1639
1640/* Called by vold when it wants to undo the crypto mapping of a volume it
1641 * manages.  This is usually in response to a factory reset, when we want
1642 * to undo the crypto mapping so the volume is formatted in the clear.
1643 */
1644int cryptfs_revert_volume(const char *label)
1645{
1646    return delete_crypto_blk_dev((char *)label);
1647}
1648
1649/*
1650 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1651 * Setup a dm-crypt mapping, use the saved master key from
1652 * setting up the /data mapping, and return the new device path.
1653 */
1654int cryptfs_setup_volume(const char *label, int major, int minor,
1655                         char *crypto_sys_path, unsigned int max_path,
1656                         int *new_major, int *new_minor)
1657{
1658    char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1659    struct crypt_mnt_ftr sd_crypt_ftr;
1660    struct stat statbuf;
1661    int nr_sec, fd;
1662
1663    sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1664
1665    get_crypt_ftr_and_key(&sd_crypt_ftr);
1666
1667    /* Update the fs_size field to be the size of the volume */
1668    fd = open(real_blkdev, O_RDONLY);
1669    nr_sec = get_blkdev_size(fd);
1670    close(fd);
1671    if (nr_sec == 0) {
1672        SLOGE("Cannot get size of volume %s\n", real_blkdev);
1673        return -1;
1674    }
1675
1676    sd_crypt_ftr.fs_size = nr_sec;
1677    create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1678                          crypto_blkdev, label);
1679
1680    stat(crypto_blkdev, &statbuf);
1681    *new_major = MAJOR(statbuf.st_rdev);
1682    *new_minor = MINOR(statbuf.st_rdev);
1683
1684    /* Create path to sys entry for this block device */
1685    snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1686
1687    return 0;
1688}
1689
1690int cryptfs_crypto_complete(void)
1691{
1692  return do_crypto_complete("/data");
1693}
1694
1695int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1696{
1697    char encrypted_state[PROPERTY_VALUE_MAX];
1698    property_get("ro.crypto.state", encrypted_state, "");
1699    if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1700        SLOGE("encrypted fs already validated or not running with encryption,"
1701              " aborting");
1702        return -1;
1703    }
1704
1705    if (get_crypt_ftr_and_key(crypt_ftr)) {
1706        SLOGE("Error getting crypt footer and key");
1707        return -1;
1708    }
1709
1710    return 0;
1711}
1712
1713int cryptfs_check_passwd(char *passwd)
1714{
1715    struct crypt_mnt_ftr crypt_ftr;
1716    int rc;
1717
1718    rc = check_unmounted_and_get_ftr(&crypt_ftr);
1719    if (rc)
1720        return rc;
1721
1722    rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1723                                 DATA_MNT_POINT, "userdata");
1724
1725    if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
1726        cryptfs_clear_password();
1727        password = strdup(passwd);
1728        struct timespec now;
1729        clock_gettime(CLOCK_BOOTTIME, &now);
1730        password_expiry_time = now.tv_sec + password_max_age_seconds;
1731    }
1732
1733    return rc;
1734}
1735
1736int cryptfs_verify_passwd(char *passwd)
1737{
1738    struct crypt_mnt_ftr crypt_ftr;
1739    /* Allocate enough space for a 256 bit key, but we may use less */
1740    unsigned char decrypted_master_key[32];
1741    char encrypted_state[PROPERTY_VALUE_MAX];
1742    int rc;
1743
1744    property_get("ro.crypto.state", encrypted_state, "");
1745    if (strcmp(encrypted_state, "encrypted") ) {
1746        SLOGE("device not encrypted, aborting");
1747        return -2;
1748    }
1749
1750    if (!master_key_saved) {
1751        SLOGE("encrypted fs not yet mounted, aborting");
1752        return -1;
1753    }
1754
1755    if (!saved_mount_point) {
1756        SLOGE("encrypted fs failed to save mount point, aborting");
1757        return -1;
1758    }
1759
1760    if (get_crypt_ftr_and_key(&crypt_ftr)) {
1761        SLOGE("Error getting crypt footer and key\n");
1762        return -1;
1763    }
1764
1765    if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1766        /* If the device has no password, then just say the password is valid */
1767        rc = 0;
1768    } else {
1769        decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
1770        if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1771            /* They match, the password is correct */
1772            rc = 0;
1773        } else {
1774            /* If incorrect, sleep for a bit to prevent dictionary attacks */
1775            sleep(1);
1776            rc = 1;
1777        }
1778    }
1779
1780    return rc;
1781}
1782
1783/* Initialize a crypt_mnt_ftr structure.  The keysize is
1784 * defaulted to 16 bytes, and the filesystem size to 0.
1785 * Presumably, at a minimum, the caller will update the
1786 * filesystem size and crypto_type_name after calling this function.
1787 */
1788static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1789{
1790    off64_t off;
1791
1792    memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
1793    ftr->magic = CRYPT_MNT_MAGIC;
1794    ftr->major_version = CURRENT_MAJOR_VERSION;
1795    ftr->minor_version = CURRENT_MINOR_VERSION;
1796    ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
1797    ftr->keysize = KEY_LEN_BYTES;
1798
1799    switch (keymaster_check_compatibility()) {
1800    case 1:
1801        ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1802        break;
1803
1804    case 0:
1805        ftr->kdf_type = KDF_SCRYPT;
1806        break;
1807
1808    default:
1809        SLOGE("keymaster_check_compatibility failed");
1810        return -1;
1811    }
1812
1813    get_device_scrypt_params(ftr);
1814
1815    ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1816    if (get_crypt_ftr_info(NULL, &off) == 0) {
1817        ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1818        ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1819                                    ftr->persist_data_size;
1820    }
1821
1822    return 0;
1823}
1824
1825static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
1826{
1827    const char *args[10];
1828    char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1829    int num_args;
1830    int status;
1831    int tmp;
1832    int rc = -1;
1833
1834    if (type == EXT4_FS) {
1835        args[0] = "/system/bin/make_ext4fs";
1836        args[1] = "-a";
1837        args[2] = "/data";
1838        args[3] = "-l";
1839        snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1840        args[4] = size_str;
1841        args[5] = crypto_blkdev;
1842        num_args = 6;
1843        SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1844              args[0], args[1], args[2], args[3], args[4], args[5]);
1845    } else if (type== FAT_FS) {
1846        args[0] = "/system/bin/newfs_msdos";
1847        args[1] = "-F";
1848        args[2] = "32";
1849        args[3] = "-O";
1850        args[4] = "android";
1851        args[5] = "-c";
1852        args[6] = "8";
1853        args[7] = "-s";
1854        snprintf(size_str, sizeof(size_str), "%lld", size);
1855        args[8] = size_str;
1856        args[9] = crypto_blkdev;
1857        num_args = 10;
1858        SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1859              args[0], args[1], args[2], args[3], args[4], args[5],
1860              args[6], args[7], args[8], args[9]);
1861    } else {
1862        SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1863        return -1;
1864    }
1865
1866    tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1867
1868    if (tmp != 0) {
1869      SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
1870    } else {
1871        if (WIFEXITED(status)) {
1872            if (WEXITSTATUS(status)) {
1873                SLOGE("Error creating filesystem on %s, exit status %d ",
1874                      crypto_blkdev, WEXITSTATUS(status));
1875            } else {
1876                SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1877                rc = 0;
1878            }
1879        } else {
1880            SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1881       }
1882    }
1883
1884    return rc;
1885}
1886
1887#define CRYPT_INPLACE_BUFSIZE 4096
1888#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1889#define CRYPT_SECTOR_SIZE 512
1890
1891/* aligned 32K writes tends to make flash happy.
1892 * SD card association recommends it.
1893 */
1894#define BLOCKS_AT_A_TIME 8
1895
1896struct encryptGroupsData
1897{
1898    int realfd;
1899    int cryptofd;
1900    off64_t numblocks;
1901    off64_t one_pct, cur_pct, new_pct;
1902    off64_t blocks_already_done, tot_numblocks;
1903    off64_t used_blocks_already_done, tot_used_blocks;
1904    char* real_blkdev, * crypto_blkdev;
1905    int count;
1906    off64_t offset;
1907    char* buffer;
1908    off64_t last_written_sector;
1909    int completed;
1910    time_t time_started;
1911    int remaining_time;
1912};
1913
1914static void update_progress(struct encryptGroupsData* data, int is_used)
1915{
1916    data->blocks_already_done++;
1917
1918    if (is_used) {
1919        data->used_blocks_already_done++;
1920    }
1921
1922    if (data->tot_used_blocks) {
1923        data->new_pct = data->used_blocks_already_done / data->one_pct;
1924    } else {
1925        data->new_pct = data->blocks_already_done / data->one_pct;
1926    }
1927
1928    if (data->new_pct > data->cur_pct) {
1929        char buf[8];
1930        data->cur_pct = data->new_pct;
1931        snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1932        property_set("vold.encrypt_progress", buf);
1933        SLOGI("Encrypted %lld percent of drive", data->cur_pct);
1934    }
1935
1936    if (data->cur_pct >= 5) {
1937        double elapsed_time = difftime(time(NULL), data->time_started);
1938        off64_t remaining_blocks = data->tot_used_blocks
1939                                   - data->used_blocks_already_done;
1940        int remaining_time = (int)(elapsed_time * remaining_blocks
1941                                   / data->used_blocks_already_done);
1942        if (data->remaining_time == -1
1943            || remaining_time < data->remaining_time) {
1944            char buf[8];
1945            snprintf(buf, sizeof(buf), "%d", remaining_time);
1946            property_set("vold.encrypt_time_remaining", buf);
1947
1948            SLOGI("Encrypted %lld percent of drive, %d seconds to go",
1949                  data->cur_pct, remaining_time);
1950            data->remaining_time = remaining_time;
1951        }
1952    }
1953}
1954
1955static int flush_outstanding_data(struct encryptGroupsData* data)
1956{
1957    if (data->count == 0) {
1958        return 0;
1959    }
1960
1961    SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1962
1963    if (pread64(data->realfd, data->buffer,
1964                info.block_size * data->count, data->offset)
1965        <= 0) {
1966        SLOGE("Error reading real_blkdev %s for inplace encrypt",
1967              data->real_blkdev);
1968        return -1;
1969    }
1970
1971    if (pwrite64(data->cryptofd, data->buffer,
1972                 info.block_size * data->count, data->offset)
1973        <= 0) {
1974        SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1975              data->crypto_blkdev);
1976        return -1;
1977    } else {
1978        SLOGI("Encrypted %d blocks at sector %lld",
1979              data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
1980    }
1981
1982    data->count = 0;
1983    data->last_written_sector = (data->offset + data->count)
1984                                / info.block_size * CRYPT_SECTOR_SIZE - 1;
1985    return 0;
1986}
1987
1988static int encrypt_groups(struct encryptGroupsData* data)
1989{
1990    unsigned int i;
1991    u8 *block_bitmap = 0;
1992    unsigned int block;
1993    off64_t ret;
1994    int rc = -1;
1995
1996    data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1997    if (!data->buffer) {
1998        SLOGE("Failed to allocate crypto buffer");
1999        goto errout;
2000    }
2001
2002    block_bitmap = malloc(info.block_size);
2003    if (!block_bitmap) {
2004        SLOGE("failed to allocate block bitmap");
2005        goto errout;
2006    }
2007
2008    for (i = 0; i < aux_info.groups; ++i) {
2009        SLOGI("Encrypting group %d", i);
2010
2011        u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2012        u32 block_count = min(info.blocks_per_group,
2013                             aux_info.len_blocks - first_block);
2014
2015        off64_t offset = (u64)info.block_size
2016                         * aux_info.bg_desc[i].bg_block_bitmap;
2017
2018        ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2019        if (ret != (int)info.block_size) {
2020            SLOGE("failed to read all of block group bitmap %d", i);
2021            goto errout;
2022        }
2023
2024        offset = (u64)info.block_size * first_block;
2025
2026        data->count = 0;
2027
2028        for (block = 0; block < block_count; block++) {
2029            int used = bitmap_get_bit(block_bitmap, block);
2030            update_progress(data, used);
2031            if (used) {
2032                if (data->count == 0) {
2033                    data->offset = offset;
2034                }
2035                data->count++;
2036            } else {
2037                if (flush_outstanding_data(data)) {
2038                    goto errout;
2039                }
2040            }
2041
2042            offset += info.block_size;
2043
2044            /* Write data if we are aligned or buffer size reached */
2045            if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2046                || data->count == BLOCKS_AT_A_TIME) {
2047                if (flush_outstanding_data(data)) {
2048                    goto errout;
2049                }
2050            }
2051
2052            if (!is_battery_ok_to_continue()) {
2053                SLOGE("Stopping encryption due to low battery");
2054                rc = 0;
2055                goto errout;
2056            }
2057
2058        }
2059        if (flush_outstanding_data(data)) {
2060            goto errout;
2061        }
2062    }
2063
2064    data->completed = 1;
2065    rc = 0;
2066
2067errout:
2068    free(data->buffer);
2069    free(block_bitmap);
2070    return rc;
2071}
2072
2073static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2074                                       char *real_blkdev,
2075                                       off64_t size,
2076                                       off64_t *size_already_done,
2077                                       off64_t tot_size,
2078                                       off64_t previously_encrypted_upto)
2079{
2080    u32 i;
2081    struct encryptGroupsData data;
2082    int rc = -1;
2083
2084    if (previously_encrypted_upto > *size_already_done) {
2085        SLOGD("Not fast encrypting since resuming part way through");
2086        return -1;
2087    }
2088
2089    memset(&data, 0, sizeof(data));
2090    data.real_blkdev = real_blkdev;
2091    data.crypto_blkdev = crypto_blkdev;
2092
2093    if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2094        SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2095              real_blkdev);
2096        goto errout;
2097    }
2098
2099    if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2100        SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2101              crypto_blkdev);
2102        goto errout;
2103    }
2104
2105    if (setjmp(setjmp_env)) {
2106        SLOGE("Reading extent caused an exception");
2107        goto errout;
2108    }
2109
2110    if (read_ext(data.realfd, 0) != 0) {
2111        SLOGE("Failed to read extent");
2112        goto errout;
2113    }
2114
2115    data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2116    data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2117    data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2118
2119    SLOGI("Encrypting filesystem in place...");
2120
2121    data.tot_used_blocks = data.numblocks;
2122    for (i = 0; i < aux_info.groups; ++i) {
2123      data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2124    }
2125
2126    data.one_pct = data.tot_used_blocks / 100;
2127    data.cur_pct = 0;
2128    data.time_started = time(NULL);
2129    data.remaining_time = -1;
2130
2131    rc = encrypt_groups(&data);
2132    if (rc) {
2133        SLOGE("Error encrypting groups");
2134        goto errout;
2135    }
2136
2137    *size_already_done += data.completed ? size : data.last_written_sector;
2138    rc = 0;
2139
2140errout:
2141    close(data.realfd);
2142    close(data.cryptofd);
2143
2144    return rc;
2145}
2146
2147static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2148                                       off64_t size, off64_t *size_already_done,
2149                                       off64_t tot_size,
2150                                       off64_t previously_encrypted_upto)
2151{
2152    int realfd, cryptofd;
2153    char *buf[CRYPT_INPLACE_BUFSIZE];
2154    int rc = -1;
2155    off64_t numblocks, i, remainder;
2156    off64_t one_pct, cur_pct, new_pct;
2157    off64_t blocks_already_done, tot_numblocks;
2158
2159    if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2160        SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2161        return -1;
2162    }
2163
2164    if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2165        SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2166        close(realfd);
2167        return -1;
2168    }
2169
2170    /* This is pretty much a simple loop of reading 4K, and writing 4K.
2171     * The size passed in is the number of 512 byte sectors in the filesystem.
2172     * So compute the number of whole 4K blocks we should read/write,
2173     * and the remainder.
2174     */
2175    numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2176    remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
2177    tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2178    blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2179
2180    SLOGE("Encrypting filesystem in place...");
2181
2182    i = previously_encrypted_upto + 1 - *size_already_done;
2183
2184    if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2185        SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2186        goto errout;
2187    }
2188
2189    if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2190        SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2191        goto errout;
2192    }
2193
2194    for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2195        if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2196            SLOGE("Error reading initial sectors from real_blkdev %s for "
2197                  "inplace encrypt\n", crypto_blkdev);
2198            goto errout;
2199        }
2200        if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2201            SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2202                  "inplace encrypt\n", crypto_blkdev);
2203            goto errout;
2204        } else {
2205            SLOGI("Encrypted 1 block at %lld", i);
2206        }
2207    }
2208
2209    one_pct = tot_numblocks / 100;
2210    cur_pct = 0;
2211    /* process the majority of the filesystem in blocks */
2212    for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
2213        new_pct = (i + blocks_already_done) / one_pct;
2214        if (new_pct > cur_pct) {
2215            char buf[8];
2216
2217            cur_pct = new_pct;
2218            snprintf(buf, sizeof(buf), "%lld", cur_pct);
2219            property_set("vold.encrypt_progress", buf);
2220        }
2221        if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
2222            SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
2223            goto errout;
2224        }
2225        if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
2226            SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2227            goto errout;
2228        } else {
2229            SLOGD("Encrypted %d block at %lld",
2230                  CRYPT_SECTORS_PER_BUFSIZE,
2231                  i * CRYPT_SECTORS_PER_BUFSIZE);
2232        }
2233
2234       if (!is_battery_ok_to_continue()) {
2235            SLOGE("Stopping encryption due to low battery");
2236            *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2237            rc = 0;
2238            goto errout;
2239        }
2240    }
2241
2242    /* Do any remaining sectors */
2243    for (i=0; i<remainder; i++) {
2244        if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2245            SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
2246            goto errout;
2247        }
2248        if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2249            SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2250            goto errout;
2251        } else {
2252            SLOGI("Encrypted 1 block at next location");
2253        }
2254    }
2255
2256    *size_already_done += size;
2257    rc = 0;
2258
2259errout:
2260    close(realfd);
2261    close(cryptofd);
2262
2263    return rc;
2264}
2265
2266static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2267                                  off64_t size, off64_t *size_already_done,
2268                                  off64_t tot_size,
2269                                  off64_t previously_encrypted_upto)
2270{
2271    if (previously_encrypted_upto) {
2272        SLOGD("Continuing encryption from %lld", previously_encrypted_upto);
2273    }
2274
2275    if (*size_already_done + size < previously_encrypted_upto) {
2276        *size_already_done += size;
2277        return 0;
2278    }
2279
2280    if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
2281                                    size, size_already_done,
2282                                    tot_size, previously_encrypted_upto) == 0) {
2283        return 0;
2284    }
2285
2286    return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
2287                                       size, size_already_done, tot_size,
2288                                       previously_encrypted_upto);
2289}
2290
2291#define CRYPTO_ENABLE_WIPE 1
2292#define CRYPTO_ENABLE_INPLACE 2
2293
2294#define FRAMEWORK_BOOT_WAIT 60
2295
2296static inline int should_encrypt(struct volume_info *volume)
2297{
2298    return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
2299            (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2300}
2301
2302static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2303{
2304    int fd = open(filename, O_RDONLY);
2305    if (fd == -1) {
2306        SLOGE("Error opening file %s", filename);
2307        return -1;
2308    }
2309
2310    char block[CRYPT_INPLACE_BUFSIZE];
2311    memset(block, 0, sizeof(block));
2312    if (unix_read(fd, block, sizeof(block)) < 0) {
2313        SLOGE("Error reading file %s", filename);
2314        close(fd);
2315        return -1;
2316    }
2317
2318    close(fd);
2319
2320    SHA256_CTX c;
2321    SHA256_Init(&c);
2322    SHA256_Update(&c, block, sizeof(block));
2323    SHA256_Final(buf, &c);
2324
2325    return 0;
2326}
2327
2328static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2329                                      char *crypto_blkdev, char *real_blkdev,
2330                                      int previously_encrypted_upto)
2331{
2332    off64_t cur_encryption_done=0, tot_encryption_size=0;
2333    int i, rc = -1;
2334
2335    if (!is_battery_ok_to_start()) {
2336        SLOGW("Not starting encryption due to low battery");
2337        return 0;
2338    }
2339
2340    /* The size of the userdata partition, and add in the vold volumes below */
2341    tot_encryption_size = crypt_ftr->fs_size;
2342
2343    if (how == CRYPTO_ENABLE_WIPE) {
2344        rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, EXT4_FS);
2345    } else if (how == CRYPTO_ENABLE_INPLACE) {
2346        rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2347                                    crypt_ftr->fs_size, &cur_encryption_done,
2348                                    tot_encryption_size,
2349                                    previously_encrypted_upto);
2350
2351        if (!rc) {
2352            crypt_ftr->encrypted_upto = cur_encryption_done;
2353        }
2354
2355        if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2356            /* The inplace routine never actually sets the progress to 100% due
2357             * to the round down nature of integer division, so set it here */
2358            property_set("vold.encrypt_progress", "100");
2359        }
2360    } else {
2361        /* Shouldn't happen */
2362        SLOGE("cryptfs_enable: internal error, unknown option\n");
2363        rc = -1;
2364    }
2365
2366    return rc;
2367}
2368
2369int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2370                            int allow_reboot)
2371{
2372    int how = 0;
2373    char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
2374    unsigned long nr_sec;
2375    unsigned char decrypted_master_key[KEY_LEN_BYTES];
2376    int rc=-1, fd, i, ret;
2377    struct crypt_mnt_ftr crypt_ftr;
2378    struct crypt_persist_data *pdata;
2379    char encrypted_state[PROPERTY_VALUE_MAX];
2380    char lockid[32] = { 0 };
2381    char key_loc[PROPERTY_VALUE_MAX];
2382    char fuse_sdcard[PROPERTY_VALUE_MAX];
2383    char *sd_mnt_point;
2384    int num_vols;
2385    struct volume_info *vol_list = 0;
2386    off64_t previously_encrypted_upto = 0;
2387
2388    if (!strcmp(howarg, "wipe")) {
2389      how = CRYPTO_ENABLE_WIPE;
2390    } else if (! strcmp(howarg, "inplace")) {
2391      how = CRYPTO_ENABLE_INPLACE;
2392    } else {
2393      /* Shouldn't happen, as CommandListener vets the args */
2394      goto error_unencrypted;
2395    }
2396
2397    /* See if an encryption was underway and interrupted */
2398    if (how == CRYPTO_ENABLE_INPLACE
2399          && get_crypt_ftr_and_key(&crypt_ftr) == 0
2400          && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2401        previously_encrypted_upto = crypt_ftr.encrypted_upto;
2402        crypt_ftr.encrypted_upto = 0;
2403    }
2404
2405    property_get("ro.crypto.state", encrypted_state, "");
2406    if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2407        SLOGE("Device is already running encrypted, aborting");
2408        goto error_unencrypted;
2409    }
2410
2411    // TODO refactor fs_mgr_get_crypt_info to get both in one call
2412    fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
2413    fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
2414
2415    /* Get the size of the real block device */
2416    fd = open(real_blkdev, O_RDONLY);
2417    if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2418        SLOGE("Cannot get size of block device %s\n", real_blkdev);
2419        goto error_unencrypted;
2420    }
2421    close(fd);
2422
2423    /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
2424    if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
2425        unsigned int fs_size_sec, max_fs_size_sec;
2426
2427        fs_size_sec = get_fs_size(real_blkdev);
2428        max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2429
2430        if (fs_size_sec > max_fs_size_sec) {
2431            SLOGE("Orig filesystem overlaps crypto footer region.  Cannot encrypt in place.");
2432            goto error_unencrypted;
2433        }
2434    }
2435
2436    /* Get a wakelock as this may take a while, and we don't want the
2437     * device to sleep on us.  We'll grab a partial wakelock, and if the UI
2438     * wants to keep the screen on, it can grab a full wakelock.
2439     */
2440    snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
2441    acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2442
2443    /* Get the sdcard mount point */
2444    sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
2445    if (!sd_mnt_point) {
2446       sd_mnt_point = getenv("EXTERNAL_STORAGE");
2447    }
2448    if (!sd_mnt_point) {
2449        sd_mnt_point = "/mnt/sdcard";
2450    }
2451
2452    /* TODO
2453     * Currently do not have test devices with multiple encryptable volumes.
2454     * When we acquire some, re-add support.
2455     */
2456    num_vols=vold_getNumDirectVolumes();
2457    vol_list = malloc(sizeof(struct volume_info) * num_vols);
2458    vold_getDirectVolumeList(vol_list);
2459
2460    for (i=0; i<num_vols; i++) {
2461        if (should_encrypt(&vol_list[i])) {
2462            SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2463                  "%s\n", vol_list[i].label);
2464            goto error_unencrypted;
2465        }
2466    }
2467
2468    /* The init files are setup to stop the class main and late start when
2469     * vold sets trigger_shutdown_framework.
2470     */
2471    property_set("vold.decrypt", "trigger_shutdown_framework");
2472    SLOGD("Just asked init to shut down class main\n");
2473
2474    if (vold_unmountAllAsecs()) {
2475        /* Just report the error.  If any are left mounted,
2476         * umounting /data below will fail and handle the error.
2477         */
2478        SLOGE("Error unmounting internal asecs");
2479    }
2480
2481    property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2482    if (!strcmp(fuse_sdcard, "true")) {
2483        /* This is a device using the fuse layer to emulate the sdcard semantics
2484         * on top of the userdata partition.  vold does not manage it, it is managed
2485         * by the sdcard service.  The sdcard service was killed by the property trigger
2486         * above, so just unmount it now.  We must do this _AFTER_ killing the framework,
2487         * unlike the case for vold managed devices above.
2488         */
2489        if (wait_and_unmount(sd_mnt_point)) {
2490            goto error_shutting_down;
2491        }
2492    }
2493
2494    /* Now unmount the /data partition. */
2495    if (wait_and_unmount(DATA_MNT_POINT)) {
2496        if (allow_reboot) {
2497            goto error_shutting_down;
2498        } else {
2499            goto error_unencrypted;
2500        }
2501    }
2502
2503    /* Do extra work for a better UX when doing the long inplace encryption */
2504    if (how == CRYPTO_ENABLE_INPLACE) {
2505        /* Now that /data is unmounted, we need to mount a tmpfs
2506         * /data, set a property saying we're doing inplace encryption,
2507         * and restart the framework.
2508         */
2509        if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2510            goto error_shutting_down;
2511        }
2512        /* Tells the framework that inplace encryption is starting */
2513        property_set("vold.encrypt_progress", "0");
2514
2515        /* restart the framework. */
2516        /* Create necessary paths on /data */
2517        if (prep_data_fs()) {
2518            goto error_shutting_down;
2519        }
2520
2521        /* Ugh, shutting down the framework is not synchronous, so until it
2522         * can be fixed, this horrible hack will wait a moment for it all to
2523         * shut down before proceeding.  Without it, some devices cannot
2524         * restart the graphics services.
2525         */
2526        sleep(2);
2527
2528        /* startup service classes main and late_start */
2529        property_set("vold.decrypt", "trigger_restart_min_framework");
2530        SLOGD("Just triggered restart_min_framework\n");
2531
2532        /* OK, the framework is restarted and will soon be showing a
2533         * progress bar.  Time to setup an encrypted mapping, and
2534         * either write a new filesystem, or encrypt in place updating
2535         * the progress bar as we work.
2536         */
2537    }
2538
2539    /* Start the actual work of making an encrypted filesystem */
2540    /* Initialize a crypt_mnt_ftr for the partition */
2541    if (previously_encrypted_upto == 0) {
2542        if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2543            goto error_shutting_down;
2544        }
2545
2546        if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2547            crypt_ftr.fs_size = nr_sec
2548              - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2549        } else {
2550            crypt_ftr.fs_size = nr_sec;
2551        }
2552        crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2553        crypt_ftr.crypt_type = crypt_type;
2554        strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
2555
2556        /* Make an encrypted master key */
2557        if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2558            SLOGE("Cannot create encrypted master key\n");
2559            goto error_shutting_down;
2560        }
2561
2562        /* Write the key to the end of the partition */
2563        put_crypt_ftr_and_key(&crypt_ftr);
2564
2565        /* If any persistent data has been remembered, save it.
2566         * If none, create a valid empty table and save that.
2567         */
2568        if (!persist_data) {
2569           pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2570           if (pdata) {
2571               init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2572               persist_data = pdata;
2573           }
2574        }
2575        if (persist_data) {
2576            save_persistent_data();
2577        }
2578    }
2579
2580    decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
2581    create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2582                          "userdata");
2583
2584    /* If we are continuing, check checksums match */
2585    rc = 0;
2586    if (previously_encrypted_upto) {
2587        __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2588        rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
2589
2590        if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2591                          sizeof(hash_first_block)) != 0) {
2592            SLOGE("Checksums do not match - trigger wipe");
2593            rc = -1;
2594        }
2595    }
2596
2597    if (!rc) {
2598        rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2599                                        crypto_blkdev, real_blkdev,
2600                                        previously_encrypted_upto);
2601    }
2602
2603    /* Calculate checksum if we are not finished */
2604    if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
2605        rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2606                                      crypt_ftr.hash_first_block);
2607        if (rc) {
2608            SLOGE("Error calculating checksum for continuing encryption");
2609            rc = -1;
2610        }
2611    }
2612
2613    /* Undo the dm-crypt mapping whether we succeed or not */
2614    delete_crypto_blk_dev("userdata");
2615
2616    free(vol_list);
2617
2618    if (! rc) {
2619        /* Success */
2620
2621        /* Clear the encryption in progress flag in the footer */
2622        if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2623            crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2624        } else {
2625            SLOGD("Encrypted up to sector %lld - will continue after reboot",
2626                  crypt_ftr.encrypted_upto);
2627        }
2628
2629        if (crypt_ftr.encrypted_upto) {
2630            put_crypt_ftr_and_key(&crypt_ftr);
2631        }
2632
2633        sleep(2); /* Give the UI a chance to show 100% progress */
2634                  /* Partially encrypted - ensure writes are flushed to ssd */
2635
2636        if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2637            cryptfs_reboot(reboot);
2638        } else {
2639            cryptfs_reboot(shutdown);
2640        }
2641    } else {
2642        char value[PROPERTY_VALUE_MAX];
2643
2644        property_get("ro.vold.wipe_on_crypt_fail", value, "0");
2645        if (!strcmp(value, "1")) {
2646            /* wipe data if encryption failed */
2647            SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2648            mkdir("/cache/recovery", 0700);
2649            int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
2650            if (fd >= 0) {
2651                write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2652                close(fd);
2653            } else {
2654                SLOGE("could not open /cache/recovery/command\n");
2655            }
2656            cryptfs_reboot(recovery);
2657        } else {
2658            /* set property to trigger dialog */
2659            property_set("vold.encrypt_progress", "error_partially_encrypted");
2660            release_wake_lock(lockid);
2661        }
2662        return -1;
2663    }
2664
2665    /* hrm, the encrypt step claims success, but the reboot failed.
2666     * This should not happen.
2667     * Set the property and return.  Hope the framework can deal with it.
2668     */
2669    property_set("vold.encrypt_progress", "error_reboot_failed");
2670    release_wake_lock(lockid);
2671    return rc;
2672
2673error_unencrypted:
2674    free(vol_list);
2675    property_set("vold.encrypt_progress", "error_not_encrypted");
2676    if (lockid[0]) {
2677        release_wake_lock(lockid);
2678    }
2679    return -1;
2680
2681error_shutting_down:
2682    /* we failed, and have not encrypted anthing, so the users's data is still intact,
2683     * but the framework is stopped and not restarted to show the error, so it's up to
2684     * vold to restart the system.
2685     */
2686    SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
2687    cryptfs_reboot(reboot);
2688
2689    /* shouldn't get here */
2690    property_set("vold.encrypt_progress", "error_shutting_down");
2691    free(vol_list);
2692    if (lockid[0]) {
2693        release_wake_lock(lockid);
2694    }
2695    return -1;
2696}
2697
2698int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
2699{
2700    return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
2701}
2702
2703int cryptfs_enable_default(char *howarg, int allow_reboot)
2704{
2705    return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2706                          DEFAULT_PASSWORD, allow_reboot);
2707}
2708
2709int cryptfs_changepw(int crypt_type, const char *newpw)
2710{
2711    struct crypt_mnt_ftr crypt_ftr;
2712    unsigned char decrypted_master_key[KEY_LEN_BYTES];
2713
2714    /* This is only allowed after we've successfully decrypted the master key */
2715    if (!master_key_saved) {
2716        SLOGE("Key not saved, aborting");
2717        return -1;
2718    }
2719
2720    if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2721        SLOGE("Invalid crypt_type %d", crypt_type);
2722        return -1;
2723    }
2724
2725    /* get key */
2726    if (get_crypt_ftr_and_key(&crypt_ftr)) {
2727        SLOGE("Error getting crypt footer and key");
2728        return -1;
2729    }
2730
2731    crypt_ftr.crypt_type = crypt_type;
2732
2733    encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2734                                                        : newpw,
2735                       crypt_ftr.salt,
2736                       saved_master_key,
2737                       crypt_ftr.master_key,
2738                       &crypt_ftr);
2739
2740    /* save the key */
2741    put_crypt_ftr_and_key(&crypt_ftr);
2742
2743    return 0;
2744}
2745
2746static int persist_get_key(char *fieldname, char *value)
2747{
2748    unsigned int i;
2749
2750    if (persist_data == NULL) {
2751        return -1;
2752    }
2753    for (i = 0; i < persist_data->persist_valid_entries; i++) {
2754        if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2755            /* We found it! */
2756            strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2757            return 0;
2758        }
2759    }
2760
2761    return -1;
2762}
2763
2764static int persist_set_key(char *fieldname, char *value, int encrypted)
2765{
2766    unsigned int i;
2767    unsigned int num;
2768    struct crypt_mnt_ftr crypt_ftr;
2769    unsigned int max_persistent_entries;
2770    unsigned int dsize;
2771
2772    if (persist_data == NULL) {
2773        return -1;
2774    }
2775
2776    /* If encrypted, use the values from the crypt_ftr, otherwise
2777     * use the values for the current spec.
2778     */
2779    if (encrypted) {
2780        if(get_crypt_ftr_and_key(&crypt_ftr)) {
2781            return -1;
2782        }
2783        dsize = crypt_ftr.persist_data_size;
2784    } else {
2785        dsize = CRYPT_PERSIST_DATA_SIZE;
2786    }
2787    max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2788                             sizeof(struct crypt_persist_entry);
2789
2790    num = persist_data->persist_valid_entries;
2791
2792    for (i = 0; i < num; i++) {
2793        if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2794            /* We found an existing entry, update it! */
2795            memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2796            strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2797            return 0;
2798        }
2799    }
2800
2801    /* We didn't find it, add it to the end, if there is room */
2802    if (persist_data->persist_valid_entries < max_persistent_entries) {
2803        memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2804        strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2805        strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2806        persist_data->persist_valid_entries++;
2807        return 0;
2808    }
2809
2810    return -1;
2811}
2812
2813/* Return the value of the specified field. */
2814int cryptfs_getfield(char *fieldname, char *value, int len)
2815{
2816    char temp_value[PROPERTY_VALUE_MAX];
2817    char real_blkdev[MAXPATHLEN];
2818    /* 0 is success, 1 is not encrypted,
2819     * -1 is value not set, -2 is any other error
2820     */
2821    int rc = -2;
2822
2823    if (persist_data == NULL) {
2824        load_persistent_data();
2825        if (persist_data == NULL) {
2826            SLOGE("Getfield error, cannot load persistent data");
2827            goto out;
2828        }
2829    }
2830
2831    if (!persist_get_key(fieldname, temp_value)) {
2832        /* We found it, copy it to the caller's buffer and return */
2833        strlcpy(value, temp_value, len);
2834        rc = 0;
2835    } else {
2836        /* Sadness, it's not there.  Return the error */
2837        rc = -1;
2838    }
2839
2840out:
2841    return rc;
2842}
2843
2844/* Set the value of the specified field. */
2845int cryptfs_setfield(char *fieldname, char *value)
2846{
2847    struct crypt_persist_data stored_pdata;
2848    struct crypt_persist_data *pdata_p;
2849    struct crypt_mnt_ftr crypt_ftr;
2850    char encrypted_state[PROPERTY_VALUE_MAX];
2851    /* 0 is success, -1 is an error */
2852    int rc = -1;
2853    int encrypted = 0;
2854
2855    if (persist_data == NULL) {
2856        load_persistent_data();
2857        if (persist_data == NULL) {
2858            SLOGE("Setfield error, cannot load persistent data");
2859            goto out;
2860        }
2861    }
2862
2863    property_get("ro.crypto.state", encrypted_state, "");
2864    if (!strcmp(encrypted_state, "encrypted") ) {
2865        encrypted = 1;
2866    }
2867
2868    if (persist_set_key(fieldname, value, encrypted)) {
2869        goto out;
2870    }
2871
2872    /* If we are running encrypted, save the persistent data now */
2873    if (encrypted) {
2874        if (save_persistent_data()) {
2875            SLOGE("Setfield error, cannot save persistent data");
2876            goto out;
2877        }
2878    }
2879
2880    rc = 0;
2881
2882out:
2883    return rc;
2884}
2885
2886/* Checks userdata. Attempt to mount the volume if default-
2887 * encrypted.
2888 * On success trigger next init phase and return 0.
2889 * Currently do not handle failure - see TODO below.
2890 */
2891int cryptfs_mount_default_encrypted(void)
2892{
2893    char decrypt_state[PROPERTY_VALUE_MAX];
2894    property_get("vold.decrypt", decrypt_state, "0");
2895    if (!strcmp(decrypt_state, "0")) {
2896        SLOGE("Not encrypted - should not call here");
2897    } else {
2898        int crypt_type = cryptfs_get_password_type();
2899        if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2900            SLOGE("Bad crypt type - error");
2901        } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2902            SLOGD("Password is not default - "
2903                  "starting min framework to prompt");
2904            property_set("vold.decrypt", "trigger_restart_min_framework");
2905            return 0;
2906        } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2907            SLOGD("Password is default - restarting filesystem");
2908            cryptfs_restart_internal(0);
2909            return 0;
2910        } else {
2911            SLOGE("Encrypted, default crypt type but can't decrypt");
2912        }
2913    }
2914
2915    /** @TODO make sure we factory wipe in this situation
2916     *  In general if we got here there is no recovery
2917     */
2918    return 0;
2919}
2920
2921/* Returns type of the password, default, pattern, pin or password.
2922 */
2923int cryptfs_get_password_type(void)
2924{
2925    struct crypt_mnt_ftr crypt_ftr;
2926
2927    if (get_crypt_ftr_and_key(&crypt_ftr)) {
2928        SLOGE("Error getting crypt footer and key\n");
2929        return -1;
2930    }
2931
2932    return crypt_ftr.crypt_type;
2933}
2934
2935char* cryptfs_get_password()
2936{
2937    struct timespec now;
2938    clock_gettime(CLOCK_MONOTONIC, &now);
2939    if (now.tv_sec < password_expiry_time) {
2940        return password;
2941    } else {
2942        cryptfs_clear_password();
2943        return 0;
2944    }
2945}
2946
2947void cryptfs_clear_password()
2948{
2949    if (password) {
2950        size_t len = strlen(password);
2951        memset(password, 0, len);
2952        free(password);
2953        password = 0;
2954        password_expiry_time = 0;
2955    }
2956}
2957