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