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