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