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