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>
42 #include <linux/kdev_t.h>
47 #define LOG_TAG "Cryptfs"
48 #include "cutils/log.h"
49 #include "cutils/properties.h"
50 #include "cutils/android_reboot.h"
51 #include "hardware_legacy/power.h"
52 #include <logwrap/logwrap.h>
53 #include "VolumeManager.h"
55 #include "crypto_scrypt.h"
56 #include "Ext4Crypt.h"
57 #include "ext4_crypt_init_extensions.h"
58 #include "ext4_utils.h"
59 #include "f2fs_sparseblock.h"
60 #include "CheckBattery.h"
63 #include <hardware/keymaster0.h>
64 #include <hardware/keymaster1.h>
66 #define UNUSED __attribute__((unused))
68 #define UNUSED __attribute__((unused))
70 #ifdef CONFIG_HW_DISK_ENCRYPTION
71 #include "cryptfs_hw.h"
74 #define DM_CRYPT_BUF_SIZE 4096
76 #define HASH_COUNT 2000
77 #define KEY_LEN_BYTES 16
78 #define IV_LEN_BYTES 16
80 #define KEY_IN_FOOTER "footer"
82 #define DEFAULT_PASSWORD "default_password"
87 #define TABLE_LOAD_RETRIES 10
89 #define RSA_KEY_SIZE 2048
90 #define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
91 #define RSA_EXPONENT 0x10001
92 #define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
94 #define RETRY_MOUNT_ATTEMPTS 10
95 #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 static int previous_type;
107 inline int release_wake_lock(const char* id) { return 0; }
108 inline int acquire_wake_lock(int lock, const char* id) { return 0; }
111 #ifdef CONFIG_HW_DISK_ENCRYPTION
112 static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
113 unsigned char *ikey, void *params);
115 static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
117 const struct crypt_mnt_ftr *ftr)
119 /* if newpw updated, return 0
120 * if newpw not updated return -1
124 if (should_use_keymaster()) {
125 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
126 SLOGE("scrypt failed");
136 #ifndef MINIVOLD // no HALs in recovery...
137 static int keymaster_init(keymaster0_device_t **keymaster0_dev,
138 keymaster1_device_t **keymaster1_dev)
142 const hw_module_t* mod;
143 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
145 ALOGE("could not find any keystore module");
149 SLOGI("keymaster module name is %s", mod->name);
150 SLOGI("keymaster version is %d", mod->module_api_version);
152 *keymaster0_dev = NULL;
153 *keymaster1_dev = NULL;
154 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
155 SLOGI("Found keymaster1 module, using keymaster1 API.");
156 rc = keymaster1_open(mod, keymaster1_dev);
158 SLOGI("Found keymaster0 module, using keymaster0 API.");
159 rc = keymaster0_open(mod, keymaster0_dev);
163 ALOGE("could not open keymaster device in %s (%s)",
164 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
171 *keymaster0_dev = NULL;
172 *keymaster1_dev = NULL;
177 /* Should we use keymaster? */
178 static int keymaster_check_compatibility()
183 keymaster0_device_t *keymaster0_dev = 0;
184 keymaster1_device_t *keymaster1_dev = 0;
187 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
188 SLOGE("Failed to init keymaster");
193 if (keymaster1_dev) {
198 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
200 if (keymaster0_dev->common.module->module_api_version
201 < KEYMASTER_MODULE_API_VERSION_0_3) {
206 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
207 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
212 if (keymaster1_dev) {
213 keymaster1_close(keymaster1_dev);
215 if (keymaster0_dev) {
216 keymaster0_close(keymaster0_dev);
222 /* Create a new keymaster key and store it in this footer */
223 static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
225 #ifdef MINIVOLD // no HALs in recovery...
229 keymaster0_device_t *keymaster0_dev = 0;
230 keymaster1_device_t *keymaster1_dev = 0;
232 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
233 SLOGE("Failed to init keymaster");
239 if (keymaster1_dev) {
240 keymaster_key_param_t params[] = {
241 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
242 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
243 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
244 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
246 /* The only allowed purpose for this key is signing. */
247 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
249 /* Padding & digest specifications. */
250 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
251 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
253 /* Require that the key be usable in standalone mode. File system isn't available. */
254 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
256 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
257 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
259 /* Rate-limit key usage attempts, to rate-limit brute force */
260 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
262 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
263 keymaster_key_blob_t key_blob;
264 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, ¶m_set,
266 NULL /* characteristics */);
267 if (error != KM_ERROR_OK) {
268 SLOGE("Failed to generate keymaster1 key, error %d", error);
273 key = (uint8_t*)key_blob.key_material;
274 key_size = key_blob.key_material_size;
276 else if (keymaster0_dev) {
277 keymaster_rsa_keygen_params_t params;
278 memset(¶ms, '\0', sizeof(params));
279 params.public_exponent = RSA_EXPONENT;
280 params.modulus_size = RSA_KEY_SIZE;
282 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, ¶ms,
284 SLOGE("Failed to generate keypair");
289 SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
294 if (key_size > KEYMASTER_BLOB_SIZE) {
295 SLOGE("Keymaster key too large for crypto footer");
300 memcpy(ftr->keymaster_blob, key, key_size);
301 ftr->keymaster_blob_size = key_size;
305 keymaster0_close(keymaster0_dev);
307 keymaster1_close(keymaster1_dev);
313 /* This signs the given object using the keymaster key. */
314 static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
315 const unsigned char *object,
316 const size_t object_size,
317 unsigned char **signature,
318 size_t *signature_size)
320 #ifdef MINIVOLD // no HALs in recovery...
324 keymaster0_device_t *keymaster0_dev = 0;
325 keymaster1_device_t *keymaster1_dev = 0;
326 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
327 SLOGE("Failed to init keymaster");
332 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
333 size_t to_sign_size = sizeof(to_sign);
334 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
336 // To sign a message with RSA, the message must satisfy two
339 // 1. The message, when interpreted as a big-endian numeric value, must
340 // be strictly less than the public modulus of the RSA key. Note
341 // that because the most significant bit of the public modulus is
342 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
343 // key), an n-bit message with most significant bit 0 always
344 // satisfies this requirement.
346 // 2. The message must have the same length in bits as the public
347 // modulus of the RSA key. This requirement isn't mathematically
348 // necessary, but is necessary to ensure consistency in
350 switch (ftr->kdf_type) {
351 case KDF_SCRYPT_KEYMASTER:
352 // This ensures the most significant byte of the signed message
353 // is zero. We could have zero-padded to the left instead, but
354 // this approach is slightly more robust against changes in
355 // object size. However, it's still broken (but not unusably
356 // so) because we really should be using a proper deterministic
357 // RSA padding function, such as PKCS1.
358 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
359 SLOGI("Signing safely-padded object");
362 SLOGE("Unknown KDF type %d", ftr->kdf_type);
367 if (keymaster0_dev) {
368 keymaster_rsa_sign_params_t params;
369 params.digest_type = DIGEST_NONE;
370 params.padding_type = PADDING_NONE;
372 rc = keymaster0_dev->sign_data(keymaster0_dev,
375 ftr->keymaster_blob_size,
381 } else if (keymaster1_dev) {
382 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
383 keymaster_key_param_t params[] = {
384 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
385 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
387 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
388 keymaster_operation_handle_t op_handle;
389 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
390 ¶m_set, NULL /* out_params */,
392 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
393 // Key usage has been rate-limited. Wait a bit and try again.
394 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
395 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
396 ¶m_set, NULL /* out_params */,
399 if (error != KM_ERROR_OK) {
400 SLOGE("Error starting keymaster signature transaction: %d", error);
405 keymaster_blob_t input = { to_sign, to_sign_size };
406 size_t input_consumed;
407 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
408 &input, &input_consumed, NULL /* out_params */,
410 if (error != KM_ERROR_OK) {
411 SLOGE("Error sending data to keymaster signature transaction: %d", error);
415 if (input_consumed != to_sign_size) {
416 // This should never happen. If it does, it's a bug in the keymaster implementation.
417 SLOGE("Keymaster update() did not consume all data.");
418 keymaster1_dev->abort(keymaster1_dev, op_handle);
423 keymaster_blob_t tmp_sig;
424 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
425 NULL /* verify signature */, NULL /* out_params */,
427 if (error != KM_ERROR_OK) {
428 SLOGE("Error finishing keymaster signature transaction: %d", error);
433 *signature = (uint8_t*)tmp_sig.data;
434 *signature_size = tmp_sig.data_length;
436 SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
443 keymaster1_close(keymaster1_dev);
445 keymaster0_close(keymaster0_dev);
451 /* Store password when userdata is successfully decrypted and mounted.
452 * Cleared by cryptfs_clear_password
454 * To avoid a double prompt at boot, we need to store the CryptKeeper
455 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
456 * Since the entire framework is torn down and rebuilt after encryption,
457 * we have to use a daemon or similar to store the password. Since vold
458 * is secured against IPC except from system processes, it seems a reasonable
459 * place to store this.
461 * password should be cleared once it has been used.
463 * password is aged out after password_max_age_seconds seconds.
465 static char* password = 0;
466 static int password_expiry_time = 0;
467 static const int password_max_age_seconds = 60;
469 extern struct fstab *fstab;
471 enum RebootType {reboot, recovery, shutdown};
472 static void cryptfs_reboot(enum RebootType rt)
476 property_set(ANDROID_RB_PROPERTY, "reboot");
480 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
484 property_set(ANDROID_RB_PROPERTY, "shutdown");
490 /* Shouldn't get here, reboot should happen before sleep times out */
494 static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
496 memset(io, 0, dataSize);
497 io->data_size = dataSize;
498 io->data_start = sizeof(struct dm_ioctl);
504 strlcpy(io->name, name, sizeof(io->name));
509 * Gets the default device scrypt parameters for key derivation time tuning.
510 * The parameters should lead to about one second derivation time for the
513 static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
514 const int default_params[] = SCRYPT_DEFAULTS;
515 int params[] = SCRYPT_DEFAULTS;
516 char paramstr[PROPERTY_VALUE_MAX];
521 property_get(SCRYPT_PROP, paramstr, "");
522 if (paramstr[0] != '\0') {
524 * The token we're looking for should be three integers separated by
525 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
527 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
528 token != NULL && i < 3;
529 i++, token = strtok_r(NULL, ":", &saveptr)) {
531 params[i] = strtol(token, &endptr, 10);
534 * Check that there was a valid number and it's 8-bit. If not,
535 * break out and the end check will take the default values.
537 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
543 * If there were not enough tokens or a token was malformed (not an
544 * integer), it will end up here and the default parameters can be
547 if ((i != 3) || (token != NULL)) {
548 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
549 memcpy(params, default_params, sizeof(params));
553 ftr->N_factor = params[0];
554 ftr->r_factor = params[1];
555 ftr->p_factor = params[2];
558 static unsigned int get_fs_size(char *dev)
561 struct ext4_super_block sb;
564 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
565 SLOGE("Cannot open device to get filesystem size ");
569 if (lseek64(fd, 1024, SEEK_SET) < 0) {
570 SLOGE("Cannot seek to superblock");
574 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
575 SLOGE("Cannot read superblock");
581 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
582 SLOGE("Not a valid ext4 superblock");
585 block_size = 1024 << sb.s_log_block_size;
586 /* compute length in bytes */
587 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
589 /* return length in sectors */
590 return (unsigned int) (len / 512);
593 static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
595 static int cached_data = 0;
596 static off64_t cached_off = 0;
597 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
599 char key_loc[PROPERTY_VALUE_MAX];
600 char real_blkdev[PROPERTY_VALUE_MAX];
604 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
606 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
607 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
608 SLOGE("Cannot open real block device %s\n", real_blkdev);
612 unsigned long nr_sec = 0;
613 get_blkdev_size(fd, &nr_sec);
615 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
616 * encryption info footer and key, and plenty of bytes to spare for future
619 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
620 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
623 SLOGE("Cannot get size of block device %s\n", real_blkdev);
627 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
634 if (metadata_fname) {
635 *metadata_fname = cached_metadata_fname;
646 /* key or salt can be NULL, in which case just skip writing that value. Useful to
647 * update the failed mount count but not change the key.
649 static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
653 /* starting_off is set to the SEEK_SET offset
654 * where the crypto structure starts
656 off64_t starting_off;
661 if (get_crypt_ftr_info(&fname, &starting_off)) {
662 SLOGE("Unable to get crypt_ftr_info\n");
665 if (fname[0] != '/') {
666 SLOGE("Unexpected value for crypto key location\n");
669 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
670 SLOGE("Cannot open footer file %s for put\n", fname);
674 /* Seek to the start of the crypt footer */
675 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
676 SLOGE("Cannot seek to real block device footer\n");
680 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
681 SLOGE("Cannot write real block device footer\n");
686 /* If the keys are kept on a raw block device, do not try to truncate it. */
687 if (S_ISREG(statbuf.st_mode)) {
688 if (ftruncate(fd, 0x4000)) {
689 SLOGE("Cannot set footer file size\n");
703 static inline int unix_read(int fd, void* buff, int len)
705 return TEMP_FAILURE_RETRY(read(fd, buff, len));
708 static inline int unix_write(int fd, const void* buff, int len)
710 return TEMP_FAILURE_RETRY(write(fd, buff, len));
713 static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
715 memset(pdata, 0, len);
716 pdata->persist_magic = PERSIST_DATA_MAGIC;
717 pdata->persist_valid_entries = 0;
720 /* A routine to update the passed in crypt_ftr to the lastest version.
721 * fd is open read/write on the device that holds the crypto footer and persistent
722 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
723 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
725 static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
727 int orig_major = crypt_ftr->major_version;
728 int orig_minor = crypt_ftr->minor_version;
730 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
731 struct crypt_persist_data *pdata;
732 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
734 SLOGW("upgrading crypto footer to 1.1");
736 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
738 SLOGE("Cannot allocate persisent data\n");
741 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
743 /* Need to initialize the persistent data area */
744 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
745 SLOGE("Cannot seek to persisent data offset\n");
749 /* Write all zeros to the first copy, making it invalid */
750 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
752 /* Write a valid but empty structure to the second copy */
753 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
754 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
756 /* Update the footer */
757 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
758 crypt_ftr->persist_data_offset[0] = pdata_offset;
759 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
760 crypt_ftr->minor_version = 1;
764 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
765 SLOGW("upgrading crypto footer to 1.2");
766 /* But keep the old kdf_type.
767 * It will get updated later to KDF_SCRYPT after the password has been verified.
769 crypt_ftr->kdf_type = KDF_PBKDF2;
770 get_device_scrypt_params(crypt_ftr);
771 crypt_ftr->minor_version = 2;
774 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
775 SLOGW("upgrading crypto footer to 1.3");
776 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
777 crypt_ftr->minor_version = 3;
780 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
781 if (lseek64(fd, offset, SEEK_SET) == -1) {
782 SLOGE("Cannot seek to crypt footer\n");
785 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
790 static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
794 off64_t starting_off;
799 if (get_crypt_ftr_info(&fname, &starting_off)) {
800 SLOGE("Unable to get crypt_ftr_info\n");
803 if (fname[0] != '/') {
804 SLOGE("Unexpected value for crypto key location\n");
807 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
808 SLOGE("Cannot open footer file %s for get\n", fname);
812 /* Make sure it's 16 Kbytes in length */
814 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
815 SLOGE("footer file %s is not the expected size!\n", fname);
819 /* Seek to the start of the crypt footer */
820 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
821 SLOGE("Cannot seek to real block device footer\n");
825 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
826 SLOGE("Cannot read real block device footer\n");
830 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
831 SLOGE("Bad magic for real block device %s\n", fname);
835 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
836 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
837 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
841 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
842 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
843 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
846 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
847 * copy on disk before returning.
849 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
850 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
861 static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
863 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
864 crypt_ftr->persist_data_offset[1]) {
865 SLOGE("Crypt_ftr persist data regions overlap");
869 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
870 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
874 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
875 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
876 CRYPT_FOOTER_OFFSET) {
877 SLOGE("Persistent data extends past crypto footer");
884 static int load_persistent_data(void)
886 struct crypt_mnt_ftr crypt_ftr;
887 struct crypt_persist_data *pdata = NULL;
888 char encrypted_state[PROPERTY_VALUE_MAX];
896 /* Nothing to do, we've already loaded or initialized it */
901 /* If not encrypted, just allocate an empty table and initialize it */
902 property_get("ro.crypto.state", encrypted_state, "");
903 if (strcmp(encrypted_state, "encrypted") ) {
904 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
906 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
907 persist_data = pdata;
913 if(get_crypt_ftr_and_key(&crypt_ftr)) {
917 if ((crypt_ftr.major_version < 1)
918 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
919 SLOGE("Crypt_ftr version doesn't support persistent data");
923 if (get_crypt_ftr_info(&fname, NULL)) {
927 ret = validate_persistent_data_storage(&crypt_ftr);
932 fd = open(fname, O_RDONLY|O_CLOEXEC);
934 SLOGE("Cannot open %s metadata file", fname);
938 if (persist_data == NULL) {
939 pdata = malloc(crypt_ftr.persist_data_size);
941 SLOGE("Cannot allocate memory for persistent data");
946 for (i = 0; i < 2; i++) {
947 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
948 SLOGE("Cannot seek to read persistent data on %s", fname);
951 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
952 SLOGE("Error reading persistent data on iteration %d", i);
955 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
962 SLOGI("Could not find valid persistent data, creating");
963 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
967 persist_data = pdata;
979 static int save_persistent_data(void)
981 struct crypt_mnt_ftr crypt_ftr;
982 struct crypt_persist_data *pdata;
984 off64_t write_offset;
985 off64_t erase_offset;
989 if (persist_data == NULL) {
990 SLOGE("No persistent data to save");
994 if(get_crypt_ftr_and_key(&crypt_ftr)) {
998 if ((crypt_ftr.major_version < 1)
999 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
1000 SLOGE("Crypt_ftr version doesn't support persistent data");
1004 ret = validate_persistent_data_storage(&crypt_ftr);
1009 if (get_crypt_ftr_info(&fname, NULL)) {
1013 fd = open(fname, O_RDWR|O_CLOEXEC);
1015 SLOGE("Cannot open %s metadata file", fname);
1019 pdata = malloc(crypt_ftr.persist_data_size);
1020 if (pdata == NULL) {
1021 SLOGE("Cannot allocate persistant data");
1025 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1026 SLOGE("Cannot seek to read persistent data on %s", fname);
1030 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
1031 SLOGE("Error reading persistent data before save");
1035 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1036 /* The first copy is the curent valid copy, so write to
1037 * the second copy and erase this one */
1038 write_offset = crypt_ftr.persist_data_offset[1];
1039 erase_offset = crypt_ftr.persist_data_offset[0];
1041 /* The second copy must be the valid copy, so write to
1042 * the first copy, and erase the second */
1043 write_offset = crypt_ftr.persist_data_offset[0];
1044 erase_offset = crypt_ftr.persist_data_offset[1];
1047 /* Write the new copy first, if successful, then erase the old copy */
1048 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
1049 SLOGE("Cannot seek to write persistent data");
1052 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1053 (int) crypt_ftr.persist_data_size) {
1054 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
1055 SLOGE("Cannot seek to erase previous persistent data");
1059 memset(pdata, 0, crypt_ftr.persist_data_size);
1060 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1061 (int) crypt_ftr.persist_data_size) {
1062 SLOGE("Cannot write to erase previous persistent data");
1067 SLOGE("Cannot write to save persistent data");
1083 /* Convert a binary key of specified length into an ascii hex string equivalent,
1084 * without the leading 0x and with null termination
1086 static void convert_key_to_hex_ascii(const unsigned char *master_key,
1087 unsigned int keysize, char *master_key_ascii) {
1089 unsigned char nibble;
1091 for (i=0, a=0; i<keysize; i++, a+=2) {
1092 /* For each byte, write out two ascii hex digits */
1093 nibble = (master_key[i] >> 4) & 0xf;
1094 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
1096 nibble = master_key[i] & 0xf;
1097 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1100 /* Add the null termination */
1101 master_key_ascii[a] = '\0';
1105 static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1106 const unsigned char *master_key, const char *real_blk_name,
1107 const char *name, int fd, const char *extra_params) {
1108 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1109 struct dm_ioctl *io;
1110 struct dm_target_spec *tgt;
1112 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1115 io = (struct dm_ioctl *) buffer;
1117 /* Load the mapping table for this device */
1118 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1120 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1121 io->target_count = 1;
1123 tgt->sector_start = 0;
1124 tgt->length = crypt_ftr->fs_size;
1125 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1127 #ifdef CONFIG_HW_DISK_ENCRYPTION
1128 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1129 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1130 if (is_ice_enabled())
1131 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1133 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1136 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1137 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1140 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1141 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1144 snprintf(crypt_params,
1145 sizeof(buffer)-sizeof(struct dm_ioctl)-sizeof(struct dm_target_spec),
1146 "%s %s 0 %s 0 %s 0",
1147 crypt_ftr->crypto_type_name, master_key_ascii,
1148 real_blk_name, extra_params);
1150 SLOGI("target_type = %s", tgt->target_type);
1151 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1153 crypt_params += strlen(crypt_params) + 1;
1154 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1155 tgt->next = crypt_params - buffer;
1157 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1158 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1164 if (i == TABLE_LOAD_RETRIES) {
1165 /* We failed to load the table, return an error */
1172 static int get_dm_crypt_version(int fd, const char *name, int *version)
1174 char buffer[DM_CRYPT_BUF_SIZE];
1175 struct dm_ioctl *io;
1176 struct dm_target_versions *v;
1178 io = (struct dm_ioctl *) buffer;
1180 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1182 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1186 /* Iterate over the returned versions, looking for name of "crypt".
1187 * When found, get and return the version.
1189 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1191 if (! strcmp(v->name, "crypt")) {
1193 /* We found the crypt driver, return the version, and get out */
1194 version[0] = v->version[0];
1195 version[1] = v->version[1];
1196 version[2] = v->version[2];
1199 v = (struct dm_target_versions *)(((char *)v) + v->next);
1205 static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1206 const unsigned char *master_key, const char *real_blk_name,
1207 char *crypto_blk_name, const char *name) {
1208 char buffer[DM_CRYPT_BUF_SIZE];
1209 struct dm_ioctl *io;
1216 #ifdef CONFIG_HW_DISK_ENCRYPTION
1217 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1218 char progress[PROPERTY_VALUE_MAX] = {0};
1221 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
1222 SLOGE("Cannot open device-mapper\n");
1226 io = (struct dm_ioctl *) buffer;
1228 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1229 if (ioctl(fd, DM_DEV_CREATE, io)) {
1230 SLOGE("Cannot create dm-crypt device\n");
1234 /* Get the device status, in particular, the name of it's device file */
1235 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1236 if (ioctl(fd, DM_DEV_STATUS, io)) {
1237 SLOGE("Cannot retrieve dm-crypt device status\n");
1240 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1241 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1243 #ifdef CONFIG_HW_DISK_ENCRYPTION
1244 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1245 /* Set fde_enabled if either FDE completed or in-progress */
1246 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1247 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1248 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1249 if (is_ice_enabled())
1250 extra_params = "fde_enabled ice";
1252 extra_params = "fde_enabled";
1254 extra_params = "fde_disabled";
1257 if (! get_dm_crypt_version(fd, name, version)) {
1258 /* Support for allow_discards was added in version 1.11.0 */
1259 if ((version[0] >= 2) ||
1260 ((version[0] == 1) && (version[1] >= 11))) {
1261 extra_params = "1 allow_discards";
1262 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1268 if (! get_dm_crypt_version(fd, name, version)) {
1269 /* Support for allow_discards was added in version 1.11.0 */
1270 if ((version[0] >= 2) ||
1271 ((version[0] == 1) && (version[1] >= 11))) {
1272 extra_params = "1 allow_discards";
1273 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1278 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1280 if (load_count < 0) {
1281 SLOGE("Cannot load dm-crypt mapping table.\n");
1283 } else if (load_count > 1) {
1284 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1287 /* Resume this device to activate it */
1288 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1290 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1291 SLOGE("Cannot resume the dm-crypt device\n");
1295 /* We made it here with no errors. Woot! */
1299 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1304 static int delete_crypto_blk_dev(char *name)
1307 char buffer[DM_CRYPT_BUF_SIZE];
1308 struct dm_ioctl *io;
1311 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
1312 SLOGE("Cannot open device-mapper\n");
1316 io = (struct dm_ioctl *) buffer;
1318 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1319 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1320 SLOGE("Cannot remove dm-crypt device\n");
1324 /* We made it here with no errors. Woot! */
1328 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1334 static int pbkdf2(const char *passwd, const unsigned char *salt,
1335 unsigned char *ikey, void *params UNUSED)
1337 SLOGI("Using pbkdf2 for cryptfs KDF");
1339 /* Turn the password into a key and IV that can decrypt the master key */
1340 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd),
1342 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
1347 static int scrypt(const char *passwd, const unsigned char *salt,
1348 unsigned char *ikey, void *params)
1350 SLOGI("Using scrypt for cryptfs KDF");
1352 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1354 int N = 1 << ftr->N_factor;
1355 int r = 1 << ftr->r_factor;
1356 int p = 1 << ftr->p_factor;
1358 /* Turn the password into a key and IV that can decrypt the master key */
1359 unsigned int keysize;
1360 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1361 salt, SALT_LEN, N, r, p, ikey,
1362 KEY_LEN_BYTES + IV_LEN_BYTES);
1367 static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1368 unsigned char *ikey, void *params)
1370 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1373 size_t signature_size;
1374 unsigned char* signature;
1375 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1377 int N = 1 << ftr->N_factor;
1378 int r = 1 << ftr->r_factor;
1379 int p = 1 << ftr->p_factor;
1381 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1382 salt, SALT_LEN, N, r, p, ikey,
1383 KEY_LEN_BYTES + IV_LEN_BYTES);
1386 SLOGE("scrypt failed");
1390 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1391 &signature, &signature_size)) {
1392 SLOGE("Signing failed");
1396 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1397 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1401 SLOGE("scrypt failed");
1408 static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1409 const unsigned char *decrypted_master_key,
1410 unsigned char *encrypted_master_key,
1411 struct crypt_mnt_ftr *crypt_ftr,
1412 bool create_keymaster_key)
1414 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1415 EVP_CIPHER_CTX e_ctx;
1416 int encrypted_len, final_len;
1419 /* Turn the password into an intermediate key and IV that can decrypt the master key */
1420 get_device_scrypt_params(crypt_ftr);
1422 switch (crypt_ftr->kdf_type) {
1423 case KDF_SCRYPT_KEYMASTER:
1424 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
1425 SLOGE("keymaster_create_key failed");
1429 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1430 SLOGE("scrypt failed");
1436 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1437 SLOGE("scrypt failed");
1443 SLOGE("Invalid kdf_type");
1447 /* Initialize the decryption engine */
1448 EVP_CIPHER_CTX_init(&e_ctx);
1449 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
1450 SLOGE("EVP_EncryptInit failed\n");
1453 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
1455 /* Encrypt the master key */
1456 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1457 decrypted_master_key, KEY_LEN_BYTES)) {
1458 SLOGE("EVP_EncryptUpdate failed\n");
1461 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
1462 SLOGE("EVP_EncryptFinal failed\n");
1466 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1467 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1471 /* Store the scrypt of the intermediate key, so we can validate if it's a
1472 password error or mount error when things go wrong.
1473 Note there's no need to check for errors, since if this is incorrect, we
1474 simply won't wipe userdata, which is the correct default behavior
1476 int N = 1 << crypt_ftr->N_factor;
1477 int r = 1 << crypt_ftr->r_factor;
1478 int p = 1 << crypt_ftr->p_factor;
1480 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1481 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1482 crypt_ftr->scrypted_intermediate_key,
1483 sizeof(crypt_ftr->scrypted_intermediate_key));
1486 SLOGE("encrypt_master_key: crypto_scrypt failed");
1492 static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
1493 unsigned char *encrypted_master_key,
1494 unsigned char *decrypted_master_key,
1495 kdf_func kdf, void *kdf_params,
1496 unsigned char** intermediate_key,
1497 size_t* intermediate_key_size)
1499 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1500 EVP_CIPHER_CTX d_ctx;
1501 int decrypted_len, final_len;
1503 /* Turn the password into an intermediate key and IV that can decrypt the
1505 if (kdf(passwd, salt, ikey, kdf_params)) {
1506 SLOGE("kdf failed");
1510 /* Initialize the decryption engine */
1511 EVP_CIPHER_CTX_init(&d_ctx);
1512 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
1515 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1516 /* Decrypt the master key */
1517 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1518 encrypted_master_key, KEY_LEN_BYTES)) {
1521 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1525 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1529 /* Copy intermediate key if needed by params */
1530 if (intermediate_key && intermediate_key_size) {
1531 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1532 if (intermediate_key) {
1533 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1534 *intermediate_key_size = KEY_LEN_BYTES;
1541 static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
1543 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1544 *kdf = scrypt_keymaster;
1546 } else if (ftr->kdf_type == KDF_SCRYPT) {
1555 static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
1556 struct crypt_mnt_ftr *crypt_ftr,
1557 unsigned char** intermediate_key,
1558 size_t* intermediate_key_size)
1564 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1565 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1566 decrypted_master_key, kdf, kdf_params,
1567 intermediate_key, intermediate_key_size);
1569 SLOGW("failure decrypting master key");
1575 static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1576 struct crypt_mnt_ftr *crypt_ftr) {
1578 unsigned char key_buf[KEY_LEN_BYTES];
1580 /* Get some random bits for a key */
1581 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
1582 read(fd, key_buf, sizeof(key_buf));
1583 read(fd, salt, SALT_LEN);
1586 /* Now encrypt it with the password */
1587 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
1590 int wait_and_unmount(const char *mountpoint, bool kill)
1593 #define WAIT_UNMOUNT_COUNT 20
1595 /* Now umount the tmpfs filesystem */
1596 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1597 if (umount(mountpoint) == 0) {
1601 if (errno == EINVAL) {
1602 /* EINVAL is returned if the directory is not a mountpoint,
1603 * i.e. there is no filesystem mounted there. So just get out.
1610 /* If allowed, be increasingly aggressive before the last two retries */
1612 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1613 SLOGW("sending SIGHUP to processes with open files\n");
1614 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
1615 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1616 SLOGW("sending SIGKILL to processes with open files\n");
1617 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
1624 if (i < WAIT_UNMOUNT_COUNT) {
1625 SLOGD("unmounting %s succeeded\n", mountpoint);
1628 vold_killProcessesWithOpenFiles(mountpoint, 0);
1629 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1636 #define DATA_PREP_TIMEOUT 1000
1637 static int prep_data_fs(void)
1641 /* Do the prep of the /data filesystem */
1642 property_set("vold.post_fs_data_done", "0");
1643 property_set("vold.decrypt", "trigger_post_fs_data");
1644 SLOGD("Just triggered post_fs_data\n");
1646 /* Wait a max of 50 seconds, hopefully it takes much less */
1647 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
1648 char p[PROPERTY_VALUE_MAX];
1650 property_get("vold.post_fs_data_done", p, "0");
1657 if (i == DATA_PREP_TIMEOUT) {
1658 /* Ugh, we failed to prep /data in time. Bail. */
1659 SLOGE("post_fs_data timed out!\n");
1662 SLOGD("post_fs_data done\n");
1667 static void cryptfs_set_corrupt()
1669 // Mark the footer as bad
1670 struct crypt_mnt_ftr crypt_ftr;
1671 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1672 SLOGE("Failed to get crypto footer - panic");
1676 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1677 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1678 SLOGE("Failed to set crypto footer - panic");
1683 static void cryptfs_trigger_restart_min_framework()
1685 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1686 SLOGE("Failed to mount tmpfs on data - panic");
1690 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1691 SLOGE("Failed to trigger post fs data - panic");
1695 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1696 SLOGE("Failed to trigger restart min framework - panic");
1701 /* returns < 0 on failure */
1702 static int cryptfs_restart_internal(int restart_main)
1704 char crypto_blkdev[MAXPATHLEN];
1706 static int restart_successful = 0;
1708 /* Validate that it's OK to call this routine */
1709 if (! master_key_saved) {
1710 SLOGE("Encrypted filesystem not validated, aborting");
1714 if (restart_successful) {
1715 SLOGE("System already restarted with encrypted disk, aborting");
1720 /* Here is where we shut down the framework. The init scripts
1721 * start all services in one of three classes: core, main or late_start.
1722 * On boot, we start core and main. Now, we stop main, but not core,
1723 * as core includes vold and a few other really important things that
1724 * we need to keep running. Once main has stopped, we should be able
1725 * to umount the tmpfs /data, then mount the encrypted /data.
1726 * We then restart the class main, and also the class late_start.
1727 * At the moment, I've only put a few things in late_start that I know
1728 * are not needed to bring up the framework, and that also cause problems
1729 * with unmounting the tmpfs /data, but I hope to add add more services
1730 * to the late_start class as we optimize this to decrease the delay
1731 * till the user is asked for the password to the filesystem.
1734 /* The init files are setup to stop the class main when vold.decrypt is
1735 * set to trigger_reset_main.
1737 property_set("vold.decrypt", "trigger_reset_main");
1738 SLOGD("Just asked init to shut down class main\n");
1740 /* Ugh, shutting down the framework is not synchronous, so until it
1741 * can be fixed, this horrible hack will wait a moment for it all to
1742 * shut down before proceeding. Without it, some devices cannot
1743 * restart the graphics services.
1748 /* Now that the framework is shutdown, we should be able to umount()
1749 * the tmpfs filesystem, and mount the real one.
1752 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1753 if (strlen(crypto_blkdev) == 0) {
1754 SLOGE("fs_crypto_blkdev not set\n");
1758 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
1759 /* If ro.crypto.readonly is set to 1, mount the decrypted
1760 * filesystem readonly. This is used when /data is mounted by
1763 char ro_prop[PROPERTY_VALUE_MAX];
1764 property_get("ro.crypto.readonly", ro_prop, "");
1765 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1766 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1767 rec->flags |= MS_RDONLY;
1770 /* If that succeeded, then mount the decrypted filesystem */
1771 int retries = RETRY_MOUNT_ATTEMPTS;
1773 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1776 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1777 /* TODO: invoke something similar to
1778 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1779 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1780 SLOGI("Failed to mount %s because it is busy - waiting",
1783 sleep(RETRY_MOUNT_DELAY_SECONDS);
1785 /* Let's hope that a reboot clears away whatever is keeping
1787 cryptfs_reboot(reboot);
1790 SLOGE("Failed to mount decrypted data");
1791 cryptfs_set_corrupt();
1792 cryptfs_trigger_restart_min_framework();
1793 SLOGI("Started framework to offer wipe");
1798 property_set("vold.decrypt", "trigger_load_persist_props");
1799 /* Create necessary paths on /data */
1800 if (prep_data_fs()) {
1804 /* startup service classes main and late_start */
1805 property_set("vold.decrypt", "trigger_restart_framework");
1806 SLOGD("Just triggered restart_framework\n");
1808 /* Give it a few moments to get started */
1813 restart_successful = 1;
1819 int cryptfs_restart(void)
1821 SLOGI("cryptfs_restart");
1822 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
1823 struct fstab_rec* rec;
1826 if (e4crypt_restart(DATA_MNT_POINT)) {
1827 SLOGE("Can't unmount e4crypt temp volume\n");
1831 rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1833 SLOGE("Can't get fstab record for %s\n", DATA_MNT_POINT);
1837 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, rec->blk_device, 0);
1839 SLOGE("Can't mount %s\n", DATA_MNT_POINT);
1843 property_set("vold.decrypt", "trigger_restart_framework");
1847 /* Call internal implementation forcing a restart of main service group */
1848 return cryptfs_restart_internal(1);
1851 static int do_crypto_complete(char *mount_point)
1853 struct crypt_mnt_ftr crypt_ftr;
1854 char encrypted_state[PROPERTY_VALUE_MAX];
1855 char key_loc[PROPERTY_VALUE_MAX];
1857 property_get("ro.crypto.state", encrypted_state, "");
1858 if (strcmp(encrypted_state, "encrypted") ) {
1859 SLOGE("not running with encryption, aborting");
1860 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1863 if (e4crypt_crypto_complete(mount_point) == 0) {
1864 return CRYPTO_COMPLETE_ENCRYPTED;
1867 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1868 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
1871 * Only report this error if key_loc is a file and it exists.
1872 * If the device was never encrypted, and /data is not mountable for
1873 * some reason, returning 1 should prevent the UI from presenting the
1874 * a "enter password" screen, or worse, a "press button to wipe the
1877 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1878 SLOGE("master key file does not exist, aborting");
1879 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1881 SLOGE("Error getting crypt footer and key\n");
1882 return CRYPTO_COMPLETE_BAD_METADATA;
1886 // Test for possible error flags
1887 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1888 SLOGE("Encryption process is partway completed\n");
1889 return CRYPTO_COMPLETE_PARTIAL;
1892 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1893 SLOGE("Encryption process was interrupted but cannot continue\n");
1894 return CRYPTO_COMPLETE_INCONSISTENT;
1897 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1898 SLOGE("Encryption is successful but data is corrupt\n");
1899 return CRYPTO_COMPLETE_CORRUPT;
1902 /* We passed the test! We shall diminish, and return to the west */
1903 return CRYPTO_COMPLETE_ENCRYPTED;
1906 static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1907 char *passwd, char *mount_point, char *label)
1909 /* Allocate enough space for a 256 bit key, but we may use less */
1910 unsigned char decrypted_master_key[32];
1911 char crypto_blkdev[MAXPATHLEN];
1912 char real_blkdev[MAXPATHLEN];
1913 char tmp_mount_point[64];
1914 unsigned int orig_failed_decrypt_count;
1916 int use_keymaster = 0;
1918 unsigned char* intermediate_key = 0;
1919 size_t intermediate_key_size = 0;
1921 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1922 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
1924 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1925 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1926 &intermediate_key, &intermediate_key_size)) {
1927 SLOGE("Failed to decrypt master key\n");
1933 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1935 #ifdef CONFIG_HW_DISK_ENCRYPTION
1937 unsigned char newpw[32];
1938 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1939 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
1940 key_index = set_hw_device_encryption_key(passwd,
1941 (char*) crypt_ftr->crypto_type_name);
1943 key_index = set_hw_device_encryption_key((const char*)newpw,
1944 (char*) crypt_ftr->crypto_type_name);
1945 if (key_index < 0) {
1946 rc = ++crypt_ftr->failed_decrypt_count;
1947 put_crypt_ftr_and_key(crypt_ftr);
1951 if (is_ice_enabled()) {
1952 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
1953 real_blkdev, crypto_blkdev, label)) {
1954 SLOGE("Error creating decrypted block device");
1959 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1960 real_blkdev, crypto_blkdev, label)) {
1961 SLOGE("Error creating decrypted block device");
1968 /* in case HW FDE is delivered through OTA and device is already encrypted
1969 * using SW FDE, we should let user continue using SW FDE until userdata is
1972 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1973 real_blkdev, crypto_blkdev, label)) {
1974 SLOGE("Error creating decrypted block device");
1980 // Create crypto block device - all (non fatal) code paths
1982 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1983 real_blkdev, crypto_blkdev, label)) {
1984 SLOGE("Error creating decrypted block device\n");
1990 /* Work out if the problem is the password or the data */
1991 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1992 scrypted_intermediate_key)];
1993 int N = 1 << crypt_ftr->N_factor;
1994 int r = 1 << crypt_ftr->r_factor;
1995 int p = 1 << crypt_ftr->p_factor;
1997 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1998 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1999 N, r, p, scrypted_intermediate_key,
2000 sizeof(scrypted_intermediate_key));
2002 // Does the key match the crypto footer?
2003 if (rc == 0 && memcmp(scrypted_intermediate_key,
2004 crypt_ftr->scrypted_intermediate_key,
2005 sizeof(scrypted_intermediate_key)) == 0) {
2006 SLOGI("Password matches");
2009 /* Try mounting the file system anyway, just in case the problem's with
2010 * the footer, not the key. */
2011 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
2012 mkdir(tmp_mount_point, 0755);
2013 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
2014 SLOGE("Error temp mounting decrypted block device\n");
2015 delete_crypto_blk_dev(label);
2017 rc = ++crypt_ftr->failed_decrypt_count;
2018 put_crypt_ftr_and_key(crypt_ftr);
2021 SLOGI("Password did not match but decrypted drive mounted - continue");
2022 umount(tmp_mount_point);
2028 crypt_ftr->failed_decrypt_count = 0;
2029 if (orig_failed_decrypt_count != 0) {
2030 put_crypt_ftr_and_key(crypt_ftr);
2033 /* Save the name of the crypto block device
2034 * so we can mount it when restarting the framework. */
2035 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2037 /* Also save a the master key so we can reencrypted the key
2038 * the key when we want to change the password on it. */
2039 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
2040 saved_mount_point = strdup(mount_point);
2041 master_key_saved = 1;
2042 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2045 // Upgrade if we're not using the latest KDF.
2046 use_keymaster = keymaster_check_compatibility();
2047 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2048 // Don't allow downgrade
2049 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2050 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2052 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2053 crypt_ftr->kdf_type = KDF_SCRYPT;
2058 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
2059 crypt_ftr->master_key, crypt_ftr, true);
2061 rc = put_crypt_ftr_and_key(crypt_ftr);
2063 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2065 // Do not fail even if upgrade failed - machine is bootable
2066 // Note that if this code is ever hit, there is a *serious* problem
2067 // since KDFs should never fail. You *must* fix the kdf before
2070 SLOGW("Upgrade failed with error %d,"
2071 " but continuing with previous state",
2079 if (intermediate_key) {
2080 memset(intermediate_key, 0, intermediate_key_size);
2081 free(intermediate_key);
2087 * Called by vold when it's asked to mount an encrypted external
2088 * storage volume. The incoming partition has no crypto header/footer,
2089 * as any metadata is been stored in a separate, small partition.
2091 * out_crypto_blkdev must be MAXPATHLEN.
2093 int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
2094 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
2095 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
2097 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
2101 unsigned long nr_sec = 0;
2102 get_blkdev_size(fd, &nr_sec);
2106 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
2110 struct crypt_mnt_ftr ext_crypt_ftr;
2111 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2112 ext_crypt_ftr.fs_size = nr_sec;
2113 ext_crypt_ftr.keysize = keysize;
2114 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
2116 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
2117 out_crypto_blkdev, label);
2121 * Called by vold when it's asked to unmount an encrypted external
2124 int cryptfs_revert_ext_volume(const char* label) {
2125 return delete_crypto_blk_dev((char*) label);
2128 int cryptfs_crypto_complete(void)
2130 int mdtp_activated = fs_mgr_is_mdtp_activated();
2131 int crypto_state = do_crypto_complete("/data");
2133 /* if MDTP is activated, it should be reflected in the crypto state */
2135 if (crypto_state != CRYPTO_COMPLETE_ENCRYPTED ){
2136 /* MDTP is activated and crypto state is bad */
2137 return CRYPTO_COMPLETE_ERROR_MDTP_ACTIVATED;
2139 /* MDTP is activated and crypto state is ok */
2140 return CRYPTO_COMPLETE_ENCRYPTED_MDTP_ACTIVATED;
2144 /* mdtp is not activated, return the crypto state only */
2145 return crypto_state;
2148 int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2150 char encrypted_state[PROPERTY_VALUE_MAX];
2151 property_get("ro.crypto.state", encrypted_state, "");
2152 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2153 SLOGE("encrypted fs already validated or not running with encryption,"
2158 if (get_crypt_ftr_and_key(crypt_ftr)) {
2159 SLOGE("Error getting crypt footer and key");
2166 int cryptfs_check_passwd(char *passwd)
2168 SLOGI("cryptfs_check_passwd");
2169 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
2170 return e4crypt_check_passwd(DATA_MNT_POINT, passwd);
2173 struct crypt_mnt_ftr crypt_ftr;
2176 rc = check_unmounted_and_get_ftr(&crypt_ftr);
2180 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2181 DATA_MNT_POINT, "userdata");
2183 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2184 cryptfs_clear_password();
2185 password = strdup(passwd);
2186 struct timespec now;
2187 clock_gettime(CLOCK_BOOTTIME, &now);
2188 password_expiry_time = now.tv_sec + password_max_age_seconds;
2194 int cryptfs_verify_passwd(char *passwd)
2196 struct crypt_mnt_ftr crypt_ftr;
2197 /* Allocate enough space for a 256 bit key, but we may use less */
2198 unsigned char decrypted_master_key[32];
2199 char encrypted_state[PROPERTY_VALUE_MAX];
2202 property_get("ro.crypto.state", encrypted_state, "");
2203 if (strcmp(encrypted_state, "encrypted") ) {
2204 SLOGE("device not encrypted, aborting");
2208 if (!master_key_saved) {
2209 SLOGE("encrypted fs not yet mounted, aborting");
2213 if (!saved_mount_point) {
2214 SLOGE("encrypted fs failed to save mount point, aborting");
2218 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2219 SLOGE("Error getting crypt footer and key\n");
2223 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2224 /* If the device has no password, then just say the password is valid */
2227 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2228 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2229 /* They match, the password is correct */
2232 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2241 /* Initialize a crypt_mnt_ftr structure. The keysize is
2242 * defaulted to 16 bytes, and the filesystem size to 0.
2243 * Presumably, at a minimum, the caller will update the
2244 * filesystem size and crypto_type_name after calling this function.
2246 static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
2250 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
2251 ftr->magic = CRYPT_MNT_MAGIC;
2252 ftr->major_version = CURRENT_MAJOR_VERSION;
2253 ftr->minor_version = CURRENT_MINOR_VERSION;
2254 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
2255 ftr->keysize = KEY_LEN_BYTES;
2257 switch (keymaster_check_compatibility()) {
2259 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2263 ftr->kdf_type = KDF_SCRYPT;
2267 SLOGE("keymaster_check_compatibility failed");
2271 get_device_scrypt_params(ftr);
2273 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2274 if (get_crypt_ftr_info(NULL, &off) == 0) {
2275 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2276 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2277 ftr->persist_data_size;
2283 static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
2285 const char *args[10];
2286 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2292 if (type == EXT4_FS) {
2293 args[0] = "/system/bin/make_ext4fs";
2297 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
2299 args[5] = crypto_blkdev;
2301 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2302 args[0], args[1], args[2], args[3], args[4], args[5]);
2303 } else if (type == F2FS_FS) {
2304 args[0] = "/system/bin/mkfs.f2fs";
2307 args[3] = crypto_blkdev;
2308 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
2311 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2312 args[0], args[1], args[2], args[3], args[4]);
2314 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2318 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2321 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
2323 if (WIFEXITED(status)) {
2324 if (WEXITSTATUS(status)) {
2325 SLOGE("Error creating filesystem on %s, exit status %d ",
2326 crypto_blkdev, WEXITSTATUS(status));
2328 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2332 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2339 #define CRYPT_INPLACE_BUFSIZE 4096
2340 #define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2341 #define CRYPT_SECTOR_SIZE 512
2343 /* aligned 32K writes tends to make flash happy.
2344 * SD card association recommends it.
2346 #ifndef CONFIG_HW_DISK_ENCRYPTION
2347 #define BLOCKS_AT_A_TIME 8
2349 #define BLOCKS_AT_A_TIME 1024
2352 struct encryptGroupsData
2357 off64_t one_pct, cur_pct, new_pct;
2358 off64_t blocks_already_done, tot_numblocks;
2359 off64_t used_blocks_already_done, tot_used_blocks;
2360 char* real_blkdev, * crypto_blkdev;
2364 off64_t last_written_sector;
2366 time_t time_started;
2370 static void update_progress(struct encryptGroupsData* data, int is_used)
2372 data->blocks_already_done++;
2375 data->used_blocks_already_done++;
2377 if (data->tot_used_blocks) {
2378 data->new_pct = data->used_blocks_already_done / data->one_pct;
2380 data->new_pct = data->blocks_already_done / data->one_pct;
2383 if (data->new_pct > data->cur_pct) {
2385 data->cur_pct = data->new_pct;
2386 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
2387 property_set("vold.encrypt_progress", buf);
2390 if (data->cur_pct >= 5) {
2391 struct timespec time_now;
2392 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2393 SLOGW("Error getting time");
2395 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2396 off64_t remaining_blocks = data->tot_used_blocks
2397 - data->used_blocks_already_done;
2398 int remaining_time = (int)(elapsed_time * remaining_blocks
2399 / data->used_blocks_already_done);
2401 // Change time only if not yet set, lower, or a lot higher for
2402 // best user experience
2403 if (data->remaining_time == -1
2404 || remaining_time < data->remaining_time
2405 || remaining_time > data->remaining_time + 60) {
2407 snprintf(buf, sizeof(buf), "%d", remaining_time);
2408 property_set("vold.encrypt_time_remaining", buf);
2409 data->remaining_time = remaining_time;
2415 static void log_progress(struct encryptGroupsData const* data, bool completed)
2417 // Precondition - if completed data = 0 else data != 0
2419 // Track progress so we can skip logging blocks
2420 static off64_t offset = -1;
2422 // Need to close existing 'Encrypting from' log?
2423 if (completed || (offset != -1 && data->offset != offset)) {
2424 SLOGI("Encrypted to sector %" PRId64,
2425 offset / info.block_size * CRYPT_SECTOR_SIZE);
2429 // Need to start new 'Encrypting from' log?
2430 if (!completed && offset != data->offset) {
2431 SLOGI("Encrypting from sector %" PRId64,
2432 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2437 offset = data->offset + (off64_t)data->count * info.block_size;
2441 static int flush_outstanding_data(struct encryptGroupsData* data)
2443 if (data->count == 0) {
2447 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
2449 if (pread64(data->realfd, data->buffer,
2450 info.block_size * data->count, data->offset)
2452 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2457 if (pwrite64(data->cryptofd, data->buffer,
2458 info.block_size * data->count, data->offset)
2460 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2461 data->crypto_blkdev);
2464 log_progress(data, false);
2468 data->last_written_sector = (data->offset + data->count)
2469 / info.block_size * CRYPT_SECTOR_SIZE - 1;
2473 static int encrypt_groups(struct encryptGroupsData* data)
2476 u8 *block_bitmap = 0;
2481 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2482 if (!data->buffer) {
2483 SLOGE("Failed to allocate crypto buffer");
2487 block_bitmap = malloc(info.block_size);
2488 if (!block_bitmap) {
2489 SLOGE("failed to allocate block bitmap");
2493 for (i = 0; i < aux_info.groups; ++i) {
2494 SLOGI("Encrypting group %d", i);
2496 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2497 u32 block_count = min(info.blocks_per_group,
2498 aux_info.len_blocks - first_block);
2500 off64_t offset = (u64)info.block_size
2501 * aux_info.bg_desc[i].bg_block_bitmap;
2503 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2504 if (ret != (int)info.block_size) {
2505 SLOGE("failed to read all of block group bitmap %d", i);
2509 offset = (u64)info.block_size * first_block;
2513 for (block = 0; block < block_count; block++) {
2514 int used = bitmap_get_bit(block_bitmap, block);
2515 update_progress(data, used);
2517 if (data->count == 0) {
2518 data->offset = offset;
2522 if (flush_outstanding_data(data)) {
2527 offset += info.block_size;
2529 /* Write data if we are aligned or buffer size reached */
2530 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2531 || data->count == BLOCKS_AT_A_TIME) {
2532 if (flush_outstanding_data(data)) {
2537 if (!is_battery_ok_to_continue()) {
2538 SLOGE("Stopping encryption due to low battery");
2544 if (flush_outstanding_data(data)) {
2549 data->completed = 1;
2553 log_progress(0, true);
2559 static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2562 off64_t *size_already_done,
2564 off64_t previously_encrypted_upto)
2567 struct encryptGroupsData data;
2568 int rc; // Can't initialize without causing warning -Wclobbered
2570 if (previously_encrypted_upto > *size_already_done) {
2571 SLOGD("Not fast encrypting since resuming part way through");
2575 memset(&data, 0, sizeof(data));
2576 data.real_blkdev = real_blkdev;
2577 data.crypto_blkdev = crypto_blkdev;
2579 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
2580 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2581 real_blkdev, errno, strerror(errno));
2586 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2587 int retries = RETRY_MOUNT_ATTEMPTS;
2588 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2590 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2591 crypto_blkdev, errno, strerror(errno));
2592 sleep(RETRY_MOUNT_DELAY_SECONDS);
2594 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2595 crypto_blkdev, errno, strerror(errno));
2596 rc = ENABLE_INPLACE_ERR_DEV;
2601 if (setjmp(setjmp_env)) {
2602 SLOGE("Reading ext4 extent caused an exception\n");
2607 if (read_ext(data.realfd, 0) != 0) {
2608 SLOGE("Failed to read ext4 extent\n");
2613 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2614 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2615 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2617 SLOGI("Encrypting ext4 filesystem in place...");
2619 data.tot_used_blocks = data.numblocks;
2620 for (i = 0; i < aux_info.groups; ++i) {
2621 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2624 data.one_pct = data.tot_used_blocks / 100;
2627 struct timespec time_started = {0};
2628 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2629 SLOGW("Error getting time at start");
2630 // Note - continue anyway - we'll run with 0
2632 data.time_started = time_started.tv_sec;
2633 data.remaining_time = -1;
2635 rc = encrypt_groups(&data);
2637 SLOGE("Error encrypting groups");
2641 *size_already_done += data.completed ? size : data.last_written_sector;
2646 close(data.cryptofd);
2651 static void log_progress_f2fs(u64 block, bool completed)
2653 // Precondition - if completed data = 0 else data != 0
2655 // Track progress so we can skip logging blocks
2656 static u64 last_block = (u64)-1;
2658 // Need to close existing 'Encrypting from' log?
2659 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2660 SLOGI("Encrypted to block %" PRId64, last_block);
2664 // Need to start new 'Encrypting from' log?
2665 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2666 SLOGI("Encrypting from block %" PRId64, block);
2675 static int encrypt_one_block_f2fs(u64 pos, void *data)
2677 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2679 priv_dat->blocks_already_done = pos - 1;
2680 update_progress(priv_dat, 1);
2682 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2684 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2685 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
2689 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2690 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
2693 log_progress_f2fs(pos, false);
2699 static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2702 off64_t *size_already_done,
2704 off64_t previously_encrypted_upto)
2706 struct encryptGroupsData data;
2707 struct f2fs_info *f2fs_info = NULL;
2708 int rc = ENABLE_INPLACE_ERR_OTHER;
2709 if (previously_encrypted_upto > *size_already_done) {
2710 SLOGD("Not fast encrypting since resuming part way through");
2711 return ENABLE_INPLACE_ERR_OTHER;
2713 memset(&data, 0, sizeof(data));
2714 data.real_blkdev = real_blkdev;
2715 data.crypto_blkdev = crypto_blkdev;
2718 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
2719 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
2723 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2724 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
2725 crypto_blkdev, errno, strerror(errno));
2726 rc = ENABLE_INPLACE_ERR_DEV;
2730 f2fs_info = generate_f2fs_info(data.realfd);
2734 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2735 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2736 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2738 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2740 data.one_pct = data.tot_used_blocks / 100;
2742 data.time_started = time(NULL);
2743 data.remaining_time = -1;
2745 data.buffer = malloc(f2fs_info->block_size);
2747 SLOGE("Failed to allocate crypto buffer");
2753 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2754 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2757 SLOGE("Error in running over f2fs blocks");
2758 rc = ENABLE_INPLACE_ERR_OTHER;
2762 *size_already_done += size;
2767 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2769 log_progress_f2fs(0, true);
2773 close(data.cryptofd);
2778 static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2779 off64_t size, off64_t *size_already_done,
2781 off64_t previously_encrypted_upto)
2783 int realfd, cryptofd;
2784 char *buf[CRYPT_INPLACE_BUFSIZE];
2785 int rc = ENABLE_INPLACE_ERR_OTHER;
2786 off64_t numblocks, i, remainder;
2787 off64_t one_pct, cur_pct, new_pct;
2788 off64_t blocks_already_done, tot_numblocks;
2790 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
2791 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2792 return ENABLE_INPLACE_ERR_OTHER;
2795 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
2796 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2797 crypto_blkdev, errno, strerror(errno));
2799 return ENABLE_INPLACE_ERR_DEV;
2802 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2803 * The size passed in is the number of 512 byte sectors in the filesystem.
2804 * So compute the number of whole 4K blocks we should read/write,
2805 * and the remainder.
2807 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2808 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
2809 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2810 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2812 SLOGE("Encrypting filesystem in place...");
2814 i = previously_encrypted_upto + 1 - *size_already_done;
2816 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2817 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2821 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2822 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2826 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2827 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2828 SLOGE("Error reading initial sectors from real_blkdev %s for "
2829 "inplace encrypt\n", crypto_blkdev);
2832 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2833 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2834 "inplace encrypt\n", crypto_blkdev);
2837 SLOGI("Encrypted 1 block at %" PRId64, i);
2841 one_pct = tot_numblocks / 100;
2843 /* process the majority of the filesystem in blocks */
2844 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
2845 new_pct = (i + blocks_already_done) / one_pct;
2846 if (new_pct > cur_pct) {
2850 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
2851 property_set("vold.encrypt_progress", buf);
2853 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
2854 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
2857 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
2858 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2861 SLOGD("Encrypted %d block at %" PRId64,
2862 CRYPT_SECTORS_PER_BUFSIZE,
2863 i * CRYPT_SECTORS_PER_BUFSIZE);
2866 if (!is_battery_ok_to_continue()) {
2867 SLOGE("Stopping encryption due to low battery");
2868 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2874 /* Do any remaining sectors */
2875 for (i=0; i<remainder; i++) {
2876 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2877 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
2880 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2881 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2884 SLOGI("Encrypted 1 block at next location");
2888 *size_already_done += size;
2898 /* returns on of the ENABLE_INPLACE_* return codes */
2899 static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2900 off64_t size, off64_t *size_already_done,
2902 off64_t previously_encrypted_upto)
2904 int rc_ext4, rc_f2fs, rc_full;
2905 if (previously_encrypted_upto) {
2906 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
2909 if (*size_already_done + size < previously_encrypted_upto) {
2910 *size_already_done += size;
2914 /* TODO: identify filesystem type.
2915 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2916 * then we will drop down to cryptfs_enable_inplace_f2fs.
2918 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
2919 size, size_already_done,
2920 tot_size, previously_encrypted_upto)) == 0) {
2923 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
2925 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2926 size, size_already_done,
2927 tot_size, previously_encrypted_upto)) == 0) {
2930 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
2932 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
2933 size, size_already_done, tot_size,
2934 previously_encrypted_upto);
2935 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2937 /* Hack for b/17898962, the following is the symptom... */
2938 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2939 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2940 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2941 return ENABLE_INPLACE_ERR_DEV;
2946 #define CRYPTO_ENABLE_WIPE 1
2947 #define CRYPTO_ENABLE_INPLACE 2
2949 #define FRAMEWORK_BOOT_WAIT 60
2951 static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2953 int fd = open(filename, O_RDONLY|O_CLOEXEC);
2955 SLOGE("Error opening file %s", filename);
2959 char block[CRYPT_INPLACE_BUFSIZE];
2960 memset(block, 0, sizeof(block));
2961 if (unix_read(fd, block, sizeof(block)) < 0) {
2962 SLOGE("Error reading file %s", filename);
2971 SHA256_Update(&c, block, sizeof(block));
2972 SHA256_Final(buf, &c);
2977 static int get_fs_type(struct fstab_rec *rec)
2979 if (!strcmp(rec->fs_type, "ext4")) {
2981 } else if (!strcmp(rec->fs_type, "f2fs")) {
2988 static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2989 char *crypto_blkdev, char *real_blkdev,
2990 int previously_encrypted_upto)
2992 off64_t cur_encryption_done=0, tot_encryption_size=0;
2995 if (!is_battery_ok_to_start()) {
2996 SLOGW("Not starting encryption due to low battery");
3000 /* The size of the userdata partition, and add in the vold volumes below */
3001 tot_encryption_size = crypt_ftr->fs_size;
3003 if (how == CRYPTO_ENABLE_WIPE) {
3004 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3005 int fs_type = get_fs_type(rec);
3007 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
3010 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
3011 } else if (how == CRYPTO_ENABLE_INPLACE) {
3012 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
3013 crypt_ftr->fs_size, &cur_encryption_done,
3014 tot_encryption_size,
3015 previously_encrypted_upto);
3017 if (rc == ENABLE_INPLACE_ERR_DEV) {
3018 /* Hack for b/17898962 */
3019 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
3020 cryptfs_reboot(reboot);
3024 crypt_ftr->encrypted_upto = cur_encryption_done;
3027 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
3028 /* The inplace routine never actually sets the progress to 100% due
3029 * to the round down nature of integer division, so set it here */
3030 property_set("vold.encrypt_progress", "100");
3033 /* Shouldn't happen */
3034 SLOGE("cryptfs_enable: internal error, unknown option\n");
3041 int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
3045 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
3046 unsigned char decrypted_master_key[KEY_LEN_BYTES];
3048 struct crypt_mnt_ftr crypt_ftr;
3049 struct crypt_persist_data *pdata;
3050 char encrypted_state[PROPERTY_VALUE_MAX];
3051 char lockid[32] = { 0 };
3052 char key_loc[PROPERTY_VALUE_MAX];
3054 off64_t previously_encrypted_upto = 0;
3055 #ifdef CONFIG_HW_DISK_ENCRYPTION
3056 unsigned char newpw[32];
3060 if (!strcmp(howarg, "wipe")) {
3061 how = CRYPTO_ENABLE_WIPE;
3062 } else if (! strcmp(howarg, "inplace")) {
3063 how = CRYPTO_ENABLE_INPLACE;
3065 /* Shouldn't happen, as CommandListener vets the args */
3066 goto error_unencrypted;
3069 /* See if an encryption was underway and interrupted */
3070 if (how == CRYPTO_ENABLE_INPLACE
3071 && get_crypt_ftr_and_key(&crypt_ftr) == 0
3072 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
3073 previously_encrypted_upto = crypt_ftr.encrypted_upto;
3074 crypt_ftr.encrypted_upto = 0;
3075 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
3077 /* At this point, we are in an inconsistent state. Until we successfully
3078 complete encryption, a reboot will leave us broken. So mark the
3079 encryption failed in case that happens.
3080 On successfully completing encryption, remove this flag */
3081 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3083 put_crypt_ftr_and_key(&crypt_ftr);
3086 property_get("ro.crypto.state", encrypted_state, "");
3087 if (how != CRYPTO_ENABLE_WIPE && !strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
3088 SLOGE("Device is already running encrypted, aborting");
3089 goto error_unencrypted;
3092 // TODO refactor fs_mgr_get_crypt_info to get both in one call
3093 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
3094 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
3096 /* Get the size of the real block device */
3097 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
3099 SLOGE("Cannot open block device %s\n", real_blkdev);
3100 goto error_unencrypted;
3102 unsigned long nr_sec;
3103 get_blkdev_size(fd, &nr_sec);
3105 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3106 goto error_unencrypted;
3110 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
3111 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
3112 unsigned int fs_size_sec, max_fs_size_sec;
3113 fs_size_sec = get_fs_size(real_blkdev);
3114 if (fs_size_sec == 0)
3115 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3117 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3119 if (fs_size_sec > max_fs_size_sec) {
3120 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3121 goto error_unencrypted;
3125 /* Get a wakelock as this may take a while, and we don't want the
3126 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3127 * wants to keep the screen on, it can grab a full wakelock.
3129 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
3130 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3132 /* The init files are setup to stop the class main and late start when
3133 * vold sets trigger_shutdown_framework.
3135 property_set("vold.decrypt", "trigger_shutdown_framework");
3136 SLOGD("Just asked init to shut down class main\n");
3138 /* Ask vold to unmount all devices that it manages */
3139 if (vold_unmountAll()) {
3140 SLOGE("Failed to unmount all vold managed devices");
3143 /* Now unmount the /data partition. */
3144 if (wait_and_unmount(DATA_MNT_POINT, false)) {
3146 goto error_shutting_down;
3148 goto error_unencrypted;
3152 /* Start the actual work of making an encrypted filesystem */
3153 /* Initialize a crypt_mnt_ftr for the partition */
3154 if (previously_encrypted_upto == 0) {
3155 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3156 goto error_shutting_down;
3159 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3160 crypt_ftr.fs_size = nr_sec
3161 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3163 crypt_ftr.fs_size = nr_sec;
3165 /* At this point, we are in an inconsistent state. Until we successfully
3166 complete encryption, a reboot will leave us broken. So mark the
3167 encryption failed in case that happens.
3168 On successfully completing encryption, remove this flag */
3169 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3170 crypt_ftr.crypt_type = crypt_type;
3171 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3173 /* Make an encrypted master key */
3174 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3175 SLOGE("Cannot create encrypted master key\n");
3176 goto error_shutting_down;
3179 #ifdef CONFIG_HW_DISK_ENCRYPTION
3180 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3181 clear_hw_device_encryption_key();
3182 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr.salt,
3184 key_index = set_hw_device_encryption_key(passwd, (char*)crypt_ftr.crypto_type_name);
3186 key_index = set_hw_device_encryption_key((const char*)newpw,
3187 (char*) crypt_ftr.crypto_type_name);
3189 goto error_shutting_down;
3192 /* Write the key to the end of the partition */
3193 put_crypt_ftr_and_key(&crypt_ftr);
3195 /* If any persistent data has been remembered, save it.
3196 * If none, create a valid empty table and save that.
3198 if (!persist_data) {
3199 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3201 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3202 persist_data = pdata;
3206 save_persistent_data();
3210 /* Do extra work for a better UX when doing the long inplace encryption */
3211 if (how == CRYPTO_ENABLE_INPLACE) {
3212 /* Now that /data is unmounted, we need to mount a tmpfs
3213 * /data, set a property saying we're doing inplace encryption,
3214 * and restart the framework.
3216 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
3217 goto error_shutting_down;
3219 /* Tells the framework that inplace encryption is starting */
3220 property_set("vold.encrypt_progress", "0");
3222 /* restart the framework. */
3223 /* Create necessary paths on /data */
3224 if (prep_data_fs()) {
3225 goto error_shutting_down;
3228 /* Ugh, shutting down the framework is not synchronous, so until it
3229 * can be fixed, this horrible hack will wait a moment for it all to
3230 * shut down before proceeding. Without it, some devices cannot
3231 * restart the graphics services.
3235 /* startup service classes main and late_start */
3236 property_set("vold.decrypt", "trigger_restart_min_framework");
3237 SLOGD("Just triggered restart_min_framework\n");
3239 /* OK, the framework is restarted and will soon be showing a
3240 * progress bar. Time to setup an encrypted mapping, and
3241 * either write a new filesystem, or encrypt in place updating
3242 * the progress bar as we work.
3246 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
3247 #ifdef CONFIG_HW_DISK_ENCRYPTION
3248 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
3249 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev, crypto_blkdev,
3252 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3256 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3260 /* If we are continuing, check checksums match */
3262 if (previously_encrypted_upto) {
3263 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3264 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
3266 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3267 sizeof(hash_first_block)) != 0) {
3268 SLOGE("Checksums do not match - trigger wipe");
3274 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3275 crypto_blkdev, real_blkdev,
3276 previously_encrypted_upto);
3279 /* Calculate checksum if we are not finished */
3280 if (!rc && how == CRYPTO_ENABLE_INPLACE
3281 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
3282 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3283 crypt_ftr.hash_first_block);
3285 SLOGE("Error calculating checksum for continuing encryption");
3290 /* Undo the dm-crypt mapping whether we succeed or not */
3291 delete_crypto_blk_dev("userdata");
3295 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
3297 if (how == CRYPTO_ENABLE_INPLACE
3298 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
3299 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3300 crypt_ftr.encrypted_upto);
3301 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
3304 put_crypt_ftr_and_key(&crypt_ftr);
3306 if (how == CRYPTO_ENABLE_WIPE
3307 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
3308 char value[PROPERTY_VALUE_MAX];
3309 property_get("ro.crypto.state", value, "");
3310 if (!strcmp(value, "")) {
3311 /* default encryption - continue first boot sequence */
3312 property_set("ro.crypto.state", "encrypted");
3313 release_wake_lock(lockid);
3314 cryptfs_check_passwd(DEFAULT_PASSWORD);
3315 cryptfs_restart_internal(1);
3318 sleep(2); /* Give the UI a chance to show 100% progress */
3319 cryptfs_reboot(reboot);
3322 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
3323 cryptfs_reboot(shutdown);
3326 char value[PROPERTY_VALUE_MAX];
3328 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
3329 if (!strcmp(value, "1")) {
3330 /* wipe data if encryption failed */
3331 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3332 mkdir("/cache/recovery", 0700);
3333 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
3335 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3336 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
3339 SLOGE("could not open /cache/recovery/command\n");
3341 cryptfs_reboot(recovery);
3343 /* set property to trigger dialog */
3344 property_set("vold.encrypt_progress", "error_partially_encrypted");
3345 release_wake_lock(lockid);
3350 /* hrm, the encrypt step claims success, but the reboot failed.
3351 * This should not happen.
3352 * Set the property and return. Hope the framework can deal with it.
3354 property_set("vold.encrypt_progress", "error_reboot_failed");
3355 release_wake_lock(lockid);
3359 property_set("vold.encrypt_progress", "error_not_encrypted");
3361 release_wake_lock(lockid);
3365 error_shutting_down:
3366 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3367 * but the framework is stopped and not restarted to show the error, so it's up to
3368 * vold to restart the system.
3370 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
3371 cryptfs_reboot(reboot);
3373 /* shouldn't get here */
3374 property_set("vold.encrypt_progress", "error_shutting_down");
3376 release_wake_lock(lockid);
3381 int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
3383 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3386 int cryptfs_enable_default(char *howarg, int allow_reboot)
3388 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3389 DEFAULT_PASSWORD, allow_reboot);
3392 int cryptfs_changepw(int crypt_type, const char *currentpw, const char *newpw)
3394 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3395 return e4crypt_change_password(DATA_MNT_POINT, crypt_type,
3396 crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3400 struct crypt_mnt_ftr crypt_ftr;
3403 /* This is only allowed after we've successfully decrypted the master key */
3404 if (!master_key_saved) {
3405 SLOGE("Key not saved, aborting");
3409 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3410 SLOGE("Invalid crypt_type %d", crypt_type);
3415 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3416 SLOGE("Error getting crypt footer and key");
3420 #ifdef CONFIG_HW_DISK_ENCRYPTION
3422 unsigned char tmp_curpw[32] = {0};
3423 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3424 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3425 crypt_ftr.salt, &crypt_ftr);
3429 crypt_ftr.crypt_type = crypt_type;
3431 if (previous_type == CRYPT_TYPE_DEFAULT)
3432 currentpw = DEFAULT_PASSWORD;
3433 previous_type = crypt_type;
3435 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3439 crypt_ftr.master_key,
3442 SLOGE("Encrypt master key failed: %d", rc);
3446 put_crypt_ftr_and_key(&crypt_ftr);
3448 #ifdef CONFIG_HW_DISK_ENCRYPTION
3450 unsigned char tmp_newpw[32] = {0};
3452 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3453 DEFAULT_PASSWORD : newpw , tmp_newpw,
3454 crypt_ftr.salt, &crypt_ftr);
3456 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3457 ret = update_hw_device_encryption_key(
3458 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3459 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3460 (char*)crypt_ftr.crypto_type_name);
3462 SLOGE("Error updating device encryption hardware key ret %d", ret);
3465 SLOGI("Encryption hardware key updated");
3472 static unsigned int persist_get_max_entries(int encrypted) {
3473 struct crypt_mnt_ftr crypt_ftr;
3475 unsigned int max_persistent_entries;
3477 /* If encrypted, use the values from the crypt_ftr, otherwise
3478 * use the values for the current spec.
3481 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3484 dsize = crypt_ftr.persist_data_size;
3486 dsize = CRYPT_PERSIST_DATA_SIZE;
3489 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3490 sizeof(struct crypt_persist_entry);
3492 return max_persistent_entries;
3495 static int persist_get_key(const char *fieldname, char *value)
3499 if (persist_data == NULL) {
3502 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3503 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3505 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3513 static int persist_set_key(const char *fieldname, const char *value, int encrypted)
3517 unsigned int max_persistent_entries;
3519 if (persist_data == NULL) {
3523 max_persistent_entries = persist_get_max_entries(encrypted);
3525 num = persist_data->persist_valid_entries;
3527 for (i = 0; i < num; i++) {
3528 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3529 /* We found an existing entry, update it! */
3530 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3531 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3536 /* We didn't find it, add it to the end, if there is room */
3537 if (persist_data->persist_valid_entries < max_persistent_entries) {
3538 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3539 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3540 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3541 persist_data->persist_valid_entries++;
3549 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3550 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3552 static int match_multi_entry(const char *key, const char *field, unsigned index) {
3553 unsigned int field_len;
3554 unsigned int key_index;
3555 field_len = strlen(field);
3558 // The first key in a multi-entry field is just the filedname itself.
3559 if (!strcmp(key, field)) {
3563 // Match key against "%s_%d" % (field, index)
3564 if (strlen(key) < field_len + 1 + 1) {
3565 // Need at least a '_' and a digit.
3568 if (strncmp(key, field, field_len)) {
3569 // If the key does not begin with field, it's not a match.
3572 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3575 return key_index >= index;
3579 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3580 * remaining entries starting from index will be deleted.
3581 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3582 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3583 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3586 static int persist_del_keys(const char *fieldname, unsigned index)
3592 if (persist_data == NULL) {
3593 return PERSIST_DEL_KEY_ERROR_OTHER;
3596 num = persist_data->persist_valid_entries;
3598 j = 0; // points to the end of non-deleted entries.
3599 // Filter out to-be-deleted entries in place.
3600 for (i = 0; i < num; i++) {
3601 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3602 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3608 persist_data->persist_valid_entries = j;
3609 // Zeroise the remaining entries
3610 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3611 return PERSIST_DEL_KEY_OK;
3613 // Did not find an entry matching the given fieldname
3614 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3618 static int persist_count_keys(const char *fieldname)
3623 if (persist_data == NULL) {
3628 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3629 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3637 /* Return the value of the specified field. */
3638 int cryptfs_getfield(const char *fieldname, char *value, int len)
3640 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3641 return e4crypt_get_field(DATA_MNT_POINT, fieldname, value, len);
3644 char temp_value[PROPERTY_VALUE_MAX];
3645 /* CRYPTO_GETFIELD_OK is success,
3646 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3647 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3648 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
3650 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3652 char temp_field[PROPERTY_KEY_MAX];
3654 if (persist_data == NULL) {
3655 load_persistent_data();
3656 if (persist_data == NULL) {
3657 SLOGE("Getfield error, cannot load persistent data");
3662 // Read value from persistent entries. If the original value is split into multiple entries,
3663 // stitch them back together.
3664 if (!persist_get_key(fieldname, temp_value)) {
3665 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3666 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3668 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3671 rc = CRYPTO_GETFIELD_OK;
3673 for (i = 1; /* break explicitly */; i++) {
3674 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3675 (int) sizeof(temp_field)) {
3676 // If the fieldname is very long, we stop as soon as it begins to overflow the
3677 // maximum field length. At this point we have in fact fully read out the original
3678 // value because cryptfs_setfield would not allow fields with longer names to be
3679 // written in the first place.
3682 if (!persist_get_key(temp_field, temp_value)) {
3683 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3685 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3689 // Exhaust all entries.
3694 /* Sadness, it's not there. Return the error */
3695 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
3702 /* Set the value of the specified field. */
3703 int cryptfs_setfield(const char *fieldname, const char *value)
3705 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3706 return e4crypt_set_field(DATA_MNT_POINT, fieldname, value);
3709 char encrypted_state[PROPERTY_VALUE_MAX];
3710 /* 0 is success, negative values are error */
3711 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
3713 unsigned int field_id;
3714 char temp_field[PROPERTY_KEY_MAX];
3715 unsigned int num_entries;
3716 unsigned int max_keylen;
3718 if (persist_data == NULL) {
3719 load_persistent_data();
3720 if (persist_data == NULL) {
3721 SLOGE("Setfield error, cannot load persistent data");
3726 property_get("ro.crypto.state", encrypted_state, "");
3727 if (!strcmp(encrypted_state, "encrypted") ) {
3731 // Compute the number of entries required to store value, each entry can store up to
3732 // (PROPERTY_VALUE_MAX - 1) chars
3733 if (strlen(value) == 0) {
3734 // Empty value also needs one entry to store.
3737 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3740 max_keylen = strlen(fieldname);
3741 if (num_entries > 1) {
3742 // Need an extra "_%d" suffix.
3743 max_keylen += 1 + log10(num_entries);
3745 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3746 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
3750 // Make sure we have enough space to write the new value
3751 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3752 persist_get_max_entries(encrypted)) {
3753 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3757 // Now that we know persist_data has enough space for value, let's delete the old field first
3758 // to make up space.
3759 persist_del_keys(fieldname, 0);
3761 if (persist_set_key(fieldname, value, encrypted)) {
3762 // fail to set key, should not happen as we have already checked the available space
3763 SLOGE("persist_set_key() error during setfield()");
3767 for (field_id = 1; field_id < num_entries; field_id++) {
3768 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3770 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3771 // fail to set key, should not happen as we have already checked the available space.
3772 SLOGE("persist_set_key() error during setfield()");
3777 /* If we are running encrypted, save the persistent data now */
3779 if (save_persistent_data()) {
3780 SLOGE("Setfield error, cannot save persistent data");
3785 rc = CRYPTO_SETFIELD_OK;
3791 /* Checks userdata. Attempt to mount the volume if default-
3793 * On success trigger next init phase and return 0.
3794 * Currently do not handle failure - see TODO below.
3796 int cryptfs_mount_default_encrypted(void)
3798 char decrypt_state[PROPERTY_VALUE_MAX];
3799 property_get("vold.decrypt", decrypt_state, "0");
3800 if (!strcmp(decrypt_state, "0")) {
3801 SLOGE("Not encrypted - should not call here");
3803 int crypt_type = cryptfs_get_password_type();
3804 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3805 SLOGE("Bad crypt type - error");
3806 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3807 SLOGD("Password is not default - "
3808 "starting min framework to prompt");
3809 property_set("vold.decrypt", "trigger_restart_min_framework");
3811 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3812 SLOGD("Password is default - restarting filesystem");
3813 cryptfs_restart_internal(0);
3816 SLOGE("Encrypted, default crypt type but can't decrypt");
3820 /** Corrupt. Allow us to boot into framework, which will detect bad
3821 crypto when it calls do_crypto_complete, then do a factory reset
3823 property_set("vold.decrypt", "trigger_restart_min_framework");
3827 /* Returns type of the password, default, pattern, pin or password.
3829 int cryptfs_get_password_type(void)
3831 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3832 return e4crypt_get_password_type(DATA_MNT_POINT);
3835 struct crypt_mnt_ftr crypt_ftr;
3837 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3838 SLOGE("Error getting crypt footer and key\n");
3842 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3846 return crypt_ftr.crypt_type;
3849 const char* cryptfs_get_password()
3851 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3852 return e4crypt_get_password(DATA_MNT_POINT);
3855 struct timespec now;
3856 clock_gettime(CLOCK_BOOTTIME, &now);
3857 if (now.tv_sec < password_expiry_time) {
3860 cryptfs_clear_password();
3865 void cryptfs_clear_password()
3867 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3868 e4crypt_clear_password(DATA_MNT_POINT);
3872 size_t len = strlen(password);
3873 memset(password, 0, len);
3876 password_expiry_time = 0;
3880 int cryptfs_enable_file()
3882 return e4crypt_enable(DATA_MNT_POINT);
3885 int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3887 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3888 SLOGE("Failed to initialize crypt_ftr");
3892 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3893 crypt_ftr->salt, crypt_ftr)) {
3894 SLOGE("Cannot create encrypted master key\n");
3898 //crypt_ftr->keysize = key_length / 8;
3902 int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3903 unsigned char* master_key)
3907 unsigned char* intermediate_key = 0;
3908 size_t intermediate_key_size = 0;
3910 if (password == 0 || *password == 0) {
3911 password = DEFAULT_PASSWORD;
3914 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3915 &intermediate_key_size);
3917 int N = 1 << ftr->N_factor;
3918 int r = 1 << ftr->r_factor;
3919 int p = 1 << ftr->p_factor;
3921 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3923 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3924 ftr->salt, sizeof(ftr->salt), N, r, p,
3925 scrypted_intermediate_key,
3926 sizeof(scrypted_intermediate_key));
3928 free(intermediate_key);
3931 SLOGE("Can't calculate intermediate key");
3935 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3936 intermediate_key_size);
3939 int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3940 const unsigned char* master_key)
3942 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,