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