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