2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
23 #include <sys/types.h>
31 #include <sys/ioctl.h>
32 #include <linux/dm-ioctl.h>
35 #include <sys/param.h>
37 #include <sys/mount.h>
38 #include <openssl/evp.h>
39 #include <openssl/sha.h>
41 #include <ext4_utils/ext4.h>
42 #include <ext4_utils/ext4_utils.h>
43 #include <linux/kdev_t.h>
47 #include <selinux/selinux.h>
49 #include "secontext.h"
50 #define LOG_TAG "Cryptfs"
51 #include "cutils/log.h"
52 #include "cutils/properties.h"
53 #include "cutils/android_reboot.h"
54 #include "hardware_legacy/power.h"
55 #include <logwrap/logwrap.h>
56 #include "ScryptParameters.h"
57 #include "VolumeManager.h"
59 #include "Ext4Crypt.h"
60 #include "f2fs_sparseblock.h"
61 #include "CheckBattery.h"
63 #include "Keymaster.h"
64 #include "android-base/properties.h"
65 #include <bootloader_message/bootloader_message.h>
67 #include <crypto_scrypt.h>
70 #define UNUSED __attribute__((unused))
72 #define DM_CRYPT_BUF_SIZE 4096
74 #define HASH_COUNT 2000
75 #define KEY_LEN_BYTES 16
76 #define IV_LEN_BYTES 16
78 #define KEY_IN_FOOTER "footer"
80 #define DEFAULT_PASSWORD "default_password"
82 #define CRYPTO_BLOCK_DEVICE "userdata"
84 #define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
89 #define TABLE_LOAD_RETRIES 10
91 #define RSA_KEY_SIZE 2048
92 #define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
93 #define RSA_EXPONENT 0x10001
94 #define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
96 #define RETRY_MOUNT_ATTEMPTS 10
97 #define RETRY_MOUNT_DELAY_SECONDS 1
99 static unsigned char saved_master_key[KEY_LEN_BYTES];
100 static char *saved_mount_point;
101 static int master_key_saved = 0;
102 static struct crypt_persist_data *persist_data = NULL;
104 /* Should we use keymaster? */
105 static int keymaster_check_compatibility()
107 return keymaster_compatibility_cryptfs_scrypt();
110 /* Create a new keymaster key and store it in this footer */
111 static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
113 if (ftr->keymaster_blob_size) {
114 SLOGI("Already have key");
118 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
119 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
120 &ftr->keymaster_blob_size);
122 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
123 SLOGE("Keymaster key blob to large)");
124 ftr->keymaster_blob_size = 0;
126 SLOGE("Failed to generate keypair");
132 /* This signs the given object using the keymaster key. */
133 static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
134 const unsigned char *object,
135 const size_t object_size,
136 unsigned char **signature,
137 size_t *signature_size)
139 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
140 size_t to_sign_size = sizeof(to_sign);
141 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
143 // To sign a message with RSA, the message must satisfy two
146 // 1. The message, when interpreted as a big-endian numeric value, must
147 // be strictly less than the public modulus of the RSA key. Note
148 // that because the most significant bit of the public modulus is
149 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
150 // key), an n-bit message with most significant bit 0 always
151 // satisfies this requirement.
153 // 2. The message must have the same length in bits as the public
154 // modulus of the RSA key. This requirement isn't mathematically
155 // necessary, but is necessary to ensure consistency in
157 switch (ftr->kdf_type) {
158 case KDF_SCRYPT_KEYMASTER:
159 // This ensures the most significant byte of the signed message
160 // is zero. We could have zero-padded to the left instead, but
161 // this approach is slightly more robust against changes in
162 // object size. However, it's still broken (but not unusably
163 // so) because we really should be using a proper deterministic
164 // RSA padding function, such as PKCS1.
165 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
166 SLOGI("Signing safely-padded object");
169 SLOGE("Unknown KDF type %d", ftr->kdf_type);
172 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
173 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
176 /* Store password when userdata is successfully decrypted and mounted.
177 * Cleared by cryptfs_clear_password
179 * To avoid a double prompt at boot, we need to store the CryptKeeper
180 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
181 * Since the entire framework is torn down and rebuilt after encryption,
182 * we have to use a daemon or similar to store the password. Since vold
183 * is secured against IPC except from system processes, it seems a reasonable
184 * place to store this.
186 * password should be cleared once it has been used.
188 * password is aged out after password_max_age_seconds seconds.
190 static char* password = 0;
191 static int password_expiry_time = 0;
192 static const int password_max_age_seconds = 60;
194 extern struct fstab *fstab;
196 enum RebootType {reboot, recovery, shutdown};
197 static void cryptfs_reboot(enum RebootType rt)
201 property_set(ANDROID_RB_PROPERTY, "reboot");
205 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
209 property_set(ANDROID_RB_PROPERTY, "shutdown");
215 /* Shouldn't get here, reboot should happen before sleep times out */
219 static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
221 memset(io, 0, dataSize);
222 io->data_size = dataSize;
223 io->data_start = sizeof(struct dm_ioctl);
229 strlcpy(io->name, name, sizeof(io->name));
234 * Gets the default device scrypt parameters for key derivation time tuning.
235 * The parameters should lead to about one second derivation time for the
238 static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
239 char paramstr[PROPERTY_VALUE_MAX];
242 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
243 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
244 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
245 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
252 static unsigned int get_fs_size(char *dev)
255 struct ext4_super_block sb;
258 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
259 SLOGE("Cannot open device to get filesystem size ");
263 if (lseek64(fd, 1024, SEEK_SET) < 0) {
264 SLOGE("Cannot seek to superblock");
268 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
269 SLOGE("Cannot read superblock");
275 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
276 SLOGE("Not a valid ext4 superblock");
279 block_size = 1024 << sb.s_log_block_size;
280 /* compute length in bytes */
281 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
283 /* return length in sectors */
284 return (unsigned int) (len / 512);
287 static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
289 static int cached_data = 0;
290 static off64_t cached_off = 0;
291 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
293 char key_loc[PROPERTY_VALUE_MAX];
294 char real_blkdev[PROPERTY_VALUE_MAX];
298 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
300 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
301 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
302 SLOGE("Cannot open real block device %s\n", real_blkdev);
306 unsigned long nr_sec = 0;
307 get_blkdev_size(fd, &nr_sec);
309 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
310 * encryption info footer and key, and plenty of bytes to spare for future
313 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
314 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
317 SLOGE("Cannot get size of block device %s\n", real_blkdev);
321 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
328 if (metadata_fname) {
329 *metadata_fname = cached_metadata_fname;
340 /* Set sha256 checksum in structure */
341 static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
345 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
346 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
347 SHA256_Final(crypt_ftr->sha256, &c);
350 /* key or salt can be NULL, in which case just skip writing that value. Useful to
351 * update the failed mount count but not change the key.
353 static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
357 /* starting_off is set to the SEEK_SET offset
358 * where the crypto structure starts
360 off64_t starting_off;
365 set_ftr_sha(crypt_ftr);
367 if (get_crypt_ftr_info(&fname, &starting_off)) {
368 SLOGE("Unable to get crypt_ftr_info\n");
371 if (fname[0] != '/') {
372 SLOGE("Unexpected value for crypto key location\n");
375 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
376 SLOGE("Cannot open footer file %s for put\n", fname);
380 /* Seek to the start of the crypt footer */
381 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
382 SLOGE("Cannot seek to real block device footer\n");
386 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
387 SLOGE("Cannot write real block device footer\n");
392 /* If the keys are kept on a raw block device, do not try to truncate it. */
393 if (S_ISREG(statbuf.st_mode)) {
394 if (ftruncate(fd, 0x4000)) {
395 SLOGE("Cannot set footer file size\n");
409 static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
411 struct crypt_mnt_ftr copy;
412 memcpy(©, crypt_ftr, sizeof(copy));
414 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
417 static inline int unix_read(int fd, void* buff, int len)
419 return TEMP_FAILURE_RETRY(read(fd, buff, len));
422 static inline int unix_write(int fd, const void* buff, int len)
424 return TEMP_FAILURE_RETRY(write(fd, buff, len));
427 static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
429 memset(pdata, 0, len);
430 pdata->persist_magic = PERSIST_DATA_MAGIC;
431 pdata->persist_valid_entries = 0;
434 /* A routine to update the passed in crypt_ftr to the lastest version.
435 * fd is open read/write on the device that holds the crypto footer and persistent
436 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
437 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
439 static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
441 int orig_major = crypt_ftr->major_version;
442 int orig_minor = crypt_ftr->minor_version;
444 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
445 struct crypt_persist_data *pdata;
446 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
448 SLOGW("upgrading crypto footer to 1.1");
450 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
452 SLOGE("Cannot allocate persisent data\n");
455 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
457 /* Need to initialize the persistent data area */
458 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
459 SLOGE("Cannot seek to persisent data offset\n");
463 /* Write all zeros to the first copy, making it invalid */
464 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
466 /* Write a valid but empty structure to the second copy */
467 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
468 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
470 /* Update the footer */
471 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
472 crypt_ftr->persist_data_offset[0] = pdata_offset;
473 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
474 crypt_ftr->minor_version = 1;
478 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
479 SLOGW("upgrading crypto footer to 1.2");
480 /* But keep the old kdf_type.
481 * It will get updated later to KDF_SCRYPT after the password has been verified.
483 crypt_ftr->kdf_type = KDF_PBKDF2;
484 get_device_scrypt_params(crypt_ftr);
485 crypt_ftr->minor_version = 2;
488 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
489 SLOGW("upgrading crypto footer to 1.3");
490 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
491 crypt_ftr->minor_version = 3;
494 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
495 if (lseek64(fd, offset, SEEK_SET) == -1) {
496 SLOGE("Cannot seek to crypt footer\n");
499 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
504 static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
508 off64_t starting_off;
513 if (get_crypt_ftr_info(&fname, &starting_off)) {
514 SLOGE("Unable to get crypt_ftr_info\n");
517 if (fname[0] != '/') {
518 SLOGE("Unexpected value for crypto key location\n");
521 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
522 SLOGE("Cannot open footer file %s for get\n", fname);
526 /* Make sure it's 16 Kbytes in length */
528 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
529 SLOGE("footer file %s is not the expected size!\n", fname);
533 /* Seek to the start of the crypt footer */
534 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
535 SLOGE("Cannot seek to real block device footer\n");
539 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
540 SLOGE("Cannot read real block device footer\n");
544 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
545 SLOGE("Bad magic for real block device %s\n", fname);
549 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
550 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
551 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
555 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
556 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
557 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
560 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
561 * copy on disk before returning.
563 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
564 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
575 static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
577 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
578 crypt_ftr->persist_data_offset[1]) {
579 SLOGE("Crypt_ftr persist data regions overlap");
583 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
584 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
588 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
589 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
590 CRYPT_FOOTER_OFFSET) {
591 SLOGE("Persistent data extends past crypto footer");
598 static int load_persistent_data(void)
600 struct crypt_mnt_ftr crypt_ftr;
601 struct crypt_persist_data *pdata = NULL;
602 char encrypted_state[PROPERTY_VALUE_MAX];
610 /* Nothing to do, we've already loaded or initialized it */
615 /* If not encrypted, just allocate an empty table and initialize it */
616 property_get("ro.crypto.state", encrypted_state, "");
617 if (strcmp(encrypted_state, "encrypted") ) {
618 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
620 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
621 persist_data = pdata;
627 if(get_crypt_ftr_and_key(&crypt_ftr)) {
631 if ((crypt_ftr.major_version < 1)
632 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
633 SLOGE("Crypt_ftr version doesn't support persistent data");
637 if (get_crypt_ftr_info(&fname, NULL)) {
641 ret = validate_persistent_data_storage(&crypt_ftr);
646 fd = open(fname, O_RDONLY|O_CLOEXEC);
648 SLOGE("Cannot open %s metadata file", fname);
652 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
654 SLOGE("Cannot allocate memory for persistent data");
658 for (i = 0; i < 2; i++) {
659 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
660 SLOGE("Cannot seek to read persistent data on %s", fname);
663 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
664 SLOGE("Error reading persistent data on iteration %d", i);
667 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
674 SLOGI("Could not find valid persistent data, creating");
675 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
679 persist_data = pdata;
691 static int save_persistent_data(void)
693 struct crypt_mnt_ftr crypt_ftr;
694 struct crypt_persist_data *pdata;
696 off64_t write_offset;
697 off64_t erase_offset;
701 if (persist_data == NULL) {
702 SLOGE("No persistent data to save");
706 if(get_crypt_ftr_and_key(&crypt_ftr)) {
710 if ((crypt_ftr.major_version < 1)
711 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
712 SLOGE("Crypt_ftr version doesn't support persistent data");
716 ret = validate_persistent_data_storage(&crypt_ftr);
721 if (get_crypt_ftr_info(&fname, NULL)) {
725 fd = open(fname, O_RDWR|O_CLOEXEC);
727 SLOGE("Cannot open %s metadata file", fname);
731 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
733 SLOGE("Cannot allocate persistant data");
737 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
738 SLOGE("Cannot seek to read persistent data on %s", fname);
742 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
743 SLOGE("Error reading persistent data before save");
747 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
748 /* The first copy is the curent valid copy, so write to
749 * the second copy and erase this one */
750 write_offset = crypt_ftr.persist_data_offset[1];
751 erase_offset = crypt_ftr.persist_data_offset[0];
753 /* The second copy must be the valid copy, so write to
754 * the first copy, and erase the second */
755 write_offset = crypt_ftr.persist_data_offset[0];
756 erase_offset = crypt_ftr.persist_data_offset[1];
759 /* Write the new copy first, if successful, then erase the old copy */
760 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
761 SLOGE("Cannot seek to write persistent data");
764 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
765 (int) crypt_ftr.persist_data_size) {
766 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
767 SLOGE("Cannot seek to erase previous persistent data");
771 memset(pdata, 0, crypt_ftr.persist_data_size);
772 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
773 (int) crypt_ftr.persist_data_size) {
774 SLOGE("Cannot write to erase previous persistent data");
779 SLOGE("Cannot write to save persistent data");
795 /* Convert a binary key of specified length into an ascii hex string equivalent,
796 * without the leading 0x and with null termination
798 static void convert_key_to_hex_ascii(const unsigned char *master_key,
799 unsigned int keysize, char *master_key_ascii) {
801 unsigned char nibble;
803 for (i=0, a=0; i<keysize; i++, a+=2) {
804 /* For each byte, write out two ascii hex digits */
805 nibble = (master_key[i] >> 4) & 0xf;
806 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
808 nibble = master_key[i] & 0xf;
809 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
812 /* Add the null termination */
813 master_key_ascii[a] = '\0';
817 static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
818 const unsigned char *master_key, const char *real_blk_name,
819 const char *name, int fd, const char *extra_params) {
820 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
822 struct dm_target_spec *tgt;
824 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
828 io = (struct dm_ioctl *) buffer;
830 /* Load the mapping table for this device */
831 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
833 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
834 io->target_count = 1;
836 tgt->sector_start = 0;
837 tgt->length = crypt_ftr->fs_size;
838 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
840 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
841 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
843 buff_offset = crypt_params - buffer;
844 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
845 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
847 crypt_params += strlen(crypt_params) + 1;
848 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
849 tgt->next = crypt_params - buffer;
851 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
852 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
858 if (i == TABLE_LOAD_RETRIES) {
859 /* We failed to load the table, return an error */
867 static int get_dm_crypt_version(int fd, const char *name, int *version)
869 char buffer[DM_CRYPT_BUF_SIZE];
871 struct dm_target_versions *v;
873 io = (struct dm_ioctl *) buffer;
875 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
877 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
881 /* Iterate over the returned versions, looking for name of "crypt".
882 * When found, get and return the version.
884 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
886 if (! strcmp(v->name, "crypt")) {
887 /* We found the crypt driver, return the version, and get out */
888 version[0] = v->version[0];
889 version[1] = v->version[1];
890 version[2] = v->version[2];
893 v = (struct dm_target_versions *)(((char *)v) + v->next);
899 static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
900 const unsigned char *master_key, const char *real_blk_name,
901 char *crypto_blk_name, const char *name) {
902 char buffer[DM_CRYPT_BUF_SIZE];
909 const char *extra_params;
912 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
913 SLOGE("Cannot open device-mapper\n");
917 io = (struct dm_ioctl *) buffer;
919 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
920 err = ioctl(fd, DM_DEV_CREATE, io);
922 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
926 /* Get the device status, in particular, the name of it's device file */
927 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
928 if (ioctl(fd, DM_DEV_STATUS, io)) {
929 SLOGE("Cannot retrieve dm-crypt device status\n");
932 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
933 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
936 if (! get_dm_crypt_version(fd, name, version)) {
937 /* Support for allow_discards was added in version 1.11.0 */
938 if ((version[0] >= 2) ||
939 ((version[0] == 1) && (version[1] >= 11))) {
940 extra_params = "1 allow_discards";
941 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
945 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
947 if (load_count < 0) {
948 SLOGE("Cannot load dm-crypt mapping table.\n");
950 } else if (load_count > 1) {
951 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
954 /* Resume this device to activate it */
955 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
957 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
958 SLOGE("Cannot resume the dm-crypt device\n");
962 /* We made it here with no errors. Woot! */
966 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
971 static int delete_crypto_blk_dev(const char *name)
974 char buffer[DM_CRYPT_BUF_SIZE];
978 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
979 SLOGE("Cannot open device-mapper\n");
983 io = (struct dm_ioctl *) buffer;
985 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
986 if (ioctl(fd, DM_DEV_REMOVE, io)) {
987 SLOGE("Cannot remove dm-crypt device\n");
991 /* We made it here with no errors. Woot! */
995 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1001 static int pbkdf2(const char *passwd, const unsigned char *salt,
1002 unsigned char *ikey, void *params UNUSED)
1004 SLOGI("Using pbkdf2 for cryptfs KDF");
1006 /* Turn the password into a key and IV that can decrypt the master key */
1007 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1008 HASH_COUNT, KEY_LEN_BYTES + IV_LEN_BYTES,
1012 static int scrypt(const char *passwd, const unsigned char *salt,
1013 unsigned char *ikey, void *params)
1015 SLOGI("Using scrypt for cryptfs KDF");
1017 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1019 int N = 1 << ftr->N_factor;
1020 int r = 1 << ftr->r_factor;
1021 int p = 1 << ftr->p_factor;
1023 /* Turn the password into a key and IV that can decrypt the master key */
1024 unsigned int keysize;
1025 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1026 salt, SALT_LEN, N, r, p, ikey,
1027 KEY_LEN_BYTES + IV_LEN_BYTES);
1032 static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1033 unsigned char *ikey, void *params)
1035 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1038 size_t signature_size;
1039 unsigned char* signature;
1040 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1042 int N = 1 << ftr->N_factor;
1043 int r = 1 << ftr->r_factor;
1044 int p = 1 << ftr->p_factor;
1046 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1047 salt, SALT_LEN, N, r, p, ikey,
1048 KEY_LEN_BYTES + IV_LEN_BYTES);
1051 SLOGE("scrypt failed");
1055 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1056 &signature, &signature_size)) {
1057 SLOGE("Signing failed");
1061 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1062 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1066 SLOGE("scrypt failed");
1073 static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1074 const unsigned char *decrypted_master_key,
1075 unsigned char *encrypted_master_key,
1076 struct crypt_mnt_ftr *crypt_ftr)
1078 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1079 EVP_CIPHER_CTX e_ctx;
1080 int encrypted_len, final_len;
1083 /* Turn the password into an intermediate key and IV that can decrypt the master key */
1084 get_device_scrypt_params(crypt_ftr);
1086 switch (crypt_ftr->kdf_type) {
1087 case KDF_SCRYPT_KEYMASTER:
1088 if (keymaster_create_key(crypt_ftr)) {
1089 SLOGE("keymaster_create_key failed");
1093 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1094 SLOGE("scrypt failed");
1100 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1101 SLOGE("scrypt failed");
1107 SLOGE("Invalid kdf_type");
1111 /* Initialize the decryption engine */
1112 EVP_CIPHER_CTX_init(&e_ctx);
1113 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
1114 SLOGE("EVP_EncryptInit failed\n");
1117 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
1119 /* Encrypt the master key */
1120 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1121 decrypted_master_key, KEY_LEN_BYTES)) {
1122 SLOGE("EVP_EncryptUpdate failed\n");
1125 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
1126 SLOGE("EVP_EncryptFinal failed\n");
1130 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1131 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1135 /* Store the scrypt of the intermediate key, so we can validate if it's a
1136 password error or mount error when things go wrong.
1137 Note there's no need to check for errors, since if this is incorrect, we
1138 simply won't wipe userdata, which is the correct default behavior
1140 int N = 1 << crypt_ftr->N_factor;
1141 int r = 1 << crypt_ftr->r_factor;
1142 int p = 1 << crypt_ftr->p_factor;
1144 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1145 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1146 crypt_ftr->scrypted_intermediate_key,
1147 sizeof(crypt_ftr->scrypted_intermediate_key));
1150 SLOGE("encrypt_master_key: crypto_scrypt failed");
1153 EVP_CIPHER_CTX_cleanup(&e_ctx);
1158 static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
1159 unsigned char *encrypted_master_key,
1160 unsigned char *decrypted_master_key,
1161 kdf_func kdf, void *kdf_params,
1162 unsigned char** intermediate_key,
1163 size_t* intermediate_key_size)
1165 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1166 EVP_CIPHER_CTX d_ctx;
1167 int decrypted_len, final_len;
1169 /* Turn the password into an intermediate key and IV that can decrypt the
1171 if (kdf(passwd, salt, ikey, kdf_params)) {
1172 SLOGE("kdf failed");
1176 /* Initialize the decryption engine */
1177 EVP_CIPHER_CTX_init(&d_ctx);
1178 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
1181 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1182 /* Decrypt the master key */
1183 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1184 encrypted_master_key, KEY_LEN_BYTES)) {
1187 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1191 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1195 /* Copy intermediate key if needed by params */
1196 if (intermediate_key && intermediate_key_size) {
1197 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1198 if (*intermediate_key) {
1199 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1200 *intermediate_key_size = KEY_LEN_BYTES;
1204 EVP_CIPHER_CTX_cleanup(&d_ctx);
1209 static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
1211 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1212 *kdf = scrypt_keymaster;
1214 } else if (ftr->kdf_type == KDF_SCRYPT) {
1223 static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
1224 struct crypt_mnt_ftr *crypt_ftr,
1225 unsigned char** intermediate_key,
1226 size_t* intermediate_key_size)
1232 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1233 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1234 decrypted_master_key, kdf, kdf_params,
1235 intermediate_key, intermediate_key_size);
1237 SLOGW("failure decrypting master key");
1243 static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
1244 struct crypt_mnt_ftr *crypt_ftr) {
1246 unsigned char key_buf[KEY_LEN_BYTES];
1248 /* Get some random bits for a key */
1249 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
1250 read(fd, key_buf, sizeof(key_buf));
1251 read(fd, salt, SALT_LEN);
1254 /* Now encrypt it with the password */
1255 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
1258 int wait_and_unmount(const char *mountpoint, bool kill)
1261 #define WAIT_UNMOUNT_COUNT 20
1263 /* Now umount the tmpfs filesystem */
1264 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1265 if (umount(mountpoint) == 0) {
1269 if (errno == EINVAL) {
1270 /* EINVAL is returned if the directory is not a mountpoint,
1271 * i.e. there is no filesystem mounted there. So just get out.
1278 /* If allowed, be increasingly aggressive before the last two retries */
1280 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1281 SLOGW("sending SIGHUP to processes with open files\n");
1282 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
1283 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1284 SLOGW("sending SIGKILL to processes with open files\n");
1285 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
1292 if (i < WAIT_UNMOUNT_COUNT) {
1293 SLOGD("unmounting %s succeeded\n", mountpoint);
1296 vold_killProcessesWithOpenFiles(mountpoint, 0);
1297 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1304 static int prep_data_fs(void)
1308 // NOTE: post_fs_data results in init calling back around to vold, so all
1309 // callers to this method must be async
1311 /* Do the prep of the /data filesystem */
1312 property_set("vold.post_fs_data_done", "0");
1313 property_set("vold.decrypt", "trigger_post_fs_data");
1314 SLOGD("Just triggered post_fs_data\n");
1316 /* Wait a max of 50 seconds, hopefully it takes much less */
1317 if (!android::base::WaitForProperty("vold.post_fs_data_done",
1319 std::chrono::seconds(50))) {
1320 /* Ugh, we failed to prep /data in time. Bail. */
1321 SLOGE("post_fs_data timed out!\n");
1324 SLOGD("post_fs_data done\n");
1329 static void cryptfs_set_corrupt()
1331 // Mark the footer as bad
1332 struct crypt_mnt_ftr crypt_ftr;
1333 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1334 SLOGE("Failed to get crypto footer - panic");
1338 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1339 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1340 SLOGE("Failed to set crypto footer - panic");
1345 static void cryptfs_trigger_restart_min_framework()
1347 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1348 SLOGE("Failed to mount tmpfs on data - panic");
1352 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1353 SLOGE("Failed to trigger post fs data - panic");
1357 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1358 SLOGE("Failed to trigger restart min framework - panic");
1363 /* returns < 0 on failure */
1364 static int cryptfs_restart_internal(int restart_main)
1366 char crypto_blkdev[MAXPATHLEN];
1368 static int restart_successful = 0;
1370 /* Validate that it's OK to call this routine */
1371 if (! master_key_saved) {
1372 SLOGE("Encrypted filesystem not validated, aborting");
1376 if (restart_successful) {
1377 SLOGE("System already restarted with encrypted disk, aborting");
1382 /* Here is where we shut down the framework. The init scripts
1383 * start all services in one of three classes: core, main or late_start.
1384 * On boot, we start core and main. Now, we stop main, but not core,
1385 * as core includes vold and a few other really important things that
1386 * we need to keep running. Once main has stopped, we should be able
1387 * to umount the tmpfs /data, then mount the encrypted /data.
1388 * We then restart the class main, and also the class late_start.
1389 * At the moment, I've only put a few things in late_start that I know
1390 * are not needed to bring up the framework, and that also cause problems
1391 * with unmounting the tmpfs /data, but I hope to add add more services
1392 * to the late_start class as we optimize this to decrease the delay
1393 * till the user is asked for the password to the filesystem.
1396 /* The init files are setup to stop the class main when vold.decrypt is
1397 * set to trigger_reset_main.
1399 property_set("vold.decrypt", "trigger_reset_main");
1400 SLOGD("Just asked init to shut down class main\n");
1402 /* Ugh, shutting down the framework is not synchronous, so until it
1403 * can be fixed, this horrible hack will wait a moment for it all to
1404 * shut down before proceeding. Without it, some devices cannot
1405 * restart the graphics services.
1410 /* Now that the framework is shutdown, we should be able to umount()
1411 * the tmpfs filesystem, and mount the real one.
1414 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1415 if (strlen(crypto_blkdev) == 0) {
1416 SLOGE("fs_crypto_blkdev not set\n");
1420 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
1421 /* If ro.crypto.readonly is set to 1, mount the decrypted
1422 * filesystem readonly. This is used when /data is mounted by
1425 char ro_prop[PROPERTY_VALUE_MAX];
1426 property_get("ro.crypto.readonly", ro_prop, "");
1427 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1428 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1430 rec->flags |= MS_RDONLY;
1434 /* If that succeeded, then mount the decrypted filesystem */
1435 int retries = RETRY_MOUNT_ATTEMPTS;
1439 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1440 * partitions in the fsck domain.
1442 if (setexeccon(secontextFsck())){
1443 SLOGE("Failed to setexeccon");
1446 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1449 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1450 /* TODO: invoke something similar to
1451 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1452 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1453 SLOGI("Failed to mount %s because it is busy - waiting",
1456 sleep(RETRY_MOUNT_DELAY_SECONDS);
1458 /* Let's hope that a reboot clears away whatever is keeping
1460 cryptfs_reboot(reboot);
1463 SLOGE("Failed to mount decrypted data");
1464 cryptfs_set_corrupt();
1465 cryptfs_trigger_restart_min_framework();
1466 SLOGI("Started framework to offer wipe");
1467 if (setexeccon(NULL)) {
1468 SLOGE("Failed to setexeccon");
1473 if (setexeccon(NULL)) {
1474 SLOGE("Failed to setexeccon");
1478 /* Create necessary paths on /data */
1479 if (prep_data_fs()) {
1482 property_set("vold.decrypt", "trigger_load_persist_props");
1484 /* startup service classes main and late_start */
1485 property_set("vold.decrypt", "trigger_restart_framework");
1486 SLOGD("Just triggered restart_framework\n");
1488 /* Give it a few moments to get started */
1493 restart_successful = 1;
1499 int cryptfs_restart(void)
1501 SLOGI("cryptfs_restart");
1502 if (e4crypt_is_native()) {
1503 SLOGE("cryptfs_restart not valid for file encryption:");
1507 /* Call internal implementation forcing a restart of main service group */
1508 return cryptfs_restart_internal(1);
1511 static int do_crypto_complete(const char *mount_point)
1513 struct crypt_mnt_ftr crypt_ftr;
1514 char encrypted_state[PROPERTY_VALUE_MAX];
1515 char key_loc[PROPERTY_VALUE_MAX];
1517 property_get("ro.crypto.state", encrypted_state, "");
1518 if (strcmp(encrypted_state, "encrypted") ) {
1519 SLOGE("not running with encryption, aborting");
1520 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1523 // crypto_complete is full disk encrypted status
1524 if (e4crypt_is_native()) {
1525 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1528 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1529 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
1532 * Only report this error if key_loc is a file and it exists.
1533 * If the device was never encrypted, and /data is not mountable for
1534 * some reason, returning 1 should prevent the UI from presenting the
1535 * a "enter password" screen, or worse, a "press button to wipe the
1538 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1539 SLOGE("master key file does not exist, aborting");
1540 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1542 SLOGE("Error getting crypt footer and key\n");
1543 return CRYPTO_COMPLETE_BAD_METADATA;
1547 // Test for possible error flags
1548 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1549 SLOGE("Encryption process is partway completed\n");
1550 return CRYPTO_COMPLETE_PARTIAL;
1553 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1554 SLOGE("Encryption process was interrupted but cannot continue\n");
1555 return CRYPTO_COMPLETE_INCONSISTENT;
1558 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1559 SLOGE("Encryption is successful but data is corrupt\n");
1560 return CRYPTO_COMPLETE_CORRUPT;
1563 /* We passed the test! We shall diminish, and return to the west */
1564 return CRYPTO_COMPLETE_ENCRYPTED;
1567 static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1568 const char *passwd, const char *mount_point, const char *label)
1570 /* Allocate enough space for a 256 bit key, but we may use less */
1571 unsigned char decrypted_master_key[32];
1572 char crypto_blkdev[MAXPATHLEN];
1573 char real_blkdev[MAXPATHLEN];
1574 char tmp_mount_point[64];
1575 unsigned int orig_failed_decrypt_count;
1577 int use_keymaster = 0;
1579 unsigned char* intermediate_key = 0;
1580 size_t intermediate_key_size = 0;
1581 int N = 1 << crypt_ftr->N_factor;
1582 int r = 1 << crypt_ftr->r_factor;
1583 int p = 1 << crypt_ftr->p_factor;
1585 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1586 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
1588 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1589 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1590 &intermediate_key, &intermediate_key_size)) {
1591 SLOGE("Failed to decrypt master key\n");
1597 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1599 // Create crypto block device - all (non fatal) code paths
1601 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1602 real_blkdev, crypto_blkdev, label)) {
1603 SLOGE("Error creating decrypted block device\n");
1608 /* Work out if the problem is the password or the data */
1609 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1610 scrypted_intermediate_key)];
1612 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1613 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1614 N, r, p, scrypted_intermediate_key,
1615 sizeof(scrypted_intermediate_key));
1617 // Does the key match the crypto footer?
1618 if (rc == 0 && memcmp(scrypted_intermediate_key,
1619 crypt_ftr->scrypted_intermediate_key,
1620 sizeof(scrypted_intermediate_key)) == 0) {
1621 SLOGI("Password matches");
1624 /* Try mounting the file system anyway, just in case the problem's with
1625 * the footer, not the key. */
1626 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1628 mkdir(tmp_mount_point, 0755);
1629 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1630 SLOGE("Error temp mounting decrypted block device\n");
1631 delete_crypto_blk_dev(label);
1633 rc = ++crypt_ftr->failed_decrypt_count;
1634 put_crypt_ftr_and_key(crypt_ftr);
1637 SLOGI("Password did not match but decrypted drive mounted - continue");
1638 umount(tmp_mount_point);
1644 crypt_ftr->failed_decrypt_count = 0;
1645 if (orig_failed_decrypt_count != 0) {
1646 put_crypt_ftr_and_key(crypt_ftr);
1649 /* Save the name of the crypto block device
1650 * so we can mount it when restarting the framework. */
1651 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1653 /* Also save a the master key so we can reencrypted the key
1654 * the key when we want to change the password on it. */
1655 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
1656 saved_mount_point = strdup(mount_point);
1657 master_key_saved = 1;
1658 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1661 // Upgrade if we're not using the latest KDF.
1662 use_keymaster = keymaster_check_compatibility();
1663 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1664 // Don't allow downgrade
1665 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1666 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1668 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1669 crypt_ftr->kdf_type = KDF_SCRYPT;
1674 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1675 crypt_ftr->master_key, crypt_ftr);
1677 rc = put_crypt_ftr_and_key(crypt_ftr);
1679 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1681 // Do not fail even if upgrade failed - machine is bootable
1682 // Note that if this code is ever hit, there is a *serious* problem
1683 // since KDFs should never fail. You *must* fix the kdf before
1686 SLOGW("Upgrade failed with error %d,"
1687 " but continuing with previous state",
1695 if (intermediate_key) {
1696 memset(intermediate_key, 0, intermediate_key_size);
1697 free(intermediate_key);
1703 * Called by vold when it's asked to mount an encrypted external
1704 * storage volume. The incoming partition has no crypto header/footer,
1705 * as any metadata is been stored in a separate, small partition.
1707 * out_crypto_blkdev must be MAXPATHLEN.
1709 int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1710 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
1711 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
1713 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
1717 unsigned long nr_sec = 0;
1718 get_blkdev_size(fd, &nr_sec);
1722 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
1726 struct crypt_mnt_ftr ext_crypt_ftr;
1727 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1728 ext_crypt_ftr.fs_size = nr_sec;
1729 ext_crypt_ftr.keysize = keysize;
1730 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1732 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1733 out_crypto_blkdev, label);
1737 * Called by vold when it's asked to unmount an encrypted external
1740 int cryptfs_revert_ext_volume(const char* label) {
1741 return delete_crypto_blk_dev((char*) label);
1744 int cryptfs_crypto_complete(void)
1746 return do_crypto_complete("/data");
1749 int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1751 char encrypted_state[PROPERTY_VALUE_MAX];
1752 property_get("ro.crypto.state", encrypted_state, "");
1753 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1754 SLOGE("encrypted fs already validated or not running with encryption,"
1759 if (get_crypt_ftr_and_key(crypt_ftr)) {
1760 SLOGE("Error getting crypt footer and key");
1767 int cryptfs_check_passwd(const char *passwd)
1769 SLOGI("cryptfs_check_passwd");
1770 if (e4crypt_is_native()) {
1771 SLOGE("cryptfs_check_passwd not valid for file encryption");
1775 struct crypt_mnt_ftr crypt_ftr;
1778 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1780 SLOGE("Could not get footer");
1784 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1785 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1787 SLOGE("Password did not match");
1791 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1792 // Here we have a default actual password but a real password
1793 // we must test against the scrypted value
1794 // First, we must delete the crypto block device that
1795 // test_mount_encrypted_fs leaves behind as a side effect
1796 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1797 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1798 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1800 SLOGE("Default password did not match on reboot encryption");
1804 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1805 put_crypt_ftr_and_key(&crypt_ftr);
1806 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1808 SLOGE("Could not change password on reboot encryption");
1813 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
1814 cryptfs_clear_password();
1815 password = strdup(passwd);
1816 struct timespec now;
1817 clock_gettime(CLOCK_BOOTTIME, &now);
1818 password_expiry_time = now.tv_sec + password_max_age_seconds;
1824 int cryptfs_verify_passwd(char *passwd)
1826 struct crypt_mnt_ftr crypt_ftr;
1827 /* Allocate enough space for a 256 bit key, but we may use less */
1828 unsigned char decrypted_master_key[32];
1829 char encrypted_state[PROPERTY_VALUE_MAX];
1832 property_get("ro.crypto.state", encrypted_state, "");
1833 if (strcmp(encrypted_state, "encrypted") ) {
1834 SLOGE("device not encrypted, aborting");
1838 if (!master_key_saved) {
1839 SLOGE("encrypted fs not yet mounted, aborting");
1843 if (!saved_mount_point) {
1844 SLOGE("encrypted fs failed to save mount point, aborting");
1848 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1849 SLOGE("Error getting crypt footer and key\n");
1853 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1854 /* If the device has no password, then just say the password is valid */
1857 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
1858 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1859 /* They match, the password is correct */
1862 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1871 /* Initialize a crypt_mnt_ftr structure. The keysize is
1872 * defaulted to 16 bytes, and the filesystem size to 0.
1873 * Presumably, at a minimum, the caller will update the
1874 * filesystem size and crypto_type_name after calling this function.
1876 static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1880 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
1881 ftr->magic = CRYPT_MNT_MAGIC;
1882 ftr->major_version = CURRENT_MAJOR_VERSION;
1883 ftr->minor_version = CURRENT_MINOR_VERSION;
1884 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
1885 ftr->keysize = KEY_LEN_BYTES;
1887 switch (keymaster_check_compatibility()) {
1889 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1893 ftr->kdf_type = KDF_SCRYPT;
1897 SLOGE("keymaster_check_compatibility failed");
1901 get_device_scrypt_params(ftr);
1903 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1904 if (get_crypt_ftr_info(NULL, &off) == 0) {
1905 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1906 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1907 ftr->persist_data_size;
1913 static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
1915 const char *args[10];
1916 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1922 if (type == EXT4_FS) {
1923 #ifdef TARGET_USES_MKE2FS
1924 args[0] = "/system/bin/mke2fs";
1931 args[7] = crypto_blkdev;
1932 snprintf(size_str, sizeof(size_str), "%" PRId64, size / (4096 / 512));
1936 args[0] = "/system/bin/make_ext4fs";
1940 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
1942 args[5] = crypto_blkdev;
1945 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1946 args[0], args[1], args[2], args[3], args[4], args[5]);
1947 } else if (type == F2FS_FS) {
1948 args[0] = "/system/bin/mkfs.f2fs";
1951 args[3] = crypto_blkdev;
1952 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
1955 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
1956 args[0], args[1], args[2], args[3], args[4]);
1958 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1962 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1965 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
1967 if (WIFEXITED(status)) {
1968 if (WEXITSTATUS(status)) {
1969 SLOGE("Error creating filesystem on %s, exit status %d ",
1970 crypto_blkdev, WEXITSTATUS(status));
1972 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1976 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1983 #define CRYPT_INPLACE_BUFSIZE 4096
1984 #define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1985 #define CRYPT_SECTOR_SIZE 512
1987 /* aligned 32K writes tends to make flash happy.
1988 * SD card association recommends it.
1990 #define BLOCKS_AT_A_TIME 8
1992 struct encryptGroupsData
1997 off64_t one_pct, cur_pct, new_pct;
1998 off64_t blocks_already_done, tot_numblocks;
1999 off64_t used_blocks_already_done, tot_used_blocks;
2000 char* real_blkdev, * crypto_blkdev;
2004 off64_t last_written_sector;
2006 time_t time_started;
2010 static void update_progress(struct encryptGroupsData* data, int is_used)
2012 data->blocks_already_done++;
2015 data->used_blocks_already_done++;
2017 if (data->tot_used_blocks) {
2018 data->new_pct = data->used_blocks_already_done / data->one_pct;
2020 data->new_pct = data->blocks_already_done / data->one_pct;
2023 if (data->new_pct > data->cur_pct) {
2025 data->cur_pct = data->new_pct;
2026 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
2027 property_set("vold.encrypt_progress", buf);
2030 if (data->cur_pct >= 5) {
2031 struct timespec time_now;
2032 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2033 SLOGW("Error getting time");
2035 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2036 off64_t remaining_blocks = data->tot_used_blocks
2037 - data->used_blocks_already_done;
2038 int remaining_time = (int)(elapsed_time * remaining_blocks
2039 / data->used_blocks_already_done);
2041 // Change time only if not yet set, lower, or a lot higher for
2042 // best user experience
2043 if (data->remaining_time == -1
2044 || remaining_time < data->remaining_time
2045 || remaining_time > data->remaining_time + 60) {
2047 snprintf(buf, sizeof(buf), "%d", remaining_time);
2048 property_set("vold.encrypt_time_remaining", buf);
2049 data->remaining_time = remaining_time;
2055 static void log_progress(struct encryptGroupsData const* data, bool completed)
2057 // Precondition - if completed data = 0 else data != 0
2059 // Track progress so we can skip logging blocks
2060 static off64_t offset = -1;
2062 // Need to close existing 'Encrypting from' log?
2063 if (completed || (offset != -1 && data->offset != offset)) {
2064 SLOGI("Encrypted to sector %" PRId64,
2065 offset / info.block_size * CRYPT_SECTOR_SIZE);
2069 // Need to start new 'Encrypting from' log?
2070 if (!completed && offset != data->offset) {
2071 SLOGI("Encrypting from sector %" PRId64,
2072 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2077 offset = data->offset + (off64_t)data->count * info.block_size;
2081 static int flush_outstanding_data(struct encryptGroupsData* data)
2083 if (data->count == 0) {
2087 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
2089 if (pread64(data->realfd, data->buffer,
2090 info.block_size * data->count, data->offset)
2092 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2097 if (pwrite64(data->cryptofd, data->buffer,
2098 info.block_size * data->count, data->offset)
2100 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2101 data->crypto_blkdev);
2104 log_progress(data, false);
2108 data->last_written_sector = (data->offset + data->count)
2109 / info.block_size * CRYPT_SECTOR_SIZE - 1;
2113 static int encrypt_groups(struct encryptGroupsData* data)
2116 u8 *block_bitmap = 0;
2121 data->buffer = (char *)malloc(info.block_size * BLOCKS_AT_A_TIME);
2122 if (!data->buffer) {
2123 SLOGE("Failed to allocate crypto buffer");
2127 block_bitmap = (u8 *)malloc(info.block_size);
2128 if (!block_bitmap) {
2129 SLOGE("failed to allocate block bitmap");
2133 for (i = 0; i < aux_info.groups; ++i) {
2134 SLOGI("Encrypting group %d", i);
2136 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2137 u32 block_count = std::min(info.blocks_per_group,
2138 (u32)(aux_info.len_blocks - first_block));
2140 off64_t offset = (u64)info.block_size
2141 * aux_info.bg_desc[i].bg_block_bitmap;
2143 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2144 if (ret != (int)info.block_size) {
2145 SLOGE("failed to read all of block group bitmap %d", i);
2149 offset = (u64)info.block_size * first_block;
2153 for (block = 0; block < block_count; block++) {
2154 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
2155 0 : bitmap_get_bit(block_bitmap, block);
2156 update_progress(data, used);
2158 if (data->count == 0) {
2159 data->offset = offset;
2163 if (flush_outstanding_data(data)) {
2168 offset += info.block_size;
2170 /* Write data if we are aligned or buffer size reached */
2171 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2172 || data->count == BLOCKS_AT_A_TIME) {
2173 if (flush_outstanding_data(data)) {
2178 if (!is_battery_ok_to_continue()) {
2179 SLOGE("Stopping encryption due to low battery");
2185 if (flush_outstanding_data(data)) {
2190 data->completed = 1;
2194 log_progress(0, true);
2200 static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2203 off64_t *size_already_done,
2205 off64_t previously_encrypted_upto)
2208 struct encryptGroupsData data;
2209 int rc; // Can't initialize without causing warning -Wclobbered
2210 struct timespec time_started = {0};
2211 int retries = RETRY_MOUNT_ATTEMPTS;
2213 if (previously_encrypted_upto > *size_already_done) {
2214 SLOGD("Not fast encrypting since resuming part way through");
2218 memset(&data, 0, sizeof(data));
2219 data.real_blkdev = real_blkdev;
2220 data.crypto_blkdev = crypto_blkdev;
2222 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
2223 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2224 real_blkdev, errno, strerror(errno));
2229 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2230 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2232 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2233 crypto_blkdev, errno, strerror(errno));
2234 sleep(RETRY_MOUNT_DELAY_SECONDS);
2236 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2237 crypto_blkdev, errno, strerror(errno));
2238 rc = ENABLE_INPLACE_ERR_DEV;
2243 if (setjmp(setjmp_env)) {
2244 SLOGE("Reading ext4 extent caused an exception\n");
2249 if (read_ext(data.realfd, 0) != 0) {
2250 SLOGE("Failed to read ext4 extent\n");
2255 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2256 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2257 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2259 SLOGI("Encrypting ext4 filesystem in place...");
2261 data.tot_used_blocks = data.numblocks;
2262 for (i = 0; i < aux_info.groups; ++i) {
2263 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2266 data.one_pct = data.tot_used_blocks / 100;
2269 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2270 SLOGW("Error getting time at start");
2271 // Note - continue anyway - we'll run with 0
2273 data.time_started = time_started.tv_sec;
2274 data.remaining_time = -1;
2276 rc = encrypt_groups(&data);
2278 SLOGE("Error encrypting groups");
2282 *size_already_done += data.completed ? size : data.last_written_sector;
2287 close(data.cryptofd);
2292 static void log_progress_f2fs(u64 block, bool completed)
2294 // Precondition - if completed data = 0 else data != 0
2296 // Track progress so we can skip logging blocks
2297 static u64 last_block = (u64)-1;
2299 // Need to close existing 'Encrypting from' log?
2300 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2301 SLOGI("Encrypted to block %" PRId64, last_block);
2305 // Need to start new 'Encrypting from' log?
2306 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2307 SLOGI("Encrypting from block %" PRId64, block);
2316 static int encrypt_one_block_f2fs(u64 pos, void *data)
2318 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2320 priv_dat->blocks_already_done = pos - 1;
2321 update_progress(priv_dat, 1);
2323 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2325 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2326 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
2330 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2331 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
2334 log_progress_f2fs(pos, false);
2340 static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2343 off64_t *size_already_done,
2345 off64_t previously_encrypted_upto)
2347 struct encryptGroupsData data;
2348 struct f2fs_info *f2fs_info = NULL;
2349 int rc = ENABLE_INPLACE_ERR_OTHER;
2350 if (previously_encrypted_upto > *size_already_done) {
2351 SLOGD("Not fast encrypting since resuming part way through");
2352 return ENABLE_INPLACE_ERR_OTHER;
2354 memset(&data, 0, sizeof(data));
2355 data.real_blkdev = real_blkdev;
2356 data.crypto_blkdev = crypto_blkdev;
2359 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
2360 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
2364 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2365 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
2366 crypto_blkdev, errno, strerror(errno));
2367 rc = ENABLE_INPLACE_ERR_DEV;
2371 f2fs_info = generate_f2fs_info(data.realfd);
2375 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2376 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2377 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2379 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2381 data.one_pct = data.tot_used_blocks / 100;
2383 data.time_started = time(NULL);
2384 data.remaining_time = -1;
2386 data.buffer = (char *)malloc(f2fs_info->block_size);
2388 SLOGE("Failed to allocate crypto buffer");
2394 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2395 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2398 SLOGE("Error in running over f2fs blocks");
2399 rc = ENABLE_INPLACE_ERR_OTHER;
2403 *size_already_done += size;
2408 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2410 log_progress_f2fs(0, true);
2414 close(data.cryptofd);
2419 static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2420 off64_t size, off64_t *size_already_done,
2422 off64_t previously_encrypted_upto)
2424 int realfd, cryptofd;
2425 char *buf[CRYPT_INPLACE_BUFSIZE];
2426 int rc = ENABLE_INPLACE_ERR_OTHER;
2427 off64_t numblocks, i, remainder;
2428 off64_t one_pct, cur_pct, new_pct;
2429 off64_t blocks_already_done, tot_numblocks;
2431 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
2432 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2433 return ENABLE_INPLACE_ERR_OTHER;
2436 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2437 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2438 crypto_blkdev, errno, strerror(errno));
2440 return ENABLE_INPLACE_ERR_DEV;
2443 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2444 * The size passed in is the number of 512 byte sectors in the filesystem.
2445 * So compute the number of whole 4K blocks we should read/write,
2446 * and the remainder.
2448 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2449 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
2450 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2451 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2453 SLOGE("Encrypting filesystem in place...");
2455 i = previously_encrypted_upto + 1 - *size_already_done;
2457 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2458 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2462 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2463 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2467 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2468 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2469 SLOGE("Error reading initial sectors from real_blkdev %s for "
2470 "inplace encrypt\n", crypto_blkdev);
2473 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2474 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2475 "inplace encrypt\n", crypto_blkdev);
2478 SLOGI("Encrypted 1 block at %" PRId64, i);
2482 one_pct = tot_numblocks / 100;
2484 /* process the majority of the filesystem in blocks */
2485 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
2486 new_pct = (i + blocks_already_done) / one_pct;
2487 if (new_pct > cur_pct) {
2491 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
2492 property_set("vold.encrypt_progress", buf);
2494 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
2495 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
2498 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
2499 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2502 SLOGD("Encrypted %d block at %" PRId64,
2503 CRYPT_SECTORS_PER_BUFSIZE,
2504 i * CRYPT_SECTORS_PER_BUFSIZE);
2507 if (!is_battery_ok_to_continue()) {
2508 SLOGE("Stopping encryption due to low battery");
2509 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2515 /* Do any remaining sectors */
2516 for (i=0; i<remainder; i++) {
2517 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2518 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
2521 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2522 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2525 SLOGI("Encrypted 1 block at next location");
2529 *size_already_done += size;
2539 /* returns on of the ENABLE_INPLACE_* return codes */
2540 static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2541 off64_t size, off64_t *size_already_done,
2543 off64_t previously_encrypted_upto)
2545 int rc_ext4, rc_f2fs, rc_full;
2546 if (previously_encrypted_upto) {
2547 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
2550 if (*size_already_done + size < previously_encrypted_upto) {
2551 *size_already_done += size;
2555 /* TODO: identify filesystem type.
2556 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2557 * then we will drop down to cryptfs_enable_inplace_f2fs.
2559 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
2560 size, size_already_done,
2561 tot_size, previously_encrypted_upto)) == 0) {
2564 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
2566 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2567 size, size_already_done,
2568 tot_size, previously_encrypted_upto)) == 0) {
2571 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
2573 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
2574 size, size_already_done, tot_size,
2575 previously_encrypted_upto);
2576 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2578 /* Hack for b/17898962, the following is the symptom... */
2579 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2580 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2581 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2582 return ENABLE_INPLACE_ERR_DEV;
2587 #define CRYPTO_ENABLE_WIPE 1
2588 #define CRYPTO_ENABLE_INPLACE 2
2590 #define FRAMEWORK_BOOT_WAIT 60
2592 static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2594 int fd = open(filename, O_RDONLY|O_CLOEXEC);
2596 SLOGE("Error opening file %s", filename);
2600 char block[CRYPT_INPLACE_BUFSIZE];
2601 memset(block, 0, sizeof(block));
2602 if (unix_read(fd, block, sizeof(block)) < 0) {
2603 SLOGE("Error reading file %s", filename);
2612 SHA256_Update(&c, block, sizeof(block));
2613 SHA256_Final(buf, &c);
2618 static int get_fs_type(struct fstab_rec *rec)
2623 if (!strcmp(rec->fs_type, "ext4")) {
2625 } else if (!strcmp(rec->fs_type, "f2fs")) {
2632 static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2633 char *crypto_blkdev, char *real_blkdev,
2634 int previously_encrypted_upto)
2636 off64_t cur_encryption_done=0, tot_encryption_size=0;
2639 if (!is_battery_ok_to_start()) {
2640 SLOGW("Not starting encryption due to low battery");
2644 /* The size of the userdata partition, and add in the vold volumes below */
2645 tot_encryption_size = crypt_ftr->fs_size;
2647 if (how == CRYPTO_ENABLE_WIPE) {
2648 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2649 int fs_type = get_fs_type(rec);
2651 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2654 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
2655 } else if (how == CRYPTO_ENABLE_INPLACE) {
2656 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2657 crypt_ftr->fs_size, &cur_encryption_done,
2658 tot_encryption_size,
2659 previously_encrypted_upto);
2661 if (rc == ENABLE_INPLACE_ERR_DEV) {
2662 /* Hack for b/17898962 */
2663 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2664 cryptfs_reboot(reboot);
2668 crypt_ftr->encrypted_upto = cur_encryption_done;
2671 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2672 /* The inplace routine never actually sets the progress to 100% due
2673 * to the round down nature of integer division, so set it here */
2674 property_set("vold.encrypt_progress", "100");
2677 /* Shouldn't happen */
2678 SLOGE("cryptfs_enable: internal error, unknown option\n");
2685 int cryptfs_enable_internal(char *howarg, int crypt_type, const char *passwd,
2689 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
2690 unsigned char decrypted_master_key[KEY_LEN_BYTES];
2692 struct crypt_mnt_ftr crypt_ftr;
2693 struct crypt_persist_data *pdata;
2694 char encrypted_state[PROPERTY_VALUE_MAX];
2695 char lockid[32] = { 0 };
2696 char key_loc[PROPERTY_VALUE_MAX];
2698 off64_t previously_encrypted_upto = 0;
2699 bool rebootEncryption = false;
2700 bool onlyCreateHeader = false;
2703 if (!strcmp(howarg, "wipe")) {
2704 how = CRYPTO_ENABLE_WIPE;
2705 } else if (! strcmp(howarg, "inplace")) {
2706 how = CRYPTO_ENABLE_INPLACE;
2708 /* Shouldn't happen, as CommandListener vets the args */
2709 goto error_unencrypted;
2712 if (how == CRYPTO_ENABLE_INPLACE
2713 && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2714 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2715 /* An encryption was underway and was interrupted */
2716 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2717 crypt_ftr.encrypted_upto = 0;
2718 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2720 /* At this point, we are in an inconsistent state. Until we successfully
2721 complete encryption, a reboot will leave us broken. So mark the
2722 encryption failed in case that happens.
2723 On successfully completing encryption, remove this flag */
2724 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2726 put_crypt_ftr_and_key(&crypt_ftr);
2727 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2728 if (!check_ftr_sha(&crypt_ftr)) {
2729 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2730 put_crypt_ftr_and_key(&crypt_ftr);
2731 goto error_unencrypted;
2734 /* Doing a reboot-encryption*/
2735 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2736 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2737 rebootEncryption = true;
2741 property_get("ro.crypto.state", encrypted_state, "");
2742 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2743 SLOGE("Device is already running encrypted, aborting");
2744 goto error_unencrypted;
2747 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2748 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
2749 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
2751 /* Get the size of the real block device */
2752 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
2754 SLOGE("Cannot open block device %s\n", real_blkdev);
2755 goto error_unencrypted;
2757 unsigned long nr_sec;
2758 get_blkdev_size(fd, &nr_sec);
2760 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2761 goto error_unencrypted;
2765 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
2766 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
2767 unsigned int fs_size_sec, max_fs_size_sec;
2768 fs_size_sec = get_fs_size(real_blkdev);
2769 if (fs_size_sec == 0)
2770 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2772 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2774 if (fs_size_sec > max_fs_size_sec) {
2775 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2776 goto error_unencrypted;
2780 /* Get a wakelock as this may take a while, and we don't want the
2781 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2782 * wants to keep the screen on, it can grab a full wakelock.
2784 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
2785 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2787 /* The init files are setup to stop the class main and late start when
2788 * vold sets trigger_shutdown_framework.
2790 property_set("vold.decrypt", "trigger_shutdown_framework");
2791 SLOGD("Just asked init to shut down class main\n");
2793 /* Ask vold to unmount all devices that it manages */
2794 if (vold_unmountAll()) {
2795 SLOGE("Failed to unmount all vold managed devices");
2798 /* no_ui means we are being called from init, not settings.
2799 Now we always reboot from settings, so !no_ui means reboot
2802 /* Try fallback, which is to reboot and try there */
2803 onlyCreateHeader = true;
2804 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2805 if (breadcrumb == 0) {
2806 SLOGE("Failed to create breadcrumb file");
2807 goto error_shutting_down;
2812 /* Do extra work for a better UX when doing the long inplace encryption */
2813 if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
2814 /* Now that /data is unmounted, we need to mount a tmpfs
2815 * /data, set a property saying we're doing inplace encryption,
2816 * and restart the framework.
2818 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2819 goto error_shutting_down;
2821 /* Tells the framework that inplace encryption is starting */
2822 property_set("vold.encrypt_progress", "0");
2824 /* restart the framework. */
2825 /* Create necessary paths on /data */
2826 if (prep_data_fs()) {
2827 goto error_shutting_down;
2830 /* Ugh, shutting down the framework is not synchronous, so until it
2831 * can be fixed, this horrible hack will wait a moment for it all to
2832 * shut down before proceeding. Without it, some devices cannot
2833 * restart the graphics services.
2838 /* Start the actual work of making an encrypted filesystem */
2839 /* Initialize a crypt_mnt_ftr for the partition */
2840 if (previously_encrypted_upto == 0 && !rebootEncryption) {
2841 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2842 goto error_shutting_down;
2845 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2846 crypt_ftr.fs_size = nr_sec
2847 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2849 crypt_ftr.fs_size = nr_sec;
2851 /* At this point, we are in an inconsistent state. Until we successfully
2852 complete encryption, a reboot will leave us broken. So mark the
2853 encryption failed in case that happens.
2854 On successfully completing encryption, remove this flag */
2855 if (onlyCreateHeader) {
2856 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2858 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2860 crypt_ftr.crypt_type = crypt_type;
2861 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
2863 /* Make an encrypted master key */
2864 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2865 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2866 SLOGE("Cannot create encrypted master key\n");
2867 goto error_shutting_down;
2870 /* Replace scrypted intermediate key if we are preparing for a reboot */
2871 if (onlyCreateHeader) {
2872 unsigned char fake_master_key[KEY_LEN_BYTES];
2873 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
2874 memset(fake_master_key, 0, sizeof(fake_master_key));
2875 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2876 encrypted_fake_master_key, &crypt_ftr);
2879 /* Write the key to the end of the partition */
2880 put_crypt_ftr_and_key(&crypt_ftr);
2882 /* If any persistent data has been remembered, save it.
2883 * If none, create a valid empty table and save that.
2885 if (!persist_data) {
2886 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
2888 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2889 persist_data = pdata;
2893 save_persistent_data();
2897 if (onlyCreateHeader) {
2899 cryptfs_reboot(reboot);
2902 if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
2903 /* startup service classes main and late_start */
2904 property_set("vold.decrypt", "trigger_restart_min_framework");
2905 SLOGD("Just triggered restart_min_framework\n");
2907 /* OK, the framework is restarted and will soon be showing a
2908 * progress bar. Time to setup an encrypted mapping, and
2909 * either write a new filesystem, or encrypt in place updating
2910 * the progress bar as we work.
2914 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2915 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2916 CRYPTO_BLOCK_DEVICE);
2918 /* If we are continuing, check checksums match */
2920 if (previously_encrypted_upto) {
2921 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2922 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
2924 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2925 sizeof(hash_first_block)) != 0) {
2926 SLOGE("Checksums do not match - trigger wipe");
2932 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2933 crypto_blkdev, real_blkdev,
2934 previously_encrypted_upto);
2937 /* Calculate checksum if we are not finished */
2938 if (!rc && how == CRYPTO_ENABLE_INPLACE
2939 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
2940 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2941 crypt_ftr.hash_first_block);
2943 SLOGE("Error calculating checksum for continuing encryption");
2948 /* Undo the dm-crypt mapping whether we succeed or not */
2949 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2953 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
2955 if (how == CRYPTO_ENABLE_INPLACE
2956 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
2957 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2958 crypt_ftr.encrypted_upto);
2959 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2962 put_crypt_ftr_and_key(&crypt_ftr);
2964 if (how == CRYPTO_ENABLE_WIPE
2965 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2966 char value[PROPERTY_VALUE_MAX];
2967 property_get("ro.crypto.state", value, "");
2968 if (!strcmp(value, "")) {
2969 /* default encryption - continue first boot sequence */
2970 property_set("ro.crypto.state", "encrypted");
2971 property_set("ro.crypto.type", "block");
2972 release_wake_lock(lockid);
2973 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2974 // Bring up cryptkeeper that will check the password and set it
2975 property_set("vold.decrypt", "trigger_shutdown_framework");
2977 property_set("vold.encrypt_progress", "");
2978 cryptfs_trigger_restart_min_framework();
2980 cryptfs_check_passwd(DEFAULT_PASSWORD);
2981 cryptfs_restart_internal(1);
2985 sleep(2); /* Give the UI a chance to show 100% progress */
2986 cryptfs_reboot(reboot);
2989 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
2990 cryptfs_reboot(shutdown);
2993 char value[PROPERTY_VALUE_MAX];
2995 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
2996 if (!strcmp(value, "1")) {
2997 /* wipe data if encryption failed */
2998 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3000 const std::vector<std::string> options = {
3001 "--wipe_data\n--reason=cryptfs_enable_internal\n"
3003 if (!write_bootloader_message(options, &err)) {
3004 SLOGE("could not write bootloader message: %s", err.c_str());
3006 cryptfs_reboot(recovery);
3008 /* set property to trigger dialog */
3009 property_set("vold.encrypt_progress", "error_partially_encrypted");
3010 release_wake_lock(lockid);
3015 /* hrm, the encrypt step claims success, but the reboot failed.
3016 * This should not happen.
3017 * Set the property and return. Hope the framework can deal with it.
3019 property_set("vold.encrypt_progress", "error_reboot_failed");
3020 release_wake_lock(lockid);
3024 property_set("vold.encrypt_progress", "error_not_encrypted");
3026 release_wake_lock(lockid);
3030 error_shutting_down:
3031 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3032 * but the framework is stopped and not restarted to show the error, so it's up to
3033 * vold to restart the system.
3035 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
3036 cryptfs_reboot(reboot);
3038 /* shouldn't get here */
3039 property_set("vold.encrypt_progress", "error_shutting_down");
3041 release_wake_lock(lockid);
3046 int cryptfs_enable(char *howarg, int type, char *passwd, int no_ui)
3048 return cryptfs_enable_internal(howarg, type, passwd, no_ui);
3051 int cryptfs_enable_default(char *howarg, int no_ui)
3053 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3054 DEFAULT_PASSWORD, no_ui);
3057 int cryptfs_changepw(int crypt_type, const char *newpw)
3059 if (e4crypt_is_native()) {
3060 SLOGE("cryptfs_changepw not valid for file encryption");
3064 struct crypt_mnt_ftr crypt_ftr;
3067 /* This is only allowed after we've successfully decrypted the master key */
3068 if (!master_key_saved) {
3069 SLOGE("Key not saved, aborting");
3073 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3074 SLOGE("Invalid crypt_type %d", crypt_type);
3079 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3080 SLOGE("Error getting crypt footer and key");
3084 crypt_ftr.crypt_type = crypt_type;
3086 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3090 crypt_ftr.master_key,
3093 SLOGE("Encrypt master key failed: %d", rc);
3097 put_crypt_ftr_and_key(&crypt_ftr);
3102 static unsigned int persist_get_max_entries(int encrypted) {
3103 struct crypt_mnt_ftr crypt_ftr;
3105 unsigned int max_persistent_entries;
3107 /* If encrypted, use the values from the crypt_ftr, otherwise
3108 * use the values for the current spec.
3111 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3114 dsize = crypt_ftr.persist_data_size;
3116 dsize = CRYPT_PERSIST_DATA_SIZE;
3119 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3120 sizeof(struct crypt_persist_entry);
3122 return max_persistent_entries;
3125 static int persist_get_key(const char *fieldname, char *value)
3129 if (persist_data == NULL) {
3132 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3133 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3135 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3143 static int persist_set_key(const char *fieldname, const char *value, int encrypted)
3147 unsigned int max_persistent_entries;
3149 if (persist_data == NULL) {
3153 max_persistent_entries = persist_get_max_entries(encrypted);
3155 num = persist_data->persist_valid_entries;
3157 for (i = 0; i < num; i++) {
3158 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3159 /* We found an existing entry, update it! */
3160 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3161 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3166 /* We didn't find it, add it to the end, if there is room */
3167 if (persist_data->persist_valid_entries < max_persistent_entries) {
3168 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3169 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3170 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3171 persist_data->persist_valid_entries++;
3179 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3180 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3182 static int match_multi_entry(const char *key, const char *field, unsigned index) {
3183 unsigned int field_len;
3184 unsigned int key_index;
3185 field_len = strlen(field);
3188 // The first key in a multi-entry field is just the filedname itself.
3189 if (!strcmp(key, field)) {
3193 // Match key against "%s_%d" % (field, index)
3194 if (strlen(key) < field_len + 1 + 1) {
3195 // Need at least a '_' and a digit.
3198 if (strncmp(key, field, field_len)) {
3199 // If the key does not begin with field, it's not a match.
3202 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3205 return key_index >= index;
3209 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3210 * remaining entries starting from index will be deleted.
3211 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3212 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3213 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3216 static int persist_del_keys(const char *fieldname, unsigned index)
3222 if (persist_data == NULL) {
3223 return PERSIST_DEL_KEY_ERROR_OTHER;
3226 num = persist_data->persist_valid_entries;
3228 j = 0; // points to the end of non-deleted entries.
3229 // Filter out to-be-deleted entries in place.
3230 for (i = 0; i < num; i++) {
3231 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3232 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3238 persist_data->persist_valid_entries = j;
3239 // Zeroise the remaining entries
3240 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3241 return PERSIST_DEL_KEY_OK;
3243 // Did not find an entry matching the given fieldname
3244 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3248 static int persist_count_keys(const char *fieldname)
3253 if (persist_data == NULL) {
3258 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3259 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3267 /* Return the value of the specified field. */
3268 int cryptfs_getfield(const char *fieldname, char *value, int len)
3270 if (e4crypt_is_native()) {
3271 SLOGE("Cannot get field when file encrypted");
3275 char temp_value[PROPERTY_VALUE_MAX];
3276 /* CRYPTO_GETFIELD_OK is success,
3277 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3278 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3279 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
3281 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3283 char temp_field[PROPERTY_KEY_MAX];
3285 if (persist_data == NULL) {
3286 load_persistent_data();
3287 if (persist_data == NULL) {
3288 SLOGE("Getfield error, cannot load persistent data");
3293 // Read value from persistent entries. If the original value is split into multiple entries,
3294 // stitch them back together.
3295 if (!persist_get_key(fieldname, temp_value)) {
3296 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3297 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3299 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3302 rc = CRYPTO_GETFIELD_OK;
3304 for (i = 1; /* break explicitly */; i++) {
3305 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3306 (int) sizeof(temp_field)) {
3307 // If the fieldname is very long, we stop as soon as it begins to overflow the
3308 // maximum field length. At this point we have in fact fully read out the original
3309 // value because cryptfs_setfield would not allow fields with longer names to be
3310 // written in the first place.
3313 if (!persist_get_key(temp_field, temp_value)) {
3314 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3316 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3320 // Exhaust all entries.
3325 /* Sadness, it's not there. Return the error */
3326 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
3333 /* Set the value of the specified field. */
3334 int cryptfs_setfield(const char *fieldname, const char *value)
3336 if (e4crypt_is_native()) {
3337 SLOGE("Cannot set field when file encrypted");
3341 char encrypted_state[PROPERTY_VALUE_MAX];
3342 /* 0 is success, negative values are error */
3343 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
3345 unsigned int field_id;
3346 char temp_field[PROPERTY_KEY_MAX];
3347 unsigned int num_entries;
3348 unsigned int max_keylen;
3350 if (persist_data == NULL) {
3351 load_persistent_data();
3352 if (persist_data == NULL) {
3353 SLOGE("Setfield error, cannot load persistent data");
3358 property_get("ro.crypto.state", encrypted_state, "");
3359 if (!strcmp(encrypted_state, "encrypted") ) {
3363 // Compute the number of entries required to store value, each entry can store up to
3364 // (PROPERTY_VALUE_MAX - 1) chars
3365 if (strlen(value) == 0) {
3366 // Empty value also needs one entry to store.
3369 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3372 max_keylen = strlen(fieldname);
3373 if (num_entries > 1) {
3374 // Need an extra "_%d" suffix.
3375 max_keylen += 1 + log10(num_entries);
3377 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3378 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
3382 // Make sure we have enough space to write the new value
3383 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3384 persist_get_max_entries(encrypted)) {
3385 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3389 // Now that we know persist_data has enough space for value, let's delete the old field first
3390 // to make up space.
3391 persist_del_keys(fieldname, 0);
3393 if (persist_set_key(fieldname, value, encrypted)) {
3394 // fail to set key, should not happen as we have already checked the available space
3395 SLOGE("persist_set_key() error during setfield()");
3399 for (field_id = 1; field_id < num_entries; field_id++) {
3400 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3402 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3403 // fail to set key, should not happen as we have already checked the available space.
3404 SLOGE("persist_set_key() error during setfield()");
3409 /* If we are running encrypted, save the persistent data now */
3411 if (save_persistent_data()) {
3412 SLOGE("Setfield error, cannot save persistent data");
3417 rc = CRYPTO_SETFIELD_OK;
3423 /* Checks userdata. Attempt to mount the volume if default-
3425 * On success trigger next init phase and return 0.
3426 * Currently do not handle failure - see TODO below.
3428 int cryptfs_mount_default_encrypted(void)
3430 int crypt_type = cryptfs_get_password_type();
3431 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3432 SLOGE("Bad crypt type - error");
3433 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3434 SLOGD("Password is not default - "
3435 "starting min framework to prompt");
3436 property_set("vold.decrypt", "trigger_restart_min_framework");
3438 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3439 SLOGD("Password is default - restarting filesystem");
3440 cryptfs_restart_internal(0);
3443 SLOGE("Encrypted, default crypt type but can't decrypt");
3446 /** Corrupt. Allow us to boot into framework, which will detect bad
3447 crypto when it calls do_crypto_complete, then do a factory reset
3449 property_set("vold.decrypt", "trigger_restart_min_framework");
3453 /* Returns type of the password, default, pattern, pin or password.
3455 int cryptfs_get_password_type(void)
3457 if (e4crypt_is_native()) {
3458 SLOGE("cryptfs_get_password_type not valid for file encryption");
3462 struct crypt_mnt_ftr crypt_ftr;
3464 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3465 SLOGE("Error getting crypt footer and key\n");
3469 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3473 return crypt_ftr.crypt_type;
3476 const char* cryptfs_get_password()
3478 if (e4crypt_is_native()) {
3479 SLOGE("cryptfs_get_password not valid for file encryption");
3483 struct timespec now;
3484 clock_gettime(CLOCK_BOOTTIME, &now);
3485 if (now.tv_sec < password_expiry_time) {
3488 cryptfs_clear_password();
3493 void cryptfs_clear_password()
3496 size_t len = strlen(password);
3497 memset(password, 0, len);
3500 password_expiry_time = 0;
3504 int cryptfs_enable_file()
3506 return e4crypt_initialize_global_de();
3509 int cryptfs_isConvertibleToFBE()
3511 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3512 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
3515 int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3517 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3518 SLOGE("Failed to initialize crypt_ftr");
3522 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3523 crypt_ftr->salt, crypt_ftr)) {
3524 SLOGE("Cannot create encrypted master key\n");
3528 //crypt_ftr->keysize = key_length / 8;
3532 int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3533 unsigned char* master_key)
3537 unsigned char* intermediate_key = 0;
3538 size_t intermediate_key_size = 0;
3540 if (password == 0 || *password == 0) {
3541 password = DEFAULT_PASSWORD;
3544 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3545 &intermediate_key_size);
3548 SLOGE("Can't calculate intermediate key");
3552 int N = 1 << ftr->N_factor;
3553 int r = 1 << ftr->r_factor;
3554 int p = 1 << ftr->p_factor;
3556 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3558 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3559 ftr->salt, sizeof(ftr->salt), N, r, p,
3560 scrypted_intermediate_key,
3561 sizeof(scrypted_intermediate_key));
3563 free(intermediate_key);
3566 SLOGE("Can't scrypt intermediate key");
3570 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3571 intermediate_key_size);
3574 int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3575 const unsigned char* master_key)
3577 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3581 void cryptfs_get_file_encryption_modes(const char **contents_mode_ret,
3582 const char **filenames_mode_ret)
3584 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3585 fs_mgr_get_file_encryption_modes(rec, contents_mode_ret, filenames_mode_ret);