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 <fcntl.h>
27#include <unistd.h>
28#include <stdio.h>
29#include <sys/ioctl.h>
30#include <linux/dm-ioctl.h>
31#include <libgen.h>
32#include <stdlib.h>
33#include <sys/param.h>
34#include <string.h>
35#include <sys/mount.h>
36#include <openssl/evp.h>
37#include <openssl/sha.h>
38#include <errno.h>
39#include <ext4.h>
40#include <linux/kdev_t.h>
41#include <fs_mgr.h>
42#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
46#include "cutils/android_reboot.h"
47#include "hardware_legacy/power.h"
48#include <logwrap/logwrap.h>
49#include "VolumeManager.h"
50#include "VoldUtil.h"
51#include "crypto_scrypt.h"
52
53#define DM_CRYPT_BUF_SIZE 4096
54#define DATA_MNT_POINT "/data"
55
56#define HASH_COUNT 2000
57#define KEY_LEN_BYTES 16
58#define IV_LEN_BYTES 16
59
60#define KEY_IN_FOOTER  "footer"
61
62#define EXT4_FS 1
63#define FAT_FS 2
64
65#define TABLE_LOAD_RETRIES 10
66
67char *me = "cryptfs";
68
69static unsigned char saved_master_key[KEY_LEN_BYTES];
70static char *saved_mount_point;
71static int  master_key_saved = 0;
72static struct crypt_persist_data *persist_data = NULL;
73
74extern struct fstab *fstab;
75
76static void cryptfs_reboot(int recovery)
77{
78    if (recovery) {
79        property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
80    } else {
81        property_set(ANDROID_RB_PROPERTY, "reboot");
82    }
83    sleep(20);
84
85    /* Shouldn't get here, reboot should happen before sleep times out */
86    return;
87}
88
89static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
90{
91    memset(io, 0, dataSize);
92    io->data_size = dataSize;
93    io->data_start = sizeof(struct dm_ioctl);
94    io->version[0] = 4;
95    io->version[1] = 0;
96    io->version[2] = 0;
97    io->flags = flags;
98    if (name) {
99        strncpy(io->name, name, sizeof(io->name));
100    }
101}
102
103/**
104 * Gets the default device scrypt parameters for key derivation time tuning.
105 * The parameters should lead to about one second derivation time for the
106 * given device.
107 */
108static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
109    const int default_params[] = SCRYPT_DEFAULTS;
110    int params[] = SCRYPT_DEFAULTS;
111    char paramstr[PROPERTY_VALUE_MAX];
112    char *token;
113    char *saveptr;
114    int i;
115
116    property_get(SCRYPT_PROP, paramstr, "");
117    if (paramstr[0] != '\0') {
118        /*
119         * The token we're looking for should be three integers separated by
120         * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
121         */
122        for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
123                token != NULL && i < 3;
124                i++, token = strtok_r(NULL, ":", &saveptr)) {
125            char *endptr;
126            params[i] = strtol(token, &endptr, 10);
127
128            /*
129             * Check that there was a valid number and it's 8-bit. If not,
130             * break out and the end check will take the default values.
131             */
132            if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
133                break;
134            }
135        }
136
137        /*
138         * If there were not enough tokens or a token was malformed (not an
139         * integer), it will end up here and the default parameters can be
140         * taken.
141         */
142        if ((i != 3) || (token != NULL)) {
143            SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
144            memcpy(params, default_params, sizeof(params));
145        }
146    }
147
148    ftr->N_factor = params[0];
149    ftr->r_factor = params[1];
150    ftr->p_factor = params[2];
151}
152
153static unsigned int get_fs_size(char *dev)
154{
155    int fd, block_size;
156    struct ext4_super_block sb;
157    off64_t len;
158
159    if ((fd = open(dev, O_RDONLY)) < 0) {
160        SLOGE("Cannot open device to get filesystem size ");
161        return 0;
162    }
163
164    if (lseek64(fd, 1024, SEEK_SET) < 0) {
165        SLOGE("Cannot seek to superblock");
166        return 0;
167    }
168
169    if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
170        SLOGE("Cannot read superblock");
171        return 0;
172    }
173
174    close(fd);
175
176    block_size = 1024 << sb.s_log_block_size;
177    /* compute length in bytes */
178    len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
179
180    /* return length in sectors */
181    return (unsigned int) (len / 512);
182}
183
184static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
185{
186  static int cached_data = 0;
187  static off64_t cached_off = 0;
188  static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
189  int fd;
190  char key_loc[PROPERTY_VALUE_MAX];
191  char real_blkdev[PROPERTY_VALUE_MAX];
192  unsigned int nr_sec;
193  int rc = -1;
194
195  if (!cached_data) {
196    fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
197
198    if (!strcmp(key_loc, KEY_IN_FOOTER)) {
199      if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
200        SLOGE("Cannot open real block device %s\n", real_blkdev);
201        return -1;
202      }
203
204      if ((nr_sec = get_blkdev_size(fd))) {
205        /* If it's an encrypted Android partition, the last 16 Kbytes contain the
206         * encryption info footer and key, and plenty of bytes to spare for future
207         * growth.
208         */
209        strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
210        cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
211        cached_data = 1;
212      } else {
213        SLOGE("Cannot get size of block device %s\n", real_blkdev);
214      }
215      close(fd);
216    } else {
217      strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
218      cached_off = 0;
219      cached_data = 1;
220    }
221  }
222
223  if (cached_data) {
224    if (metadata_fname) {
225        *metadata_fname = cached_metadata_fname;
226    }
227    if (off) {
228        *off = cached_off;
229    }
230    rc = 0;
231  }
232
233  return rc;
234}
235
236/* key or salt can be NULL, in which case just skip writing that value.  Useful to
237 * update the failed mount count but not change the key.
238 */
239static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
240{
241  int fd;
242  unsigned int nr_sec, cnt;
243  /* starting_off is set to the SEEK_SET offset
244   * where the crypto structure starts
245   */
246  off64_t starting_off;
247  int rc = -1;
248  char *fname = NULL;
249  struct stat statbuf;
250
251  if (get_crypt_ftr_info(&fname, &starting_off)) {
252    SLOGE("Unable to get crypt_ftr_info\n");
253    return -1;
254  }
255  if (fname[0] != '/') {
256    SLOGE("Unexpected value for crypto key location\n");
257    return -1;
258  }
259  if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
260    SLOGE("Cannot open footer file %s for put\n", fname);
261    return -1;
262  }
263
264  /* Seek to the start of the crypt footer */
265  if (lseek64(fd, starting_off, SEEK_SET) == -1) {
266    SLOGE("Cannot seek to real block device footer\n");
267    goto errout;
268  }
269
270  if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
271    SLOGE("Cannot write real block device footer\n");
272    goto errout;
273  }
274
275  fstat(fd, &statbuf);
276  /* If the keys are kept on a raw block device, do not try to truncate it. */
277  if (S_ISREG(statbuf.st_mode)) {
278    if (ftruncate(fd, 0x4000)) {
279      SLOGE("Cannot set footer file size\n", fname);
280      goto errout;
281    }
282  }
283
284  /* Success! */
285  rc = 0;
286
287errout:
288  close(fd);
289  return rc;
290
291}
292
293static inline int unix_read(int  fd, void*  buff, int  len)
294{
295    return TEMP_FAILURE_RETRY(read(fd, buff, len));
296}
297
298static inline int unix_write(int  fd, const void*  buff, int  len)
299{
300    return TEMP_FAILURE_RETRY(write(fd, buff, len));
301}
302
303static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
304{
305    memset(pdata, 0, len);
306    pdata->persist_magic = PERSIST_DATA_MAGIC;
307    pdata->persist_valid_entries = 0;
308}
309
310/* A routine to update the passed in crypt_ftr to the lastest version.
311 * fd is open read/write on the device that holds the crypto footer and persistent
312 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
313 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
314 */
315static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
316{
317    int orig_major = crypt_ftr->major_version;
318    int orig_minor = crypt_ftr->minor_version;
319
320    if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
321        struct crypt_persist_data *pdata;
322        off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
323
324        SLOGW("upgrading crypto footer to 1.1");
325
326        pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
327        if (pdata == NULL) {
328            SLOGE("Cannot allocate persisent data\n");
329            return;
330        }
331        memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
332
333        /* Need to initialize the persistent data area */
334        if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
335            SLOGE("Cannot seek to persisent data offset\n");
336            return;
337        }
338        /* Write all zeros to the first copy, making it invalid */
339        unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
340
341        /* Write a valid but empty structure to the second copy */
342        init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
343        unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
344
345        /* Update the footer */
346        crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
347        crypt_ftr->persist_data_offset[0] = pdata_offset;
348        crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
349        crypt_ftr->minor_version = 1;
350    }
351
352    if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
353        SLOGW("upgrading crypto footer to 1.2");
354        crypt_ftr->kdf_type = KDF_PBKDF2;
355        get_device_scrypt_params(crypt_ftr);
356        crypt_ftr->minor_version = 2;
357    }
358
359    if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
360        if (lseek64(fd, offset, SEEK_SET) == -1) {
361            SLOGE("Cannot seek to crypt footer\n");
362            return;
363        }
364        unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
365    }
366}
367
368
369static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
370{
371  int fd;
372  unsigned int nr_sec, cnt;
373  off64_t starting_off;
374  int rc = -1;
375  char *fname = NULL;
376  struct stat statbuf;
377
378  if (get_crypt_ftr_info(&fname, &starting_off)) {
379    SLOGE("Unable to get crypt_ftr_info\n");
380    return -1;
381  }
382  if (fname[0] != '/') {
383    SLOGE("Unexpected value for crypto key location\n");
384    return -1;
385  }
386  if ( (fd = open(fname, O_RDWR)) < 0) {
387    SLOGE("Cannot open footer file %s for get\n", fname);
388    return -1;
389  }
390
391  /* Make sure it's 16 Kbytes in length */
392  fstat(fd, &statbuf);
393  if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
394    SLOGE("footer file %s is not the expected size!\n", fname);
395    goto errout;
396  }
397
398  /* Seek to the start of the crypt footer */
399  if (lseek64(fd, starting_off, SEEK_SET) == -1) {
400    SLOGE("Cannot seek to real block device footer\n");
401    goto errout;
402  }
403
404  if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
405    SLOGE("Cannot read real block device footer\n");
406    goto errout;
407  }
408
409  if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
410    SLOGE("Bad magic for real block device %s\n", fname);
411    goto errout;
412  }
413
414  if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
415    SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
416          crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
417    goto errout;
418  }
419
420  if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
421    SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
422          crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
423  }
424
425  /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
426   * copy on disk before returning.
427   */
428  if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
429    upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
430  }
431
432  /* Success! */
433  rc = 0;
434
435errout:
436  close(fd);
437  return rc;
438}
439
440static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
441{
442    if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
443        crypt_ftr->persist_data_offset[1]) {
444        SLOGE("Crypt_ftr persist data regions overlap");
445        return -1;
446    }
447
448    if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
449        SLOGE("Crypt_ftr persist data region 0 starts after region 1");
450        return -1;
451    }
452
453    if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
454        (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
455        CRYPT_FOOTER_OFFSET) {
456        SLOGE("Persistent data extends past crypto footer");
457        return -1;
458    }
459
460    return 0;
461}
462
463static int load_persistent_data(void)
464{
465    struct crypt_mnt_ftr crypt_ftr;
466    struct crypt_persist_data *pdata = NULL;
467    char encrypted_state[PROPERTY_VALUE_MAX];
468    char *fname;
469    int found = 0;
470    int fd;
471    int ret;
472    int i;
473
474    if (persist_data) {
475        /* Nothing to do, we've already loaded or initialized it */
476        return 0;
477    }
478
479
480    /* If not encrypted, just allocate an empty table and initialize it */
481    property_get("ro.crypto.state", encrypted_state, "");
482    if (strcmp(encrypted_state, "encrypted") ) {
483        pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
484        if (pdata) {
485            init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
486            persist_data = pdata;
487            return 0;
488        }
489        return -1;
490    }
491
492    if(get_crypt_ftr_and_key(&crypt_ftr)) {
493        return -1;
494    }
495
496    if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
497        SLOGE("Crypt_ftr version doesn't support persistent data");
498        return -1;
499    }
500
501    if (get_crypt_ftr_info(&fname, NULL)) {
502        return -1;
503    }
504
505    ret = validate_persistent_data_storage(&crypt_ftr);
506    if (ret) {
507        return -1;
508    }
509
510    fd = open(fname, O_RDONLY);
511    if (fd < 0) {
512        SLOGE("Cannot open %s metadata file", fname);
513        return -1;
514    }
515
516    if (persist_data == NULL) {
517        pdata = malloc(crypt_ftr.persist_data_size);
518        if (pdata == NULL) {
519            SLOGE("Cannot allocate memory for persistent data");
520            goto err;
521        }
522    }
523
524    for (i = 0; i < 2; i++) {
525        if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
526            SLOGE("Cannot seek to read persistent data on %s", fname);
527            goto err2;
528        }
529        if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
530            SLOGE("Error reading persistent data on iteration %d", i);
531            goto err2;
532        }
533        if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
534            found = 1;
535            break;
536        }
537    }
538
539    if (!found) {
540        SLOGI("Could not find valid persistent data, creating");
541        init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
542    }
543
544    /* Success */
545    persist_data = pdata;
546    close(fd);
547    return 0;
548
549err2:
550    free(pdata);
551
552err:
553    close(fd);
554    return -1;
555}
556
557static int save_persistent_data(void)
558{
559    struct crypt_mnt_ftr crypt_ftr;
560    struct crypt_persist_data *pdata;
561    char *fname;
562    off64_t write_offset;
563    off64_t erase_offset;
564    int found = 0;
565    int fd;
566    int ret;
567
568    if (persist_data == NULL) {
569        SLOGE("No persistent data to save");
570        return -1;
571    }
572
573    if(get_crypt_ftr_and_key(&crypt_ftr)) {
574        return -1;
575    }
576
577    if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
578        SLOGE("Crypt_ftr version doesn't support persistent data");
579        return -1;
580    }
581
582    ret = validate_persistent_data_storage(&crypt_ftr);
583    if (ret) {
584        return -1;
585    }
586
587    if (get_crypt_ftr_info(&fname, NULL)) {
588        return -1;
589    }
590
591    fd = open(fname, O_RDWR);
592    if (fd < 0) {
593        SLOGE("Cannot open %s metadata file", fname);
594        return -1;
595    }
596
597    pdata = malloc(crypt_ftr.persist_data_size);
598    if (pdata == NULL) {
599        SLOGE("Cannot allocate persistant data");
600        goto err;
601    }
602
603    if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
604        SLOGE("Cannot seek to read persistent data on %s", fname);
605        goto err2;
606    }
607
608    if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
609            SLOGE("Error reading persistent data before save");
610            goto err2;
611    }
612
613    if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
614        /* The first copy is the curent valid copy, so write to
615         * the second copy and erase this one */
616       write_offset = crypt_ftr.persist_data_offset[1];
617       erase_offset = crypt_ftr.persist_data_offset[0];
618    } else {
619        /* The second copy must be the valid copy, so write to
620         * the first copy, and erase the second */
621       write_offset = crypt_ftr.persist_data_offset[0];
622       erase_offset = crypt_ftr.persist_data_offset[1];
623    }
624
625    /* Write the new copy first, if successful, then erase the old copy */
626    if (lseek(fd, write_offset, SEEK_SET) < 0) {
627        SLOGE("Cannot seek to write persistent data");
628        goto err2;
629    }
630    if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
631        (int) crypt_ftr.persist_data_size) {
632        if (lseek(fd, erase_offset, SEEK_SET) < 0) {
633            SLOGE("Cannot seek to erase previous persistent data");
634            goto err2;
635        }
636        fsync(fd);
637        memset(pdata, 0, crypt_ftr.persist_data_size);
638        if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
639            (int) crypt_ftr.persist_data_size) {
640            SLOGE("Cannot write to erase previous persistent data");
641            goto err2;
642        }
643        fsync(fd);
644    } else {
645        SLOGE("Cannot write to save persistent data");
646        goto err2;
647    }
648
649    /* Success */
650    free(pdata);
651    close(fd);
652    return 0;
653
654err2:
655    free(pdata);
656err:
657    close(fd);
658    return -1;
659}
660
661/* Convert a binary key of specified length into an ascii hex string equivalent,
662 * without the leading 0x and with null termination
663 */
664void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
665                              char *master_key_ascii)
666{
667  unsigned int i, a;
668  unsigned char nibble;
669
670  for (i=0, a=0; i<keysize; i++, a+=2) {
671    /* For each byte, write out two ascii hex digits */
672    nibble = (master_key[i] >> 4) & 0xf;
673    master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
674
675    nibble = master_key[i] & 0xf;
676    master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
677  }
678
679  /* Add the null termination */
680  master_key_ascii[a] = '\0';
681
682}
683
684static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
685                                     char *real_blk_name, const char *name, int fd,
686                                     char *extra_params)
687{
688  char buffer[DM_CRYPT_BUF_SIZE];
689  struct dm_ioctl *io;
690  struct dm_target_spec *tgt;
691  char *crypt_params;
692  char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
693  int i;
694
695  io = (struct dm_ioctl *) buffer;
696
697  /* Load the mapping table for this device */
698  tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
699
700  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
701  io->target_count = 1;
702  tgt->status = 0;
703  tgt->sector_start = 0;
704  tgt->length = crypt_ftr->fs_size;
705  strcpy(tgt->target_type, "crypt");
706
707  crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
708  convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
709  sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
710          master_key_ascii, real_blk_name, extra_params);
711  crypt_params += strlen(crypt_params) + 1;
712  crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
713  tgt->next = crypt_params - buffer;
714
715  for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
716    if (! ioctl(fd, DM_TABLE_LOAD, io)) {
717      break;
718    }
719    usleep(500000);
720  }
721
722  if (i == TABLE_LOAD_RETRIES) {
723    /* We failed to load the table, return an error */
724    return -1;
725  } else {
726    return i + 1;
727  }
728}
729
730
731static int get_dm_crypt_version(int fd, const char *name,  int *version)
732{
733    char buffer[DM_CRYPT_BUF_SIZE];
734    struct dm_ioctl *io;
735    struct dm_target_versions *v;
736    int i;
737
738    io = (struct dm_ioctl *) buffer;
739
740    ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
741
742    if (ioctl(fd, DM_LIST_VERSIONS, io)) {
743        return -1;
744    }
745
746    /* Iterate over the returned versions, looking for name of "crypt".
747     * When found, get and return the version.
748     */
749    v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
750    while (v->next) {
751        if (! strcmp(v->name, "crypt")) {
752            /* We found the crypt driver, return the version, and get out */
753            version[0] = v->version[0];
754            version[1] = v->version[1];
755            version[2] = v->version[2];
756            return 0;
757        }
758        v = (struct dm_target_versions *)(((char *)v) + v->next);
759    }
760
761    return -1;
762}
763
764static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
765                                    char *real_blk_name, char *crypto_blk_name, const char *name)
766{
767  char buffer[DM_CRYPT_BUF_SIZE];
768  char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
769  char *crypt_params;
770  struct dm_ioctl *io;
771  struct dm_target_spec *tgt;
772  unsigned int minor;
773  int fd;
774  int i;
775  int retval = -1;
776  int version[3];
777  char *extra_params;
778  int load_count;
779
780  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
781    SLOGE("Cannot open device-mapper\n");
782    goto errout;
783  }
784
785  io = (struct dm_ioctl *) buffer;
786
787  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
788  if (ioctl(fd, DM_DEV_CREATE, io)) {
789    SLOGE("Cannot create dm-crypt device\n");
790    goto errout;
791  }
792
793  /* Get the device status, in particular, the name of it's device file */
794  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
795  if (ioctl(fd, DM_DEV_STATUS, io)) {
796    SLOGE("Cannot retrieve dm-crypt device status\n");
797    goto errout;
798  }
799  minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
800  snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
801
802  extra_params = "";
803  if (! get_dm_crypt_version(fd, name, version)) {
804      /* Support for allow_discards was added in version 1.11.0 */
805      if ((version[0] >= 2) ||
806          ((version[0] == 1) && (version[1] >= 11))) {
807          extra_params = "1 allow_discards";
808          SLOGI("Enabling support for allow_discards in dmcrypt.\n");
809      }
810  }
811
812  load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
813                                         fd, extra_params);
814  if (load_count < 0) {
815      SLOGE("Cannot load dm-crypt mapping table.\n");
816      goto errout;
817  } else if (load_count > 1) {
818      SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
819  }
820
821  /* Resume this device to activate it */
822  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
823
824  if (ioctl(fd, DM_DEV_SUSPEND, io)) {
825    SLOGE("Cannot resume the dm-crypt device\n");
826    goto errout;
827  }
828
829  /* We made it here with no errors.  Woot! */
830  retval = 0;
831
832errout:
833  close(fd);   /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
834
835  return retval;
836}
837
838static int delete_crypto_blk_dev(char *name)
839{
840  int fd;
841  char buffer[DM_CRYPT_BUF_SIZE];
842  struct dm_ioctl *io;
843  int retval = -1;
844
845  if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
846    SLOGE("Cannot open device-mapper\n");
847    goto errout;
848  }
849
850  io = (struct dm_ioctl *) buffer;
851
852  ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
853  if (ioctl(fd, DM_DEV_REMOVE, io)) {
854    SLOGE("Cannot remove dm-crypt device\n");
855    goto errout;
856  }
857
858  /* We made it here with no errors.  Woot! */
859  retval = 0;
860
861errout:
862  close(fd);    /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
863
864  return retval;
865
866}
867
868static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
869    /* Turn the password into a key and IV that can decrypt the master key */
870    PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
871                           HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
872}
873
874static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
875    struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
876
877    int N = 1 << ftr->N_factor;
878    int r = 1 << ftr->r_factor;
879    int p = 1 << ftr->p_factor;
880
881    /* Turn the password into a key and IV that can decrypt the master key */
882    crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
883            KEY_LEN_BYTES + IV_LEN_BYTES);
884}
885
886static int encrypt_master_key(char *passwd, unsigned char *salt,
887                              unsigned char *decrypted_master_key,
888                              unsigned char *encrypted_master_key,
889                              struct crypt_mnt_ftr *crypt_ftr)
890{
891    unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
892    EVP_CIPHER_CTX e_ctx;
893    int encrypted_len, final_len;
894
895    /* Turn the password into a key and IV that can decrypt the master key */
896    get_device_scrypt_params(crypt_ftr);
897    scrypt(passwd, salt, ikey, crypt_ftr);
898
899    /* Initialize the decryption engine */
900    if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
901        SLOGE("EVP_EncryptInit failed\n");
902        return -1;
903    }
904    EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
905
906    /* Encrypt the master key */
907    if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
908                              decrypted_master_key, KEY_LEN_BYTES)) {
909        SLOGE("EVP_EncryptUpdate failed\n");
910        return -1;
911    }
912    if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
913        SLOGE("EVP_EncryptFinal failed\n");
914        return -1;
915    }
916
917    if (encrypted_len + final_len != KEY_LEN_BYTES) {
918        SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
919        return -1;
920    } else {
921        return 0;
922    }
923}
924
925static int decrypt_master_key(char *passwd, unsigned char *salt,
926                              unsigned char *encrypted_master_key,
927                              unsigned char *decrypted_master_key,
928                              kdf_func kdf, void *kdf_params)
929{
930  unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
931  EVP_CIPHER_CTX d_ctx;
932  int decrypted_len, final_len;
933
934  /* Turn the password into a key and IV that can decrypt the master key */
935  kdf(passwd, salt, ikey, kdf_params);
936
937  /* Initialize the decryption engine */
938  if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
939    return -1;
940  }
941  EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
942  /* Decrypt the master key */
943  if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
944                            encrypted_master_key, KEY_LEN_BYTES)) {
945    return -1;
946  }
947  if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
948    return -1;
949  }
950
951  if (decrypted_len + final_len != KEY_LEN_BYTES) {
952    return -1;
953  } else {
954    return 0;
955  }
956}
957
958static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
959{
960    if (ftr->kdf_type == KDF_SCRYPT) {
961        *kdf = scrypt;
962        *kdf_params = ftr;
963    } else {
964        *kdf = pbkdf2;
965        *kdf_params = NULL;
966    }
967}
968
969static int decrypt_master_key_and_upgrade(char *passwd, unsigned char *decrypted_master_key,
970        struct crypt_mnt_ftr *crypt_ftr)
971{
972    kdf_func kdf;
973    void *kdf_params;
974    int ret;
975
976    get_kdf_func(crypt_ftr, &kdf, &kdf_params);
977    ret = decrypt_master_key(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
978            kdf_params);
979    if (ret != 0) {
980        SLOGW("failure decrypting master key");
981        return ret;
982    }
983
984    /*
985     * Upgrade if we're not using the latest KDF.
986     */
987    if (crypt_ftr->kdf_type != KDF_SCRYPT) {
988        crypt_ftr->kdf_type = KDF_SCRYPT;
989        encrypt_master_key(passwd, crypt_ftr->salt, decrypted_master_key, crypt_ftr->master_key,
990                crypt_ftr);
991        put_crypt_ftr_and_key(crypt_ftr);
992    }
993
994    return ret;
995}
996
997static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
998        struct crypt_mnt_ftr *crypt_ftr) {
999    int fd;
1000    unsigned char key_buf[KEY_LEN_BYTES];
1001    EVP_CIPHER_CTX e_ctx;
1002    int encrypted_len, final_len;
1003
1004    /* Get some random bits for a key */
1005    fd = open("/dev/urandom", O_RDONLY);
1006    read(fd, key_buf, sizeof(key_buf));
1007    read(fd, salt, SALT_LEN);
1008    close(fd);
1009
1010    /* Now encrypt it with the password */
1011    return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
1012}
1013
1014static int wait_and_unmount(char *mountpoint)
1015{
1016    int i, rc;
1017#define WAIT_UNMOUNT_COUNT 20
1018
1019    /*  Now umount the tmpfs filesystem */
1020    for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1021        if (umount(mountpoint)) {
1022            if (errno == EINVAL) {
1023                /* EINVAL is returned if the directory is not a mountpoint,
1024                 * i.e. there is no filesystem mounted there.  So just get out.
1025                 */
1026                break;
1027            }
1028            sleep(1);
1029            i++;
1030        } else {
1031          break;
1032        }
1033    }
1034
1035    if (i < WAIT_UNMOUNT_COUNT) {
1036      SLOGD("unmounting %s succeeded\n", mountpoint);
1037      rc = 0;
1038    } else {
1039      SLOGE("unmounting %s failed\n", mountpoint);
1040      rc = -1;
1041    }
1042
1043    return rc;
1044}
1045
1046#define DATA_PREP_TIMEOUT 200
1047static int prep_data_fs(void)
1048{
1049    int i;
1050
1051    /* Do the prep of the /data filesystem */
1052    property_set("vold.post_fs_data_done", "0");
1053    property_set("vold.decrypt", "trigger_post_fs_data");
1054    SLOGD("Just triggered post_fs_data\n");
1055
1056    /* Wait a max of 50 seconds, hopefully it takes much less */
1057    for (i=0; i<DATA_PREP_TIMEOUT; i++) {
1058        char p[PROPERTY_VALUE_MAX];
1059
1060        property_get("vold.post_fs_data_done", p, "0");
1061        if (*p == '1') {
1062            break;
1063        } else {
1064            usleep(250000);
1065        }
1066    }
1067    if (i == DATA_PREP_TIMEOUT) {
1068        /* Ugh, we failed to prep /data in time.  Bail. */
1069        SLOGE("post_fs_data timed out!\n");
1070        return -1;
1071    } else {
1072        SLOGD("post_fs_data done\n");
1073        return 0;
1074    }
1075}
1076
1077int cryptfs_restart(void)
1078{
1079    char fs_type[32];
1080    char real_blkdev[MAXPATHLEN];
1081    char crypto_blkdev[MAXPATHLEN];
1082    char fs_options[256];
1083    unsigned long mnt_flags;
1084    struct stat statbuf;
1085    int rc = -1, i;
1086    static int restart_successful = 0;
1087
1088    /* Validate that it's OK to call this routine */
1089    if (! master_key_saved) {
1090        SLOGE("Encrypted filesystem not validated, aborting");
1091        return -1;
1092    }
1093
1094    if (restart_successful) {
1095        SLOGE("System already restarted with encrypted disk, aborting");
1096        return -1;
1097    }
1098
1099    /* Here is where we shut down the framework.  The init scripts
1100     * start all services in one of three classes: core, main or late_start.
1101     * On boot, we start core and main.  Now, we stop main, but not core,
1102     * as core includes vold and a few other really important things that
1103     * we need to keep running.  Once main has stopped, we should be able
1104     * to umount the tmpfs /data, then mount the encrypted /data.
1105     * We then restart the class main, and also the class late_start.
1106     * At the moment, I've only put a few things in late_start that I know
1107     * are not needed to bring up the framework, and that also cause problems
1108     * with unmounting the tmpfs /data, but I hope to add add more services
1109     * to the late_start class as we optimize this to decrease the delay
1110     * till the user is asked for the password to the filesystem.
1111     */
1112
1113    /* The init files are setup to stop the class main when vold.decrypt is
1114     * set to trigger_reset_main.
1115     */
1116    property_set("vold.decrypt", "trigger_reset_main");
1117    SLOGD("Just asked init to shut down class main\n");
1118
1119    /* Ugh, shutting down the framework is not synchronous, so until it
1120     * can be fixed, this horrible hack will wait a moment for it all to
1121     * shut down before proceeding.  Without it, some devices cannot
1122     * restart the graphics services.
1123     */
1124    sleep(2);
1125
1126    /* Now that the framework is shutdown, we should be able to umount()
1127     * the tmpfs filesystem, and mount the real one.
1128     */
1129
1130    property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1131    if (strlen(crypto_blkdev) == 0) {
1132        SLOGE("fs_crypto_blkdev not set\n");
1133        return -1;
1134    }
1135
1136    if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1137        /* If that succeeded, then mount the decrypted filesystem */
1138        fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
1139
1140        property_set("vold.decrypt", "trigger_load_persist_props");
1141        /* Create necessary paths on /data */
1142        if (prep_data_fs()) {
1143            return -1;
1144        }
1145
1146        /* startup service classes main and late_start */
1147        property_set("vold.decrypt", "trigger_restart_framework");
1148        SLOGD("Just triggered restart_framework\n");
1149
1150        /* Give it a few moments to get started */
1151        sleep(1);
1152    }
1153
1154    if (rc == 0) {
1155        restart_successful = 1;
1156    }
1157
1158    return rc;
1159}
1160
1161static int do_crypto_complete(char *mount_point)
1162{
1163  struct crypt_mnt_ftr crypt_ftr;
1164  char encrypted_state[PROPERTY_VALUE_MAX];
1165  char key_loc[PROPERTY_VALUE_MAX];
1166
1167  property_get("ro.crypto.state", encrypted_state, "");
1168  if (strcmp(encrypted_state, "encrypted") ) {
1169    SLOGE("not running with encryption, aborting");
1170    return 1;
1171  }
1172
1173  if (get_crypt_ftr_and_key(&crypt_ftr)) {
1174    fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
1175
1176    /*
1177     * Only report this error if key_loc is a file and it exists.
1178     * If the device was never encrypted, and /data is not mountable for
1179     * some reason, returning 1 should prevent the UI from presenting the
1180     * a "enter password" screen, or worse, a "press button to wipe the
1181     * device" screen.
1182     */
1183    if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1184      SLOGE("master key file does not exist, aborting");
1185      return 1;
1186    } else {
1187      SLOGE("Error getting crypt footer and key\n");
1188      return -1;
1189    }
1190  }
1191
1192  if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1193    SLOGE("Encryption process didn't finish successfully\n");
1194    return -2;  /* -2 is the clue to the UI that there is no usable data on the disk,
1195                 * and give the user an option to wipe the disk */
1196  }
1197
1198  /* We passed the test! We shall diminish, and return to the west */
1199  return 0;
1200}
1201
1202static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
1203{
1204  struct crypt_mnt_ftr crypt_ftr;
1205  /* Allocate enough space for a 256 bit key, but we may use less */
1206  unsigned char decrypted_master_key[32];
1207  char crypto_blkdev[MAXPATHLEN];
1208  char real_blkdev[MAXPATHLEN];
1209  char tmp_mount_point[64];
1210  unsigned int orig_failed_decrypt_count;
1211  char encrypted_state[PROPERTY_VALUE_MAX];
1212  int rc;
1213  kdf_func kdf;
1214  void *kdf_params;
1215
1216  property_get("ro.crypto.state", encrypted_state, "");
1217  if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1218    SLOGE("encrypted fs already validated or not running with encryption, aborting");
1219    return -1;
1220  }
1221
1222  fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1223
1224  if (get_crypt_ftr_and_key(&crypt_ftr)) {
1225    SLOGE("Error getting crypt footer and key\n");
1226    return -1;
1227  }
1228
1229  SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1230  orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1231
1232  if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1233    decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
1234  }
1235
1236  if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
1237                               real_blkdev, crypto_blkdev, label)) {
1238    SLOGE("Error creating decrypted block device\n");
1239    return -1;
1240  }
1241
1242  /* If init detects an encrypted filesystem, it writes a file for each such
1243   * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1244   * files and passes that data to me */
1245  /* Create a tmp mount point to try mounting the decryptd fs
1246   * Since we're here, the mount_point should be a tmpfs filesystem, so make
1247   * a directory in it to test mount the decrypted filesystem.
1248   */
1249  sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1250  mkdir(tmp_mount_point, 0755);
1251  if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1252    SLOGE("Error temp mounting decrypted block device\n");
1253    delete_crypto_blk_dev(label);
1254    crypt_ftr.failed_decrypt_count++;
1255  } else {
1256    /* Success, so just umount and we'll mount it properly when we restart
1257     * the framework.
1258     */
1259    umount(tmp_mount_point);
1260    crypt_ftr.failed_decrypt_count  = 0;
1261  }
1262
1263  if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
1264    put_crypt_ftr_and_key(&crypt_ftr);
1265  }
1266
1267  if (crypt_ftr.failed_decrypt_count) {
1268    /* We failed to mount the device, so return an error */
1269    rc = crypt_ftr.failed_decrypt_count;
1270
1271  } else {
1272    /* Woot!  Success!  Save the name of the crypto block device
1273     * so we can mount it when restarting the framework.
1274     */
1275    property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1276
1277    /* Also save a the master key so we can reencrypted the key
1278     * the key when we want to change the password on it.
1279     */
1280    memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
1281    saved_mount_point = strdup(mount_point);
1282    master_key_saved = 1;
1283    rc = 0;
1284  }
1285
1286  return rc;
1287}
1288
1289/* Called by vold when it wants to undo the crypto mapping of a volume it
1290 * manages.  This is usually in response to a factory reset, when we want
1291 * to undo the crypto mapping so the volume is formatted in the clear.
1292 */
1293int cryptfs_revert_volume(const char *label)
1294{
1295    return delete_crypto_blk_dev((char *)label);
1296}
1297
1298/*
1299 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1300 * Setup a dm-crypt mapping, use the saved master key from
1301 * setting up the /data mapping, and return the new device path.
1302 */
1303int cryptfs_setup_volume(const char *label, int major, int minor,
1304                         char *crypto_sys_path, unsigned int max_path,
1305                         int *new_major, int *new_minor)
1306{
1307    char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1308    struct crypt_mnt_ftr sd_crypt_ftr;
1309    struct stat statbuf;
1310    int nr_sec, fd;
1311
1312    sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1313
1314    get_crypt_ftr_and_key(&sd_crypt_ftr);
1315
1316    /* Update the fs_size field to be the size of the volume */
1317    fd = open(real_blkdev, O_RDONLY);
1318    nr_sec = get_blkdev_size(fd);
1319    close(fd);
1320    if (nr_sec == 0) {
1321        SLOGE("Cannot get size of volume %s\n", real_blkdev);
1322        return -1;
1323    }
1324
1325    sd_crypt_ftr.fs_size = nr_sec;
1326    create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1327                          crypto_blkdev, label);
1328
1329    stat(crypto_blkdev, &statbuf);
1330    *new_major = MAJOR(statbuf.st_rdev);
1331    *new_minor = MINOR(statbuf.st_rdev);
1332
1333    /* Create path to sys entry for this block device */
1334    snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1335
1336    return 0;
1337}
1338
1339int cryptfs_crypto_complete(void)
1340{
1341  return do_crypto_complete("/data");
1342}
1343
1344int cryptfs_check_passwd(char *passwd)
1345{
1346    int rc = -1;
1347
1348    rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
1349
1350    return rc;
1351}
1352
1353int cryptfs_verify_passwd(char *passwd)
1354{
1355    struct crypt_mnt_ftr crypt_ftr;
1356    /* Allocate enough space for a 256 bit key, but we may use less */
1357    unsigned char decrypted_master_key[32];
1358    char encrypted_state[PROPERTY_VALUE_MAX];
1359    int rc;
1360
1361    property_get("ro.crypto.state", encrypted_state, "");
1362    if (strcmp(encrypted_state, "encrypted") ) {
1363        SLOGE("device not encrypted, aborting");
1364        return -2;
1365    }
1366
1367    if (!master_key_saved) {
1368        SLOGE("encrypted fs not yet mounted, aborting");
1369        return -1;
1370    }
1371
1372    if (!saved_mount_point) {
1373        SLOGE("encrypted fs failed to save mount point, aborting");
1374        return -1;
1375    }
1376
1377    if (get_crypt_ftr_and_key(&crypt_ftr)) {
1378        SLOGE("Error getting crypt footer and key\n");
1379        return -1;
1380    }
1381
1382    if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1383        /* If the device has no password, then just say the password is valid */
1384        rc = 0;
1385    } else {
1386        decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
1387        if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1388            /* They match, the password is correct */
1389            rc = 0;
1390        } else {
1391            /* If incorrect, sleep for a bit to prevent dictionary attacks */
1392            sleep(1);
1393            rc = 1;
1394        }
1395    }
1396
1397    return rc;
1398}
1399
1400/* Initialize a crypt_mnt_ftr structure.  The keysize is
1401 * defaulted to 16 bytes, and the filesystem size to 0.
1402 * Presumably, at a minimum, the caller will update the
1403 * filesystem size and crypto_type_name after calling this function.
1404 */
1405static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1406{
1407    off64_t off;
1408
1409    memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
1410    ftr->magic = CRYPT_MNT_MAGIC;
1411    ftr->major_version = CURRENT_MAJOR_VERSION;
1412    ftr->minor_version = CURRENT_MINOR_VERSION;
1413    ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
1414    ftr->keysize = KEY_LEN_BYTES;
1415
1416    ftr->kdf_type = KDF_SCRYPT;
1417    get_device_scrypt_params(ftr);
1418
1419    ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1420    if (get_crypt_ftr_info(NULL, &off) == 0) {
1421        ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1422        ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1423                                    ftr->persist_data_size;
1424    }
1425}
1426
1427static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
1428{
1429    const char *args[10];
1430    char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1431    int num_args;
1432    int status;
1433    int tmp;
1434    int rc = -1;
1435
1436    if (type == EXT4_FS) {
1437        args[0] = "/system/bin/make_ext4fs";
1438        args[1] = "-a";
1439        args[2] = "/data";
1440        args[3] = "-l";
1441        snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1442        args[4] = size_str;
1443        args[5] = crypto_blkdev;
1444        num_args = 6;
1445        SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1446              args[0], args[1], args[2], args[3], args[4], args[5]);
1447    } else if (type== FAT_FS) {
1448        args[0] = "/system/bin/newfs_msdos";
1449        args[1] = "-F";
1450        args[2] = "32";
1451        args[3] = "-O";
1452        args[4] = "android";
1453        args[5] = "-c";
1454        args[6] = "8";
1455        args[7] = "-s";
1456        snprintf(size_str, sizeof(size_str), "%lld", size);
1457        args[8] = size_str;
1458        args[9] = crypto_blkdev;
1459        num_args = 10;
1460        SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1461              args[0], args[1], args[2], args[3], args[4], args[5],
1462              args[6], args[7], args[8], args[9]);
1463    } else {
1464        SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1465        return -1;
1466    }
1467
1468    tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1469
1470    if (tmp != 0) {
1471      SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
1472    } else {
1473        if (WIFEXITED(status)) {
1474            if (WEXITSTATUS(status)) {
1475                SLOGE("Error creating filesystem on %s, exit status %d ",
1476                      crypto_blkdev, WEXITSTATUS(status));
1477            } else {
1478                SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1479                rc = 0;
1480            }
1481        } else {
1482            SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1483       }
1484    }
1485
1486    return rc;
1487}
1488
1489#define CRYPT_INPLACE_BUFSIZE 4096
1490#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
1491static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1492                                  off64_t *size_already_done, off64_t tot_size)
1493{
1494    int realfd, cryptofd;
1495    char *buf[CRYPT_INPLACE_BUFSIZE];
1496    int rc = -1;
1497    off64_t numblocks, i, remainder;
1498    off64_t one_pct, cur_pct, new_pct;
1499    off64_t blocks_already_done, tot_numblocks;
1500
1501    if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1502        SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1503        return -1;
1504    }
1505
1506    if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1507        SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1508        close(realfd);
1509        return -1;
1510    }
1511
1512    /* This is pretty much a simple loop of reading 4K, and writing 4K.
1513     * The size passed in is the number of 512 byte sectors in the filesystem.
1514     * So compute the number of whole 4K blocks we should read/write,
1515     * and the remainder.
1516     */
1517    numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1518    remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
1519    tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1520    blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1521
1522    SLOGE("Encrypting filesystem in place...");
1523
1524    one_pct = tot_numblocks / 100;
1525    cur_pct = 0;
1526    /* process the majority of the filesystem in blocks */
1527    for (i=0; i<numblocks; i++) {
1528        new_pct = (i + blocks_already_done) / one_pct;
1529        if (new_pct > cur_pct) {
1530            char buf[8];
1531
1532            cur_pct = new_pct;
1533            snprintf(buf, sizeof(buf), "%lld", cur_pct);
1534            property_set("vold.encrypt_progress", buf);
1535        }
1536        if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1537            SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1538            goto errout;
1539        }
1540        if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1541            SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1542            goto errout;
1543        }
1544    }
1545
1546    /* Do any remaining sectors */
1547    for (i=0; i<remainder; i++) {
1548        if (unix_read(realfd, buf, 512) <= 0) {
1549            SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1550            goto errout;
1551        }
1552        if (unix_write(cryptofd, buf, 512) <= 0) {
1553            SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1554            goto errout;
1555        }
1556    }
1557
1558    *size_already_done += size;
1559    rc = 0;
1560
1561errout:
1562    close(realfd);
1563    close(cryptofd);
1564
1565    return rc;
1566}
1567
1568#define CRYPTO_ENABLE_WIPE 1
1569#define CRYPTO_ENABLE_INPLACE 2
1570
1571#define FRAMEWORK_BOOT_WAIT 60
1572
1573static inline int should_encrypt(struct volume_info *volume)
1574{
1575    return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1576            (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1577}
1578
1579int cryptfs_enable(char *howarg, char *passwd)
1580{
1581    int how = 0;
1582    char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
1583    unsigned long nr_sec;
1584    unsigned char decrypted_master_key[KEY_LEN_BYTES];
1585    int rc=-1, fd, i, ret;
1586    struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
1587    struct crypt_persist_data *pdata;
1588    char tmpfs_options[PROPERTY_VALUE_MAX];
1589    char encrypted_state[PROPERTY_VALUE_MAX];
1590    char lockid[32] = { 0 };
1591    char key_loc[PROPERTY_VALUE_MAX];
1592    char fuse_sdcard[PROPERTY_VALUE_MAX];
1593    char *sd_mnt_point;
1594    char sd_blk_dev[256] = { 0 };
1595    int num_vols;
1596    struct volume_info *vol_list = 0;
1597    off64_t cur_encryption_done=0, tot_encryption_size=0;
1598
1599    property_get("ro.crypto.state", encrypted_state, "");
1600    if (strcmp(encrypted_state, "unencrypted")) {
1601        SLOGE("Device is already running encrypted, aborting");
1602        goto error_unencrypted;
1603    }
1604
1605    fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
1606
1607    if (!strcmp(howarg, "wipe")) {
1608      how = CRYPTO_ENABLE_WIPE;
1609    } else if (! strcmp(howarg, "inplace")) {
1610      how = CRYPTO_ENABLE_INPLACE;
1611    } else {
1612      /* Shouldn't happen, as CommandListener vets the args */
1613      goto error_unencrypted;
1614    }
1615
1616    fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1617
1618    /* Get the size of the real block device */
1619    fd = open(real_blkdev, O_RDONLY);
1620    if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1621        SLOGE("Cannot get size of block device %s\n", real_blkdev);
1622        goto error_unencrypted;
1623    }
1624    close(fd);
1625
1626    /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
1627    if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
1628        unsigned int fs_size_sec, max_fs_size_sec;
1629
1630        fs_size_sec = get_fs_size(real_blkdev);
1631        max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1632
1633        if (fs_size_sec > max_fs_size_sec) {
1634            SLOGE("Orig filesystem overlaps crypto footer region.  Cannot encrypt in place.");
1635            goto error_unencrypted;
1636        }
1637    }
1638
1639    /* Get a wakelock as this may take a while, and we don't want the
1640     * device to sleep on us.  We'll grab a partial wakelock, and if the UI
1641     * wants to keep the screen on, it can grab a full wakelock.
1642     */
1643    snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
1644    acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1645
1646    /* Get the sdcard mount point */
1647    sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
1648    if (!sd_mnt_point) {
1649       sd_mnt_point = getenv("EXTERNAL_STORAGE");
1650    }
1651    if (!sd_mnt_point) {
1652        sd_mnt_point = "/mnt/sdcard";
1653    }
1654
1655    num_vols=vold_getNumDirectVolumes();
1656    vol_list = malloc(sizeof(struct volume_info) * num_vols);
1657    vold_getDirectVolumeList(vol_list);
1658
1659    for (i=0; i<num_vols; i++) {
1660        if (should_encrypt(&vol_list[i])) {
1661            fd = open(vol_list[i].blk_dev, O_RDONLY);
1662            if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1663                SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1664                goto error_unencrypted;
1665            }
1666            close(fd);
1667
1668            ret=vold_disableVol(vol_list[i].label);
1669            if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1670                /* -2 is returned when the device exists but is not currently mounted.
1671                 * ignore the error and continue. */
1672                SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1673                goto error_unencrypted;
1674            }
1675        }
1676    }
1677
1678    /* The init files are setup to stop the class main and late start when
1679     * vold sets trigger_shutdown_framework.
1680     */
1681    property_set("vold.decrypt", "trigger_shutdown_framework");
1682    SLOGD("Just asked init to shut down class main\n");
1683
1684    if (vold_unmountAllAsecs()) {
1685        /* Just report the error.  If any are left mounted,
1686         * umounting /data below will fail and handle the error.
1687         */
1688        SLOGE("Error unmounting internal asecs");
1689    }
1690
1691    property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1692    if (!strcmp(fuse_sdcard, "true")) {
1693        /* This is a device using the fuse layer to emulate the sdcard semantics
1694         * on top of the userdata partition.  vold does not manage it, it is managed
1695         * by the sdcard service.  The sdcard service was killed by the property trigger
1696         * above, so just unmount it now.  We must do this _AFTER_ killing the framework,
1697         * unlike the case for vold managed devices above.
1698         */
1699        if (wait_and_unmount(sd_mnt_point)) {
1700            goto error_shutting_down;
1701        }
1702    }
1703
1704    /* Now unmount the /data partition. */
1705    if (wait_and_unmount(DATA_MNT_POINT)) {
1706        goto error_shutting_down;
1707    }
1708
1709    /* Do extra work for a better UX when doing the long inplace encryption */
1710    if (how == CRYPTO_ENABLE_INPLACE) {
1711        /* Now that /data is unmounted, we need to mount a tmpfs
1712         * /data, set a property saying we're doing inplace encryption,
1713         * and restart the framework.
1714         */
1715        if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1716            goto error_shutting_down;
1717        }
1718        /* Tells the framework that inplace encryption is starting */
1719        property_set("vold.encrypt_progress", "0");
1720
1721        /* restart the framework. */
1722        /* Create necessary paths on /data */
1723        if (prep_data_fs()) {
1724            goto error_shutting_down;
1725        }
1726
1727        /* Ugh, shutting down the framework is not synchronous, so until it
1728         * can be fixed, this horrible hack will wait a moment for it all to
1729         * shut down before proceeding.  Without it, some devices cannot
1730         * restart the graphics services.
1731         */
1732        sleep(2);
1733
1734        /* startup service classes main and late_start */
1735        property_set("vold.decrypt", "trigger_restart_min_framework");
1736        SLOGD("Just triggered restart_min_framework\n");
1737
1738        /* OK, the framework is restarted and will soon be showing a
1739         * progress bar.  Time to setup an encrypted mapping, and
1740         * either write a new filesystem, or encrypt in place updating
1741         * the progress bar as we work.
1742         */
1743    }
1744
1745    /* Start the actual work of making an encrypted filesystem */
1746    /* Initialize a crypt_mnt_ftr for the partition */
1747    cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
1748
1749    if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1750        crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1751    } else {
1752        crypt_ftr.fs_size = nr_sec;
1753    }
1754    crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
1755    strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1756
1757    /* Make an encrypted master key */
1758    if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
1759        SLOGE("Cannot create encrypted master key\n");
1760        goto error_unencrypted;
1761    }
1762
1763    /* Write the key to the end of the partition */
1764    put_crypt_ftr_and_key(&crypt_ftr);
1765
1766    /* If any persistent data has been remembered, save it.
1767     * If none, create a valid empty table and save that.
1768     */
1769    if (!persist_data) {
1770       pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1771       if (pdata) {
1772           init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1773           persist_data = pdata;
1774       }
1775    }
1776    if (persist_data) {
1777        save_persistent_data();
1778    }
1779
1780    decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
1781    create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1782                          "userdata");
1783
1784    /* The size of the userdata partition, and add in the vold volumes below */
1785    tot_encryption_size = crypt_ftr.fs_size;
1786
1787    /* setup crypto mapping for all encryptable volumes handled by vold */
1788    for (i=0; i<num_vols; i++) {
1789        if (should_encrypt(&vol_list[i])) {
1790            vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1791            vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1792            create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1793                                  vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1794                                  vol_list[i].label);
1795            tot_encryption_size += vol_list[i].size;
1796        }
1797    }
1798
1799    if (how == CRYPTO_ENABLE_WIPE) {
1800        rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1801        /* Encrypt all encryptable volumes handled by vold */
1802        if (!rc) {
1803            for (i=0; i<num_vols; i++) {
1804                if (should_encrypt(&vol_list[i])) {
1805                    rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1806                                             vol_list[i].crypt_ftr.fs_size, FAT_FS);
1807                }
1808            }
1809        }
1810    } else if (how == CRYPTO_ENABLE_INPLACE) {
1811        rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1812                                    &cur_encryption_done, tot_encryption_size);
1813        /* Encrypt all encryptable volumes handled by vold */
1814        if (!rc) {
1815            for (i=0; i<num_vols; i++) {
1816                if (should_encrypt(&vol_list[i])) {
1817                    rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1818                                                vol_list[i].blk_dev,
1819                                                vol_list[i].crypt_ftr.fs_size,
1820                                                &cur_encryption_done, tot_encryption_size);
1821                }
1822            }
1823        }
1824        if (!rc) {
1825            /* The inplace routine never actually sets the progress to 100%
1826             * due to the round down nature of integer division, so set it here */
1827            property_set("vold.encrypt_progress", "100");
1828        }
1829    } else {
1830        /* Shouldn't happen */
1831        SLOGE("cryptfs_enable: internal error, unknown option\n");
1832        goto error_unencrypted;
1833    }
1834
1835    /* Undo the dm-crypt mapping whether we succeed or not */
1836    delete_crypto_blk_dev("userdata");
1837    for (i=0; i<num_vols; i++) {
1838        if (should_encrypt(&vol_list[i])) {
1839            delete_crypto_blk_dev(vol_list[i].label);
1840        }
1841    }
1842
1843    free(vol_list);
1844
1845    if (! rc) {
1846        /* Success */
1847
1848        /* Clear the encryption in progres flag in the footer */
1849        crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
1850        put_crypt_ftr_and_key(&crypt_ftr);
1851
1852        sleep(2); /* Give the UI a chance to show 100% progress */
1853        cryptfs_reboot(0);
1854    } else {
1855        char value[PROPERTY_VALUE_MAX];
1856
1857        property_get("ro.vold.wipe_on_crypt_fail", value, "0");
1858        if (!strcmp(value, "1")) {
1859            /* wipe data if encryption failed */
1860            SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1861            mkdir("/cache/recovery", 0700);
1862            int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
1863            if (fd >= 0) {
1864                write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1865                close(fd);
1866            } else {
1867                SLOGE("could not open /cache/recovery/command\n");
1868            }
1869            cryptfs_reboot(1);
1870        } else {
1871            /* set property to trigger dialog */
1872            property_set("vold.encrypt_progress", "error_partially_encrypted");
1873            release_wake_lock(lockid);
1874        }
1875        return -1;
1876    }
1877
1878    /* hrm, the encrypt step claims success, but the reboot failed.
1879     * This should not happen.
1880     * Set the property and return.  Hope the framework can deal with it.
1881     */
1882    property_set("vold.encrypt_progress", "error_reboot_failed");
1883    release_wake_lock(lockid);
1884    return rc;
1885
1886error_unencrypted:
1887    free(vol_list);
1888    property_set("vold.encrypt_progress", "error_not_encrypted");
1889    if (lockid[0]) {
1890        release_wake_lock(lockid);
1891    }
1892    return -1;
1893
1894error_shutting_down:
1895    /* we failed, and have not encrypted anthing, so the users's data is still intact,
1896     * but the framework is stopped and not restarted to show the error, so it's up to
1897     * vold to restart the system.
1898     */
1899    SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
1900    cryptfs_reboot(0);
1901
1902    /* shouldn't get here */
1903    property_set("vold.encrypt_progress", "error_shutting_down");
1904    free(vol_list);
1905    if (lockid[0]) {
1906        release_wake_lock(lockid);
1907    }
1908    return -1;
1909}
1910
1911int cryptfs_changepw(char *newpw)
1912{
1913    struct crypt_mnt_ftr crypt_ftr;
1914    unsigned char decrypted_master_key[KEY_LEN_BYTES];
1915
1916    /* This is only allowed after we've successfully decrypted the master key */
1917    if (! master_key_saved) {
1918        SLOGE("Key not saved, aborting");
1919        return -1;
1920    }
1921
1922    /* get key */
1923    if (get_crypt_ftr_and_key(&crypt_ftr)) {
1924      SLOGE("Error getting crypt footer and key");
1925      return -1;
1926    }
1927
1928    encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
1929
1930    /* save the key */
1931    put_crypt_ftr_and_key(&crypt_ftr);
1932
1933    return 0;
1934}
1935
1936static int persist_get_key(char *fieldname, char *value)
1937{
1938    unsigned int i;
1939
1940    if (persist_data == NULL) {
1941        return -1;
1942    }
1943    for (i = 0; i < persist_data->persist_valid_entries; i++) {
1944        if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1945            /* We found it! */
1946            strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1947            return 0;
1948        }
1949    }
1950
1951    return -1;
1952}
1953
1954static int persist_set_key(char *fieldname, char *value, int encrypted)
1955{
1956    unsigned int i;
1957    unsigned int num;
1958    struct crypt_mnt_ftr crypt_ftr;
1959    unsigned int max_persistent_entries;
1960    unsigned int dsize;
1961
1962    if (persist_data == NULL) {
1963        return -1;
1964    }
1965
1966    /* If encrypted, use the values from the crypt_ftr, otherwise
1967     * use the values for the current spec.
1968     */
1969    if (encrypted) {
1970        if(get_crypt_ftr_and_key(&crypt_ftr)) {
1971            return -1;
1972        }
1973        dsize = crypt_ftr.persist_data_size;
1974    } else {
1975        dsize = CRYPT_PERSIST_DATA_SIZE;
1976    }
1977    max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1978                             sizeof(struct crypt_persist_entry);
1979
1980    num = persist_data->persist_valid_entries;
1981
1982    for (i = 0; i < num; i++) {
1983        if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1984            /* We found an existing entry, update it! */
1985            memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1986            strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1987            return 0;
1988        }
1989    }
1990
1991    /* We didn't find it, add it to the end, if there is room */
1992    if (persist_data->persist_valid_entries < max_persistent_entries) {
1993        memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
1994        strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
1995        strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
1996        persist_data->persist_valid_entries++;
1997        return 0;
1998    }
1999
2000    return -1;
2001}
2002
2003/* Return the value of the specified field. */
2004int cryptfs_getfield(char *fieldname, char *value, int len)
2005{
2006    char temp_value[PROPERTY_VALUE_MAX];
2007    char real_blkdev[MAXPATHLEN];
2008    /* 0 is success, 1 is not encrypted,
2009     * -1 is value not set, -2 is any other error
2010     */
2011    int rc = -2;
2012
2013    if (persist_data == NULL) {
2014        load_persistent_data();
2015        if (persist_data == NULL) {
2016            SLOGE("Getfield error, cannot load persistent data");
2017            goto out;
2018        }
2019    }
2020
2021    if (!persist_get_key(fieldname, temp_value)) {
2022        /* We found it, copy it to the caller's buffer and return */
2023        strlcpy(value, temp_value, len);
2024        rc = 0;
2025    } else {
2026        /* Sadness, it's not there.  Return the error */
2027        rc = -1;
2028    }
2029
2030out:
2031    return rc;
2032}
2033
2034/* Set the value of the specified field. */
2035int cryptfs_setfield(char *fieldname, char *value)
2036{
2037    struct crypt_persist_data stored_pdata;
2038    struct crypt_persist_data *pdata_p;
2039    struct crypt_mnt_ftr crypt_ftr;
2040    char encrypted_state[PROPERTY_VALUE_MAX];
2041    /* 0 is success, -1 is an error */
2042    int rc = -1;
2043    int encrypted = 0;
2044
2045    if (persist_data == NULL) {
2046        load_persistent_data();
2047        if (persist_data == NULL) {
2048            SLOGE("Setfield error, cannot load persistent data");
2049            goto out;
2050        }
2051    }
2052
2053    property_get("ro.crypto.state", encrypted_state, "");
2054    if (!strcmp(encrypted_state, "encrypted") ) {
2055        encrypted = 1;
2056    }
2057
2058    if (persist_set_key(fieldname, value, encrypted)) {
2059        goto out;
2060    }
2061
2062    /* If we are running encrypted, save the persistent data now */
2063    if (encrypted) {
2064        if (save_persistent_data()) {
2065            SLOGE("Setfield error, cannot save persistent data");
2066            goto out;
2067        }
2068    }
2069
2070    rc = 0;
2071
2072out:
2073    return rc;
2074}
2075