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