blob: b58c3436b4426ab32ea701af22d6263d80fff884 [file] [log] [blame]
bigbiffa957f072021-03-07 18:20:29 -05001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Cryptfs"
18
19#include "cryptfs.h"
20
21#include "Checkpoint.h"
22#include "CryptoType.h"
23#include "EncryptInplace.h"
24#include "FsCrypt.h"
25#include "Keymaster.h"
26#include "Process.h"
27#include "ScryptParameters.h"
28#include "Utils.h"
29#include "VoldUtil.h"
30#include "VolumeManager.h"
31
32#include <android-base/parseint.h>
33#include <android-base/properties.h>
34#include <android-base/stringprintf.h>
35#include <android-base/strings.h>
36#include <bootloader_message/bootloader_message.h>
37#include <cutils/android_reboot.h>
38#include <cutils/properties.h>
39#include <ext4_utils/ext4_utils.h>
40#include <f2fs_sparseblock.h>
41#include <fs_mgr.h>
42#include <fscrypt/fscrypt.h>
43#include <libdm/dm.h>
44#include <log/log.h>
45#include <logwrap/logwrap.h>
46#include <openssl/evp.h>
47#include <openssl/sha.h>
48#include <selinux/selinux.h>
49// #include <wakelock/wakelock.h>
50
51#include <ctype.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <inttypes.h>
55#include <libgen.h>
56#include <linux/kdev_t.h>
57#include <math.h>
58#include <mntent.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <sys/mount.h>
63#include <sys/param.h>
64#include <sys/stat.h>
65#include <sys/types.h>
66#include <sys/wait.h>
67#include <time.h>
68#include <unistd.h>
69
70#include <chrono>
71#include <thread>
72
73extern "C" {
74#include <crypto_scrypt.h>
75}
76
77using android::base::ParseUint;
78using android::base::StringPrintf;
79using android::fs_mgr::GetEntryForMountPoint;
80using ::CryptoType;
81using ::KeyBuffer;
82using ::KeyGeneration;
83using namespace android::dm;
84using namespace std::chrono_literals;
85
86/* The current cryptfs version */
87#define CURRENT_MAJOR_VERSION 1
88#define CURRENT_MINOR_VERSION 3
89
90#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
91#define CRYPT_PERSIST_DATA_SIZE 0x1000
92
93#define MAX_CRYPTO_TYPE_NAME_LEN 64
94
95#define MAX_KEY_LEN 48
96#define SALT_LEN 16
97#define SCRYPT_LEN 32
98
99/* definitions of flags in the structure below */
100#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
101#define CRYPT_ENCRYPTION_IN_PROGRESS \
102 0x2 /* Encryption partially completed, \
103 encrypted_upto valid*/
104#define CRYPT_INCONSISTENT_STATE \
105 0x4 /* Set when starting encryption, clear when \
106 exit cleanly, either through success or \
107 correctly marked partial encryption */
108#define CRYPT_DATA_CORRUPT \
109 0x8 /* Set when encryption is fine, but the \
110 underlying volume is corrupt */
111#define CRYPT_FORCE_ENCRYPTION \
112 0x10 /* Set when it is time to encrypt this \
113 volume on boot. Everything in this \
114 structure is set up correctly as \
115 though device is encrypted except \
116 that the master key is encrypted with the \
117 default password. */
118#define CRYPT_FORCE_COMPLETE \
119 0x20 /* Set when the above encryption cycle is \
120 complete. On next cryptkeeper entry, match \
121 the password. If it matches fix the master \
122 key and remove this flag. */
123
124/* Allowed values for type in the structure below */
125#define CRYPT_TYPE_PASSWORD \
126 0 /* master_key is encrypted with a password \
127 * Must be zero to be compatible with pre-L \
128 * devices where type is always password.*/
129#define CRYPT_TYPE_DEFAULT \
130 1 /* master_key is encrypted with default \
131 * password */
132#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
133#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
134#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
135
136#define CRYPT_MNT_MAGIC 0xD0B5B1C4
137#define PERSIST_DATA_MAGIC 0xE950CD44
138
139/* Key Derivation Function algorithms */
140#define KDF_PBKDF2 1
141#define KDF_SCRYPT 2
142/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
143#define KDF_SCRYPT_KEYMASTER 5
144
145/* Maximum allowed keymaster blob size. */
146#define KEYMASTER_BLOB_SIZE 2048
147
148/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
149#define __le8 unsigned char
150
151#if !defined(SHA256_DIGEST_LENGTH)
152#define SHA256_DIGEST_LENGTH 32
153#endif
154
155/* This structure starts 16,384 bytes before the end of a hardware
156 * partition that is encrypted, or in a separate partition. It's location
157 * is specified by a property set in init.<device>.rc.
158 * The structure allocates 48 bytes for a key, but the real key size is
159 * specified in the struct. Currently, the code is hardcoded to use 128
160 * bit keys.
161 * The fields after salt are only valid in rev 1.1 and later stuctures.
162 * Obviously, the filesystem does not include the last 16 kbytes
163 * of the partition if the crypt_mnt_ftr lives at the end of the
164 * partition.
165 */
166
167struct crypt_mnt_ftr {
168 __le32 magic; /* See above */
169 __le16 major_version;
170 __le16 minor_version;
171 __le32 ftr_size; /* in bytes, not including key following */
172 __le32 flags; /* See above */
173 __le32 keysize; /* in bytes */
174 __le32 crypt_type; /* how master_key is encrypted. Must be a
175 * CRYPT_TYPE_XXX value */
176 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
177 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
178 mount, set to 0 on successful mount */
179 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
180 needed to decrypt this
181 partition, null terminated */
182 __le32 spare2; /* ignored */
183 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
184 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
185 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
186 * on device with that info, either the footer of the
187 * real_blkdevice or the metadata partition. */
188
189 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
190 * persistent data table*/
191
192 __le8 kdf_type; /* The key derivation function used. */
193
194 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
195 __le8 N_factor; /* (1 << N) */
196 __le8 r_factor; /* (1 << r) */
197 __le8 p_factor; /* (1 << p) */
198 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
199 we have to stop (e.g. power low) this is the last
200 encrypted 512 byte sector.*/
201 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
202 set, hash of first block, used
203 to validate before continuing*/
204
205 /* key_master key, used to sign the derived key which is then used to generate
206 * the intermediate key
207 * This key should be used for no other purposes! We use this key to sign unpadded
208 * data, which is acceptable but only if the key is not reused elsewhere. */
209 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
210 __le32 keymaster_blob_size;
211
212 /* Store scrypt of salted intermediate key. When decryption fails, we can
213 check if this matches, and if it does, we know that the problem is with the
214 drive, and there is no point in asking the user for more passwords.
215
216 Note that if any part of this structure is corrupt, this will not match and
217 we will continue to believe the user entered the wrong password. In that
218 case the only solution is for the user to enter a password enough times to
219 force a wipe.
220
221 Note also that there is no need to worry about migration. If this data is
222 wrong, we simply won't recognise a right password, and will continue to
223 prompt. On the first password change, this value will be populated and
224 then we will be OK.
225 */
226 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
227
228 /* sha of this structure with this element set to zero
229 Used when encrypting on reboot to validate structure before doing something
230 fatal
231 */
232 unsigned char sha256[SHA256_DIGEST_LENGTH];
233};
234
235/* Persistant data that should be available before decryption.
236 * Things like airplane mode, locale and timezone are kept
237 * here and can be retrieved by the CryptKeeper UI to properly
238 * configure the phone before asking for the password
239 * This is only valid if the major and minor version above
240 * is set to 1.1 or higher.
241 *
242 * This is a 4K structure. There are 2 copies, and the code alternates
243 * writing one and then clearing the previous one. The reading
244 * code reads the first valid copy it finds, based on the magic number.
245 * The absolute offset to the first of the two copies is kept in rev 1.1
246 * and higher crypt_mnt_ftr structures.
247 */
248struct crypt_persist_entry {
249 char key[PROPERTY_KEY_MAX];
250 char val[PROPERTY_VALUE_MAX];
251};
252
253/* Should be exactly 4K in size */
254struct crypt_persist_data {
255 __le32 persist_magic;
256 __le32 persist_valid_entries;
257 __le32 persist_spare[30];
258 struct crypt_persist_entry persist_entry[0];
259};
260
261static int wait_and_unmount(const char* mountpoint, bool kill);
262
263typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
264 void* params);
265
266#define UNUSED __attribute__((unused))
267
268#define HASH_COUNT 2000
269
270constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
271constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
272constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
273
274// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
275static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
276
277#define KEY_IN_FOOTER "footer"
278
279#define DEFAULT_PASSWORD "default_password"
280
281#define CRYPTO_BLOCK_DEVICE "userdata"
282
283#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
284
285#define EXT4_FS 1
286#define F2FS_FS 2
287
288#define TABLE_LOAD_RETRIES 10
289
290#define RSA_KEY_SIZE 2048
291#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
292#define RSA_EXPONENT 0x10001
293#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
294
295#define RETRY_MOUNT_ATTEMPTS 10
296#define RETRY_MOUNT_DELAY_SECONDS 1
297
298#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
299
300static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
301
302static unsigned char saved_master_key[MAX_KEY_LEN];
303static char* saved_mount_point;
304static int master_key_saved = 0;
305static struct crypt_persist_data* persist_data = NULL;
306
307constexpr CryptoType aes_128_cbc = CryptoType()
308 .set_config_name("AES-128-CBC")
309 .set_kernel_name("aes-cbc-essiv:sha256")
310 .set_keysize(16);
311
312constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, ::adiantum};
313
314static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
315 array_length(supported_crypto_types)),
316 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
317 "incompletely constructed.");
318
319static const CryptoType& get_crypto_type() {
320 // We only want to parse this read-only property once. But we need to wait
321 // until the system is initialized before we can read it. So we use a static
322 // scoped within this function to get it only once.
323 static CryptoType crypto_type =
324 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
325 aes_128_cbc, "ro.crypto.fde_algorithm");
326 return crypto_type;
327}
328
329const KeyGeneration cryptfs_get_keygen() {
330 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
331}
332
333/* Should we use keymaster? */
334static int keymaster_check_compatibility() {
335 return keymaster_compatibility_cryptfs_scrypt();
336}
337
338/* Create a new keymaster key and store it in this footer */
339static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
340 if (ftr->keymaster_blob_size) {
341 SLOGI("Already have key");
342 return 0;
343 }
344
345 int rc = keymaster_create_key_for_cryptfs_scrypt(
346 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
347 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
348 if (rc) {
349 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
350 SLOGE("Keymaster key blob too large");
351 ftr->keymaster_blob_size = 0;
352 }
353 SLOGE("Failed to generate keypair");
354 return -1;
355 }
356 return 0;
357}
358
359/* This signs the given object using the keymaster key. */
360static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
361 const size_t object_size, unsigned char** signature,
362 size_t* signature_size) {
363 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
364 size_t to_sign_size = sizeof(to_sign);
365 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
366
367 // To sign a message with RSA, the message must satisfy two
368 // constraints:
369 //
370 // 1. The message, when interpreted as a big-endian numeric value, must
371 // be strictly less than the public modulus of the RSA key. Note
372 // that because the most significant bit of the public modulus is
373 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
374 // key), an n-bit message with most significant bit 0 always
375 // satisfies this requirement.
376 //
377 // 2. The message must have the same length in bits as the public
378 // modulus of the RSA key. This requirement isn't mathematically
379 // necessary, but is necessary to ensure consistency in
380 // implementations.
381 switch (ftr->kdf_type) {
382 case KDF_SCRYPT_KEYMASTER:
383 // This ensures the most significant byte of the signed message
384 // is zero. We could have zero-padded to the left instead, but
385 // this approach is slightly more robust against changes in
386 // object size. However, it's still broken (but not unusably
387 // so) because we really should be using a proper deterministic
388 // RSA padding function, such as PKCS1.
389 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
390 SLOGI("Signing safely-padded object");
391 break;
392 default:
393 SLOGE("Unknown KDF type %d", ftr->kdf_type);
394 return -1;
395 }
396 for (;;) {
397 auto result = keymaster_sign_object_for_cryptfs_scrypt(
398 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
399 to_sign_size, signature, signature_size);
400 switch (result) {
401 case KeymasterSignResult::ok:
402 return 0;
403 case KeymasterSignResult::upgrade:
404 break;
405 default:
406 return -1;
407 }
408 SLOGD("Upgrading key");
409 if (keymaster_upgrade_key_for_cryptfs_scrypt(
410 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
411 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
412 &ftr->keymaster_blob_size) != 0) {
413 SLOGE("Failed to upgrade key");
414 return -1;
415 }
416 if (put_crypt_ftr_and_key(ftr) != 0) {
417 SLOGE("Failed to write upgraded key to disk");
418 }
419 SLOGD("Key upgraded successfully");
420 }
421}
422
423/* Store password when userdata is successfully decrypted and mounted.
424 * Cleared by cryptfs_clear_password
425 *
426 * To avoid a double prompt at boot, we need to store the CryptKeeper
427 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
428 * Since the entire framework is torn down and rebuilt after encryption,
429 * we have to use a daemon or similar to store the password. Since vold
430 * is secured against IPC except from system processes, it seems a reasonable
431 * place to store this.
432 *
433 * password should be cleared once it has been used.
434 *
435 * password is aged out after password_max_age_seconds seconds.
436 */
437static char* password = 0;
438static int password_expiry_time = 0;
439static const int password_max_age_seconds = 60;
440
441enum class RebootType { reboot, recovery, shutdown };
442static void cryptfs_reboot(RebootType rt) {
443 switch (rt) {
444 case RebootType::reboot:
445 property_set(ANDROID_RB_PROPERTY, "reboot");
446 break;
447
448 case RebootType::recovery:
449 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
450 break;
451
452 case RebootType::shutdown:
453 property_set(ANDROID_RB_PROPERTY, "shutdown");
454 break;
455 }
456
457 sleep(20);
458
459 /* Shouldn't get here, reboot should happen before sleep times out */
460 return;
461}
462
463/**
464 * Gets the default device scrypt parameters for key derivation time tuning.
465 * The parameters should lead to about one second derivation time for the
466 * given device.
467 */
468static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
469 char paramstr[PROPERTY_VALUE_MAX];
470 int Nf, rf, pf;
471
472 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
473 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
474 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
475 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
476 }
477 ftr->N_factor = Nf;
478 ftr->r_factor = rf;
479 ftr->p_factor = pf;
480}
481
482static uint64_t get_fs_size(const char* dev) {
483 int fd, block_size;
484 struct ext4_super_block sb;
485 uint64_t len;
486
487 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
488 SLOGE("Cannot open device to get filesystem size ");
489 return 0;
490 }
491
492 if (lseek64(fd, 1024, SEEK_SET) < 0) {
493 SLOGE("Cannot seek to superblock");
494 return 0;
495 }
496
497 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
498 SLOGE("Cannot read superblock");
499 return 0;
500 }
501
502 close(fd);
503
504 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
505 SLOGE("Not a valid ext4 superblock");
506 return 0;
507 }
508 block_size = 1024 << sb.s_log_block_size;
509 /* compute length in bytes */
510 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
511
512 /* return length in sectors */
513 return len / 512;
514}
515
516static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
517 for (const auto& entry : fstab_default) {
518 if (!entry.fs_mgr_flags.vold_managed &&
519 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
520 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
521 if (key_loc != nullptr) {
522 *key_loc = entry.key_loc;
523 }
524 if (real_blk_device != nullptr) {
525 *real_blk_device = entry.blk_device;
526 }
527 return;
528 }
529 }
530}
531
532static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
533 static int cached_data = 0;
534 static uint64_t cached_off = 0;
535 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
536 char key_loc[PROPERTY_VALUE_MAX];
537 char real_blkdev[PROPERTY_VALUE_MAX];
538 int rc = -1;
539
540 if (!cached_data) {
541 std::string key_loc;
542 std::string real_blkdev;
543 get_crypt_info(&key_loc, &real_blkdev);
544
545 if (key_loc == KEY_IN_FOOTER) {
546 if (::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
547 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
548 * encryption info footer and key, and plenty of bytes to spare for future
549 * growth.
550 */
551 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
552 cached_off -= CRYPT_FOOTER_OFFSET;
553 cached_data = 1;
554 } else {
555 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
556 }
557 } else {
558 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
559 cached_off = 0;
560 cached_data = 1;
561 }
562 }
563
564 if (cached_data) {
565 if (metadata_fname) {
566 *metadata_fname = cached_metadata_fname;
567 }
568 if (off) {
569 *off = cached_off;
570 }
571 rc = 0;
572 }
573
574 return rc;
575}
576
577/* Set sha256 checksum in structure */
578static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
579 SHA256_CTX c;
580 SHA256_Init(&c);
581 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
582 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
583 SHA256_Final(crypt_ftr->sha256, &c);
584}
585
586/* key or salt can be NULL, in which case just skip writing that value. Useful to
587 * update the failed mount count but not change the key.
588 */
589static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
590 int fd;
591 unsigned int cnt;
592 /* starting_off is set to the SEEK_SET offset
593 * where the crypto structure starts
594 */
595 off64_t starting_off;
596 int rc = -1;
597 char* fname = NULL;
598 struct stat statbuf;
599
600 set_ftr_sha(crypt_ftr);
601
602 if (get_crypt_ftr_info(&fname, &starting_off)) {
603 SLOGE("Unable to get crypt_ftr_info\n");
604 return -1;
605 }
606 if (fname[0] != '/') {
607 SLOGE("put_crypt_ftr_and_key::Unexpected value for crypto key location: %s\n", fname);
608 return -1;
609 }
610 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
611 SLOGE("Cannot open footer file %s for put\n", fname);
612 return -1;
613 }
614
615 /* Seek to the start of the crypt footer */
616 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
617 SLOGE("Cannot seek to real block device footer\n");
618 goto errout;
619 }
620
621 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
622 SLOGE("Cannot write real block device footer\n");
623 goto errout;
624 }
625
626 fstat(fd, &statbuf);
627 /* If the keys are kept on a raw block device, do not try to truncate it. */
628 if (S_ISREG(statbuf.st_mode)) {
629 if (ftruncate(fd, 0x4000)) {
630 SLOGE("Cannot set footer file size\n");
631 goto errout;
632 }
633 }
634
635 /* Success! */
636 rc = 0;
637
638errout:
639 close(fd);
640 return rc;
641}
642
643static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
644 struct crypt_mnt_ftr copy;
645 memcpy(&copy, crypt_ftr, sizeof(copy));
646 set_ftr_sha(&copy);
647 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
648}
649
650static inline int unix_read(int fd, void* buff, int len) {
651 return TEMP_FAILURE_RETRY(read(fd, buff, len));
652}
653
654static inline int unix_write(int fd, const void* buff, int len) {
655 return TEMP_FAILURE_RETRY(write(fd, buff, len));
656}
657
658static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
659 memset(pdata, 0, len);
660 pdata->persist_magic = PERSIST_DATA_MAGIC;
661 pdata->persist_valid_entries = 0;
662}
663
664/* A routine to update the passed in crypt_ftr to the lastest version.
665 * fd is open read/write on the device that holds the crypto footer and persistent
666 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
667 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
668 */
669static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
670 int orig_major = crypt_ftr->major_version;
671 int orig_minor = crypt_ftr->minor_version;
672
673 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
674 struct crypt_persist_data* pdata;
675 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
676
677 SLOGW("upgrading crypto footer to 1.1");
678
679 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
680 if (pdata == NULL) {
681 SLOGE("Cannot allocate persisent data\n");
682 return;
683 }
684 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
685
686 /* Need to initialize the persistent data area */
687 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
688 SLOGE("Cannot seek to persisent data offset\n");
689 free(pdata);
690 return;
691 }
692 /* Write all zeros to the first copy, making it invalid */
693 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
694
695 /* Write a valid but empty structure to the second copy */
696 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
697 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
698
699 /* Update the footer */
700 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
701 crypt_ftr->persist_data_offset[0] = pdata_offset;
702 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
703 crypt_ftr->minor_version = 1;
704 free(pdata);
705 }
706
707 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
708 SLOGW("upgrading crypto footer to 1.2");
709 /* But keep the old kdf_type.
710 * It will get updated later to KDF_SCRYPT after the password has been verified.
711 */
712 crypt_ftr->kdf_type = KDF_PBKDF2;
713 get_device_scrypt_params(crypt_ftr);
714 crypt_ftr->minor_version = 2;
715 }
716
717 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
718 SLOGW("upgrading crypto footer to 1.3");
719 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
720 crypt_ftr->minor_version = 3;
721 }
722
723 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
724 if (lseek64(fd, offset, SEEK_SET) == -1) {
725 SLOGE("Cannot seek to crypt footer\n");
726 return;
727 }
728 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
729 }
730}
731
732static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
733 int fd;
734 unsigned int cnt;
735 off64_t starting_off;
736 int rc = -1;
737 char* fname = NULL;
738 struct stat statbuf;
739
740 if (get_crypt_ftr_info(&fname, &starting_off)) {
741 SLOGE("Unable to get crypt_ftr_info\n");
742 return -1;
743 }
744 if (fname[0] != '/') {
745 SLOGE("get_crypt_ftr_and_key::Unexpected value for crypto key location: %s\n", fname);
746 return -1;
747 }
748 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
749 SLOGE("Cannot open footer file %s for get\n", fname);
750 return -1;
751 }
752
753 /* Make sure it's 16 Kbytes in length */
754 fstat(fd, &statbuf);
755 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
756 SLOGE("footer file %s is not the expected size!\n", fname);
757 goto errout;
758 }
759
760 /* Seek to the start of the crypt footer */
761 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
762 SLOGE("Cannot seek to real block device footer\n");
763 goto errout;
764 }
765
766 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
767 SLOGE("Cannot read real block device footer\n");
768 goto errout;
769 }
770
771 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
772 SLOGE("Bad magic for real block device %s\n", fname);
773 goto errout;
774 }
775
776 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
777 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
778 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
779 goto errout;
780 }
781
782 // We risk buffer overflows with oversized keys, so we just reject them.
783 // 0-sized keys are problematic (essentially by-passing encryption), and
784 // AES-CBC key wrapping only works for multiples of 16 bytes.
785 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
786 (crypt_ftr->keysize > MAX_KEY_LEN)) {
787 SLOGE(
788 "Invalid keysize (%u) for block device %s; Must be non-zero, "
789 "divisible by 16, and <= %d\n",
790 crypt_ftr->keysize, fname, MAX_KEY_LEN);
791 goto errout;
792 }
793
794 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
795 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
796 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
797 }
798
799 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
800 * copy on disk before returning.
801 */
802 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
803 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
804 }
805
806 /* Success! */
807 rc = 0;
808
809errout:
810 close(fd);
811 return rc;
812}
813
814static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
815 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
816 crypt_ftr->persist_data_offset[1]) {
817 SLOGE("Crypt_ftr persist data regions overlap");
818 return -1;
819 }
820
821 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
822 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
823 return -1;
824 }
825
826 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
827 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
828 CRYPT_FOOTER_OFFSET) {
829 SLOGE("Persistent data extends past crypto footer");
830 return -1;
831 }
832
833 return 0;
834}
835
836static int load_persistent_data(void) {
837 struct crypt_mnt_ftr crypt_ftr;
838 struct crypt_persist_data* pdata = NULL;
839 char encrypted_state[PROPERTY_VALUE_MAX];
840 char* fname;
841 int found = 0;
842 int fd;
843 int ret;
844 int i;
845
846 if (persist_data) {
847 /* Nothing to do, we've already loaded or initialized it */
848 return 0;
849 }
850
851 /* If not encrypted, just allocate an empty table and initialize it */
852 property_get("ro.crypto.state", encrypted_state, "");
853 if (strcmp(encrypted_state, "encrypted")) {
854 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
855 if (pdata) {
856 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
857 persist_data = pdata;
858 return 0;
859 }
860 return -1;
861 }
862
863 if (get_crypt_ftr_and_key(&crypt_ftr)) {
864 return -1;
865 }
866
867 if ((crypt_ftr.major_version < 1) ||
868 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
869 SLOGE("Crypt_ftr version doesn't support persistent data");
870 return -1;
871 }
872
873 if (get_crypt_ftr_info(&fname, NULL)) {
874 return -1;
875 }
876
877 ret = validate_persistent_data_storage(&crypt_ftr);
878 if (ret) {
879 return -1;
880 }
881
882 fd = open(fname, O_RDONLY | O_CLOEXEC);
883 if (fd < 0) {
884 SLOGE("Cannot open %s metadata file", fname);
885 return -1;
886 }
887
888 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
889 if (pdata == NULL) {
890 SLOGE("Cannot allocate memory for persistent data");
891 goto err;
892 }
893
894 for (i = 0; i < 2; i++) {
895 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
896 SLOGE("Cannot seek to read persistent data on %s", fname);
897 goto err2;
898 }
899 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
900 SLOGE("Error reading persistent data on iteration %d", i);
901 goto err2;
902 }
903 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
904 found = 1;
905 break;
906 }
907 }
908
909 if (!found) {
910 SLOGI("Could not find valid persistent data, creating");
911 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
912 }
913
914 /* Success */
915 persist_data = pdata;
916 close(fd);
917 return 0;
918
919err2:
920 free(pdata);
921
922err:
923 close(fd);
924 return -1;
925}
926
927static int save_persistent_data(void) {
928 struct crypt_mnt_ftr crypt_ftr;
929 struct crypt_persist_data* pdata;
930 char* fname;
931 off64_t write_offset;
932 off64_t erase_offset;
933 int fd;
934 int ret;
935
936 if (persist_data == NULL) {
937 SLOGE("No persistent data to save");
938 return -1;
939 }
940
941 if (get_crypt_ftr_and_key(&crypt_ftr)) {
942 return -1;
943 }
944
945 if ((crypt_ftr.major_version < 1) ||
946 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
947 SLOGE("Crypt_ftr version doesn't support persistent data");
948 return -1;
949 }
950
951 ret = validate_persistent_data_storage(&crypt_ftr);
952 if (ret) {
953 return -1;
954 }
955
956 if (get_crypt_ftr_info(&fname, NULL)) {
957 return -1;
958 }
959
960 fd = open(fname, O_RDWR | O_CLOEXEC);
961 if (fd < 0) {
962 SLOGE("Cannot open %s metadata file", fname);
963 return -1;
964 }
965
966 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
967 if (pdata == NULL) {
968 SLOGE("Cannot allocate persistant data");
969 goto err;
970 }
971
972 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
973 SLOGE("Cannot seek to read persistent data on %s", fname);
974 goto err2;
975 }
976
977 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
978 SLOGE("Error reading persistent data before save");
979 goto err2;
980 }
981
982 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
983 /* The first copy is the curent valid copy, so write to
984 * the second copy and erase this one */
985 write_offset = crypt_ftr.persist_data_offset[1];
986 erase_offset = crypt_ftr.persist_data_offset[0];
987 } else {
988 /* The second copy must be the valid copy, so write to
989 * the first copy, and erase the second */
990 write_offset = crypt_ftr.persist_data_offset[0];
991 erase_offset = crypt_ftr.persist_data_offset[1];
992 }
993
994 /* Write the new copy first, if successful, then erase the old copy */
995 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
996 SLOGE("Cannot seek to write persistent data");
997 goto err2;
998 }
999 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1000 (int)crypt_ftr.persist_data_size) {
1001 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
1002 SLOGE("Cannot seek to erase previous persistent data");
1003 goto err2;
1004 }
1005 fsync(fd);
1006 memset(pdata, 0, crypt_ftr.persist_data_size);
1007 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
1008 SLOGE("Cannot write to erase previous persistent data");
1009 goto err2;
1010 }
1011 fsync(fd);
1012 } else {
1013 SLOGE("Cannot write to save persistent data");
1014 goto err2;
1015 }
1016
1017 /* Success */
1018 free(pdata);
1019 close(fd);
1020 return 0;
1021
1022err2:
1023 free(pdata);
1024err:
1025 close(fd);
1026 return -1;
1027}
1028
1029/* Convert a binary key of specified length into an ascii hex string equivalent,
1030 * without the leading 0x and with null termination
1031 */
1032static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1033 char* master_key_ascii) {
1034 unsigned int i, a;
1035 unsigned char nibble;
1036
1037 for (i = 0, a = 0; i < keysize; i++, a += 2) {
1038 /* For each byte, write out two ascii hex digits */
1039 nibble = (master_key[i] >> 4) & 0xf;
1040 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
1041
1042 nibble = master_key[i] & 0xf;
1043 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1044 }
1045
1046 /* Add the null termination */
1047 master_key_ascii[a] = '\0';
1048}
1049
1050/*
1051 * If the ro.crypto.fde_sector_size system property is set, append the
1052 * parameters to make dm-crypt use the specified crypto sector size and round
1053 * the crypto device size down to a crypto sector boundary.
1054 */
1055static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
1056 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
1057 char value[PROPERTY_VALUE_MAX];
1058
1059 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1060 unsigned int sector_size;
1061
1062 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1063 (sector_size & (sector_size - 1)) != 0) {
1064 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1065 DM_CRYPT_SECTOR_SIZE, value);
1066 return -1;
1067 }
1068
1069 target->SetSectorSize(sector_size);
1070
1071 // With this option, IVs will match the sector numbering, instead
1072 // of being hard-coded to being based on 512-byte sectors.
1073 target->SetIvLargeSectors();
1074
1075 // Round the crypto device size down to a crypto sector boundary.
1076 ftr->fs_size &= ~((sector_size / 512) - 1);
1077 }
1078 return 0;
1079}
1080
1081static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1082 const char* real_blk_name, std::string* crypto_blk_name,
1083 const char* name, uint32_t flags) {
1084 auto& dm = DeviceMapper::Instance();
1085 ALOGE("create_crypto_blk_dev\n");
1086
1087 // We need two ASCII characters to represent each byte, and need space for
1088 // the '\0' terminator.
1089 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1090 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1091
1092 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1093 (const char*)crypt_ftr->crypto_type_name,
1094 master_key_ascii, 0, real_blk_name, 0);
1095 target->AllowDiscards();
1096
1097 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1098 target->AllowEncryptOverride();
1099 }
1100 if (add_sector_size_param(target.get(), crypt_ftr)) {
1101 SLOGE("Error processing dm-crypt sector size param\n");
1102 return -1;
1103 }
1104
1105 DmTable table;
1106 table.AddTarget(std::move(target));
1107
1108 int load_count = 1;
1109 while (load_count < TABLE_LOAD_RETRIES) {
1110 if (dm.CreateDevice(name, table)) {
1111 break;
1112 }
1113 load_count++;
1114 }
1115
1116 if (load_count >= TABLE_LOAD_RETRIES) {
1117 SLOGE("Cannot load dm-crypt mapping table.\n");
1118 return -1;
1119 }
1120 if (load_count > 1) {
1121 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1122 }
1123
1124 // ALOGE("GetDmDevicePathByName::%s::%s\n", name, crypto_blk_name->c_str());
1125 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
1126 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1127 return -1;
1128 }
1129
1130 /* Ensure the dm device has been created before returning. */
1131 if (::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
1132 // WaitForFile generates a suitable log message
1133 return -1;
1134 }
1135 return 0;
1136}
1137
1138static int delete_crypto_blk_dev(const std::string& name) {
1139 bool ret;
1140 auto& dm = DeviceMapper::Instance();
1141 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1142 // to delete the device fails with EBUSY; for now, work around this by retrying.
1143 int tries = 5;
1144 while (tries-- > 0) {
1145 ret = dm.DeleteDevice(name);
1146 if (ret || errno != EBUSY) {
1147 break;
1148 }
1149 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1150 strerror(errno));
1151 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1152 }
1153 if (!ret) {
1154 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1155 return -1;
1156 }
1157 return 0;
1158}
1159
1160static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1161 void* params UNUSED) {
1162 SLOGI("Using pbkdf2 for cryptfs KDF");
1163
1164 /* Turn the password into a key and IV that can decrypt the master key */
1165 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1166 INTERMEDIATE_BUF_SIZE, ikey) != 1;
1167}
1168
1169static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
1170 SLOGI("Using scrypt for cryptfs KDF");
1171
1172 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
1173
1174 int N = 1 << ftr->N_factor;
1175 int r = 1 << ftr->r_factor;
1176 int p = 1 << ftr->p_factor;
1177
1178 /* Turn the password into a key and IV that can decrypt the master key */
1179 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
1180 INTERMEDIATE_BUF_SIZE);
1181
1182 return 0;
1183}
1184
1185static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1186 void* params) {
1187 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1188
1189 int rc;
1190 size_t signature_size;
1191 unsigned char* signature;
1192 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
1193
1194 int N = 1 << ftr->N_factor;
1195 int r = 1 << ftr->r_factor;
1196 int p = 1 << ftr->p_factor;
1197
1198 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
1199 INTERMEDIATE_BUF_SIZE);
1200
1201 if (rc) {
1202 SLOGE("scrypt failed");
1203 return -1;
1204 }
1205
1206 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
1207 SLOGE("Signing failed");
1208 return -1;
1209 }
1210
1211 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1212 INTERMEDIATE_BUF_SIZE);
1213 free(signature);
1214
1215 if (rc) {
1216 SLOGE("scrypt failed");
1217 return -1;
1218 }
1219
1220 return 0;
1221}
1222
1223static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1224 const unsigned char* decrypted_master_key,
1225 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1226 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1227 EVP_CIPHER_CTX e_ctx;
1228 int encrypted_len, final_len;
1229 int rc = 0;
1230
1231 /* Turn the password into an intermediate key and IV that can decrypt the master key */
1232 get_device_scrypt_params(crypt_ftr);
1233
1234 switch (crypt_ftr->kdf_type) {
1235 case KDF_SCRYPT_KEYMASTER:
1236 if (keymaster_create_key(crypt_ftr)) {
1237 SLOGE("keymaster_create_key failed");
1238 return -1;
1239 }
1240
1241 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1242 SLOGE("scrypt failed");
1243 return -1;
1244 }
1245 break;
1246
1247 case KDF_SCRYPT:
1248 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1249 SLOGE("scrypt failed");
1250 return -1;
1251 }
1252 break;
1253
1254 default:
1255 SLOGE("Invalid kdf_type");
1256 return -1;
1257 }
1258
1259 /* Initialize the decryption engine */
1260 EVP_CIPHER_CTX_init(&e_ctx);
1261 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1262 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1263 SLOGE("EVP_EncryptInit failed\n");
1264 return -1;
1265 }
1266 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
1267
1268 /* Encrypt the master key */
1269 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1270 crypt_ftr->keysize)) {
1271 SLOGE("EVP_EncryptUpdate failed\n");
1272 return -1;
1273 }
1274 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
1275 SLOGE("EVP_EncryptFinal failed\n");
1276 return -1;
1277 }
1278
1279 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
1280 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1281 return -1;
1282 }
1283
1284 /* Store the scrypt of the intermediate key, so we can validate if it's a
1285 password error or mount error when things go wrong.
1286 Note there's no need to check for errors, since if this is incorrect, we
1287 simply won't wipe userdata, which is the correct default behavior
1288 */
1289 int N = 1 << crypt_ftr->N_factor;
1290 int r = 1 << crypt_ftr->r_factor;
1291 int p = 1 << crypt_ftr->p_factor;
1292
1293 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1294 N, r, p, crypt_ftr->scrypted_intermediate_key,
1295 sizeof(crypt_ftr->scrypted_intermediate_key));
1296
1297 if (rc) {
1298 SLOGE("encrypt_master_key: crypto_scrypt failed");
1299 }
1300
1301 EVP_CIPHER_CTX_cleanup(&e_ctx);
1302
1303 return 0;
1304}
1305
1306static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1307 const unsigned char* encrypted_master_key, size_t keysize,
1308 unsigned char* decrypted_master_key, kdf_func kdf,
1309 void* kdf_params, unsigned char** intermediate_key,
1310 size_t* intermediate_key_size) {
1311 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1312 EVP_CIPHER_CTX d_ctx;
1313 int decrypted_len, final_len;
1314
1315 /* Turn the password into an intermediate key and IV that can decrypt the
1316 master key */
1317 if (kdf(passwd, salt, ikey, kdf_params)) {
1318 SLOGE("kdf failed");
1319 return -1;
1320 }
1321
1322 /* Initialize the decryption engine */
1323 EVP_CIPHER_CTX_init(&d_ctx);
1324 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1325 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1326 return -1;
1327 }
1328 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1329 /* Decrypt the master key */
1330 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1331 keysize)) {
1332 return -1;
1333 }
1334 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1335 return -1;
1336 }
1337
1338 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1339 return -1;
1340 }
1341
1342 /* Copy intermediate key if needed by params */
1343 if (intermediate_key && intermediate_key_size) {
1344 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1345 if (*intermediate_key) {
1346 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1347 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1348 }
1349 }
1350
1351 EVP_CIPHER_CTX_cleanup(&d_ctx);
1352
1353 return 0;
1354}
1355
1356static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
1357 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1358 *kdf = scrypt_keymaster;
1359 *kdf_params = ftr;
1360 } else if (ftr->kdf_type == KDF_SCRYPT) {
1361 *kdf = scrypt;
1362 *kdf_params = ftr;
1363 } else {
1364 *kdf = pbkdf2;
1365 *kdf_params = NULL;
1366 }
1367}
1368
1369static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1370 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1371 size_t* intermediate_key_size) {
1372 kdf_func kdf;
1373 void* kdf_params;
1374 int ret;
1375
1376 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1377 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1378 decrypted_master_key, kdf, kdf_params, intermediate_key,
1379 intermediate_key_size);
1380 if (ret != 0) {
1381 SLOGW("failure decrypting master key");
1382 }
1383
1384 return ret;
1385}
1386
1387static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1388 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
1389 unsigned char key_buf[MAX_KEY_LEN];
1390
1391 /* Get some random bits for a key and salt */
1392 if (::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1393 return -1;
1394 }
1395 if (::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1396 return -1;
1397 }
1398
1399 /* Now encrypt it with the password */
1400 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
1401}
1402
1403static void ensure_subdirectory_unmounted(const char *prefix) {
1404 std::vector<std::string> umount_points;
1405 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1406 if (!mnts) {
1407 SLOGW("could not read mount files");
1408 return;
1409 }
1410
1411 //Find sudirectory mount point
1412 mntent* mentry;
1413 std::string top_directory(prefix);
1414 if (!android::base::EndsWith(prefix, "/")) {
1415 top_directory = top_directory + "/";
1416 }
1417 while ((mentry = getmntent(mnts.get())) != nullptr) {
1418 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1419 continue;
1420 }
1421
1422 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1423 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1424 umount_points.push_back(mentry->mnt_dir);
1425 }
1426 }
1427
1428 //Sort by path length to umount longest path first
1429 std::sort(std::begin(umount_points), std::end(umount_points),
1430 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1431
1432 for (std::string& mount_point : umount_points) {
1433 umount(mount_point.c_str());
1434 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1435 }
1436}
1437
1438static int wait_and_unmount(const char* mountpoint, bool kill) {
1439 int i, err, rc;
1440
1441 // Subdirectory mount will cause a failure of umount.
1442 ensure_subdirectory_unmounted(mountpoint);
1443#define WAIT_UNMOUNT_COUNT 20
1444
1445 /* Now umount the tmpfs filesystem */
1446 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
1447 if (umount(mountpoint) == 0) {
1448 break;
1449 }
1450
1451 if (errno == EINVAL) {
1452 /* EINVAL is returned if the directory is not a mountpoint,
1453 * i.e. there is no filesystem mounted there. So just get out.
1454 */
1455 break;
1456 }
1457
1458 err = errno;
1459
1460 /* If allowed, be increasingly aggressive before the last two retries */
1461 if (kill) {
1462 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1463 SLOGW("sending SIGHUP to processes with open files\n");
1464 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
1465 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1466 SLOGW("sending SIGKILL to processes with open files\n");
1467 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
1468 }
1469 }
1470
1471 sleep(1);
1472 }
1473
1474 if (i < WAIT_UNMOUNT_COUNT) {
1475 SLOGD("unmounting %s succeeded\n", mountpoint);
1476 rc = 0;
1477 } else {
1478 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1479 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1480 rc = -1;
1481 }
1482
1483 return rc;
1484}
1485
1486static void prep_data_fs(void) {
1487 // NOTE: post_fs_data results in init calling back around to vold, so all
1488 // callers to this method must be async
1489
1490 /* Do the prep of the /data filesystem */
1491 property_set("vold.post_fs_data_done", "0");
1492 property_set("vold.decrypt", "trigger_post_fs_data");
1493 SLOGD("Just triggered post_fs_data");
1494
1495 /* Wait a max of 50 seconds, hopefully it takes much less */
1496 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
1497 /* We timed out to prep /data in time. Continue wait. */
1498 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
1499 }
1500 SLOGD("post_fs_data done");
1501}
1502
1503static void cryptfs_set_corrupt() {
1504 // Mark the footer as bad
1505 struct crypt_mnt_ftr crypt_ftr;
1506 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1507 SLOGE("Failed to get crypto footer - panic");
1508 return;
1509 }
1510
1511 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1512 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1513 SLOGE("Failed to set crypto footer - panic");
1514 return;
1515 }
1516}
1517
1518static void cryptfs_trigger_restart_min_framework() {
1519 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1520 SLOGE("Failed to mount tmpfs on data - panic");
1521 return;
1522 }
1523
1524 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1525 SLOGE("Failed to trigger post fs data - panic");
1526 return;
1527 }
1528
1529 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1530 SLOGE("Failed to trigger restart min framework - panic");
1531 return;
1532 }
1533}
1534
1535/* returns < 0 on failure */
1536static int cryptfs_restart_internal(int restart_main) {
1537 char crypto_blkdev[MAXPATHLEN];
1538 int rc = -1;
1539 static int restart_successful = 0;
1540
1541 /* Validate that it's OK to call this routine */
1542 if (!master_key_saved) {
1543 SLOGE("Encrypted filesystem not validated, aborting");
1544 return -1;
1545 }
1546
1547 if (restart_successful) {
1548 SLOGE("System already restarted with encrypted disk, aborting");
1549 return -1;
1550 }
1551
1552 if (restart_main) {
1553 /* Here is where we shut down the framework. The init scripts
1554 * start all services in one of these classes: core, early_hal, hal,
1555 * main and late_start. To get to the minimal UI for PIN entry, we
1556 * need to start core, early_hal, hal and main. When we want to
1557 * shutdown the framework again, we need to stop most of the services in
1558 * these classes, but only those services that were started after
1559 * /data was mounted. This excludes critical services like vold and
1560 * ueventd, which need to keep running. We could possible stop
1561 * even fewer services, but because we want services to pick up APEX
1562 * libraries from the real /data, restarting is better, as it makes
1563 * these devices consistent with FBE devices and lets them use the
1564 * most recent code.
1565 *
1566 * Once these services have stopped, we should be able
1567 * to umount the tmpfs /data, then mount the encrypted /data.
1568 * We then restart the class core, hal, main, and also the class
1569 * late_start.
1570 *
1571 * At the moment, I've only put a few things in late_start that I know
1572 * are not needed to bring up the framework, and that also cause problems
1573 * with unmounting the tmpfs /data, but I hope to add add more services
1574 * to the late_start class as we optimize this to decrease the delay
1575 * till the user is asked for the password to the filesystem.
1576 */
1577
1578 /* The init files are setup to stop the right set of services when
1579 * vold.decrypt is set to trigger_shutdown_framework.
1580 */
1581 property_set("vold.decrypt", "trigger_shutdown_framework");
1582 SLOGD("Just asked init to shut down class main\n");
1583
1584 /* Ugh, shutting down the framework is not synchronous, so until it
1585 * can be fixed, this horrible hack will wait a moment for it all to
1586 * shut down before proceeding. Without it, some devices cannot
1587 * restart the graphics services.
1588 */
1589 sleep(2);
1590 }
1591
1592 /* Now that the framework is shutdown, we should be able to umount()
1593 * the tmpfs filesystem, and mount the real one.
1594 */
1595
1596 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1597 if (strlen(crypto_blkdev) == 0) {
1598 SLOGE("fs_crypto_blkdev not set\n");
1599 return -1;
1600 }
1601
1602 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1603 /* If ro.crypto.readonly is set to 1, mount the decrypted
1604 * filesystem readonly. This is used when /data is mounted by
1605 * recovery mode.
1606 */
1607 char ro_prop[PROPERTY_VALUE_MAX];
1608 property_get("ro.crypto.readonly", ro_prop, "");
1609 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
1610 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1611 if (entry != nullptr) {
1612 entry->flags |= MS_RDONLY;
1613 }
1614 }
1615
1616 /* If that succeeded, then mount the decrypted filesystem */
1617 int retries = RETRY_MOUNT_ATTEMPTS;
1618 int mount_rc;
1619
1620 /*
1621 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1622 * partitions in the fsck domain.
1623 */
1624 if (setexeccon(::sFsckContext)) {
1625 SLOGE("Failed to setexeccon");
1626 return -1;
1627 }
1628 bool needs_cp = ::cp_needsCheckpoint();
1629 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
1630 needs_cp, false)) != 0) {
1631 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1632 /* TODO: invoke something similar to
1633 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1634 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1635 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
1636 if (--retries) {
1637 sleep(RETRY_MOUNT_DELAY_SECONDS);
1638 } else {
1639 /* Let's hope that a reboot clears away whatever is keeping
1640 the mount busy */
1641 cryptfs_reboot(RebootType::reboot);
1642 }
1643 } else {
1644 SLOGE("Failed to mount decrypted data");
1645 cryptfs_set_corrupt();
1646 cryptfs_trigger_restart_min_framework();
1647 SLOGI("Started framework to offer wipe");
1648 if (setexeccon(NULL)) {
1649 SLOGE("Failed to setexeccon");
1650 }
1651 return -1;
1652 }
1653 }
1654 if (setexeccon(NULL)) {
1655 SLOGE("Failed to setexeccon");
1656 return -1;
1657 }
1658
1659 /* Create necessary paths on /data */
1660 prep_data_fs();
1661 property_set("vold.decrypt", "trigger_load_persist_props");
1662
1663 /* startup service classes main and late_start */
1664 property_set("vold.decrypt", "trigger_restart_framework");
1665 SLOGD("Just triggered restart_framework\n");
1666
1667 /* Give it a few moments to get started */
1668 sleep(1);
1669 }
1670
1671 if (rc == 0) {
1672 restart_successful = 1;
1673 }
1674
1675 return rc;
1676}
1677
1678int cryptfs_restart(void) {
1679 SLOGI("cryptfs_restart");
1680 if (fscrypt_is_native()) {
1681 SLOGE("cryptfs_restart not valid for file encryption:");
1682 return -1;
1683 }
1684
1685 /* Call internal implementation forcing a restart of main service group */
1686 return cryptfs_restart_internal(1);
1687}
1688
1689static int do_crypto_complete(const char* mount_point) {
1690 struct crypt_mnt_ftr crypt_ftr;
1691 char encrypted_state[PROPERTY_VALUE_MAX];
1692
1693 property_get("ro.crypto.state", encrypted_state, "");
1694 if (strcmp(encrypted_state, "encrypted")) {
1695 SLOGE("not running with encryption, aborting");
1696 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1697 }
1698
1699 // crypto_complete is full disk encrypted status
1700 if (fscrypt_is_native()) {
1701 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1702 }
1703
1704 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1705 std::string key_loc;
1706 get_crypt_info(&key_loc, nullptr);
1707
1708 /*
1709 * Only report this error if key_loc is a file and it exists.
1710 * If the device was never encrypted, and /data is not mountable for
1711 * some reason, returning 1 should prevent the UI from presenting the
1712 * a "enter password" screen, or worse, a "press button to wipe the
1713 * device" screen.
1714 */
1715 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
1716 SLOGE("master key file does not exist, aborting");
1717 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1718 } else {
1719 SLOGE("Error getting crypt footer and key\n");
1720 return CRYPTO_COMPLETE_BAD_METADATA;
1721 }
1722 }
1723
1724 // Test for possible error flags
1725 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1726 SLOGE("Encryption process is partway completed\n");
1727 return CRYPTO_COMPLETE_PARTIAL;
1728 }
1729
1730 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1731 SLOGE("Encryption process was interrupted but cannot continue\n");
1732 return CRYPTO_COMPLETE_INCONSISTENT;
1733 }
1734
1735 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1736 SLOGE("Encryption is successful but data is corrupt\n");
1737 return CRYPTO_COMPLETE_CORRUPT;
1738 }
1739
1740 /* We passed the test! We shall diminish, and return to the west */
1741 return CRYPTO_COMPLETE_ENCRYPTED;
1742}
1743
1744static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1745 const char* mount_point, const char* label) {
1746 unsigned char decrypted_master_key[MAX_KEY_LEN];
1747 std::string crypto_blkdev;
1748 std::string real_blkdev;
1749 char tmp_mount_point[64];
1750 unsigned int orig_failed_decrypt_count;
1751 int rc;
1752 int use_keymaster = 0;
1753 int upgrade = 0;
1754 unsigned char* intermediate_key = 0;
1755 size_t intermediate_key_size = 0;
1756 int N = 1 << crypt_ftr->N_factor;
1757 int r = 1 << crypt_ftr->r_factor;
1758 int p = 1 << crypt_ftr->p_factor;
1759
1760 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1761 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
1762
1763 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1764 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1765 &intermediate_key_size)) {
1766 SLOGE("Failed to decrypt master key\n");
1767 rc = -1;
1768 goto errout;
1769 }
1770 }
1771
1772 get_crypt_info(nullptr, &real_blkdev);
1773
1774 // Create crypto block device - all (non fatal) code paths
1775 // need it
1776 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
1777 label, 0)) {
1778 SLOGE("Error creating decrypted block device\n");
1779 rc = -1;
1780 goto errout;
1781 }
1782
1783 /* Work out if the problem is the password or the data */
1784 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
1785
1786 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1787 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1788 sizeof(scrypted_intermediate_key));
1789
1790 // Does the key match the crypto footer?
1791 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1792 sizeof(scrypted_intermediate_key)) == 0) {
1793 SLOGI("Password matches");
1794 rc = 0;
1795 } else {
1796 /* Try mounting the file system anyway, just in case the problem's with
1797 * the footer, not the key. */
1798 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1799 mkdir(tmp_mount_point, 0755);
1800 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1801 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
1802 SLOGE("Error temp mounting decrypted block device\n");
1803 delete_crypto_blk_dev(label);
1804
1805 rc = ++crypt_ftr->failed_decrypt_count;
1806 put_crypt_ftr_and_key(crypt_ftr);
1807 } else {
1808 /* Success! */
1809 SLOGI("Password did not match but decrypted drive mounted - continue");
1810 umount(tmp_mount_point);
1811 rc = 0;
1812 }
1813 }
1814
1815 if (rc == 0) {
1816 crypt_ftr->failed_decrypt_count = 0;
1817 if (orig_failed_decrypt_count != 0) {
1818 put_crypt_ftr_and_key(crypt_ftr);
1819 }
1820
1821 /* Save the name of the crypto block device
1822 * so we can mount it when restarting the framework. */
1823 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
1824
1825 /* Also save a the master key so we can reencrypted the key
1826 * the key when we want to change the password on it. */
1827 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1828 saved_mount_point = strdup(mount_point);
1829 master_key_saved = 1;
1830 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1831 rc = 0;
1832
1833 // Upgrade if we're not using the latest KDF.
1834 use_keymaster = keymaster_check_compatibility();
1835 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1836 // Don't allow downgrade
1837 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1838 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1839 upgrade = 1;
1840 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1841 crypt_ftr->kdf_type = KDF_SCRYPT;
1842 upgrade = 1;
1843 }
1844
1845 if (upgrade) {
1846 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1847 crypt_ftr->master_key, crypt_ftr);
1848 if (!rc) {
1849 rc = put_crypt_ftr_and_key(crypt_ftr);
1850 }
1851 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1852
1853 // Do not fail even if upgrade failed - machine is bootable
1854 // Note that if this code is ever hit, there is a *serious* problem
1855 // since KDFs should never fail. You *must* fix the kdf before
1856 // proceeding!
1857 if (rc) {
1858 SLOGW(
1859 "Upgrade failed with error %d,"
1860 " but continuing with previous state",
1861 rc);
1862 rc = 0;
1863 }
1864 }
1865 }
1866
1867errout:
1868 if (intermediate_key) {
1869 memset(intermediate_key, 0, intermediate_key_size);
1870 free(intermediate_key);
1871 }
1872 return rc;
1873}
1874
1875/*
1876 * Called by vold when it's asked to mount an encrypted external
1877 * storage volume. The incoming partition has no crypto header/footer,
1878 * as any metadata is been stored in a separate, small partition. We
1879 * assume it must be using our same crypt type and keysize.
1880 */
1881int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
1882 std::string* out_crypto_blkdev) {
1883 auto crypto_type = get_crypto_type();
1884 if (key.size() != crypto_type.get_keysize()) {
1885 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
1886 crypto_type.get_keysize());
1887 return -1;
1888 }
1889 uint64_t nr_sec = 0;
1890 if (::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
1891 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
1892 return -1;
1893 }
1894
1895 struct crypt_mnt_ftr ext_crypt_ftr;
1896 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1897 ext_crypt_ftr.fs_size = nr_sec;
1898 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1899 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
1900 MAX_CRYPTO_TYPE_NAME_LEN);
1901 uint32_t flags = 0;
1902 if (fscrypt_is_native() &&
1903 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1904 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
1905
1906 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1907 real_blkdev, out_crypto_blkdev, label, flags);
1908}
1909
1910int cryptfs_crypto_complete(void) {
1911 return do_crypto_complete("/data");
1912}
1913
1914int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
1915 char encrypted_state[PROPERTY_VALUE_MAX];
1916 property_get("ro.crypto.state", encrypted_state, "");
1917 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1918 SLOGE(
1919 "encrypted fs already validated or not running with encryption,"
1920 " aborting");
1921 return -1;
1922 }
1923
1924 if (get_crypt_ftr_and_key(crypt_ftr)) {
1925 SLOGE("Error getting crypt footer and key");
1926 return -1;
1927 }
1928
1929 return 0;
1930}
1931
1932int cryptfs_check_passwd(const char* passwd) {
1933 SLOGI("cryptfs_check_passwd");
1934 if (fscrypt_is_native()) {
1935 SLOGE("cryptfs_check_passwd not valid for file encryption");
1936 return -1;
1937 }
1938
1939 struct crypt_mnt_ftr crypt_ftr;
1940 int rc;
1941
1942 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1943 if (rc) {
1944 SLOGE("Could not get footer");
1945 return rc;
1946 }
1947
1948 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1949 if (rc) {
1950 SLOGE("Password did not match");
1951 return rc;
1952 }
1953
1954 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1955 // Here we have a default actual password but a real password
1956 // we must test against the scrypted value
1957 // First, we must delete the crypto block device that
1958 // test_mount_encrypted_fs leaves behind as a side effect
1959 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1960 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1961 CRYPTO_BLOCK_DEVICE);
1962 if (rc) {
1963 SLOGE("Default password did not match on reboot encryption");
1964 return rc;
1965 }
1966
1967 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1968 put_crypt_ftr_and_key(&crypt_ftr);
1969 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1970 if (rc) {
1971 SLOGE("Could not change password on reboot encryption");
1972 return rc;
1973 }
1974 }
1975
1976 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
1977 cryptfs_clear_password();
1978 password = strdup(passwd);
1979 struct timespec now;
1980 clock_gettime(CLOCK_BOOTTIME, &now);
1981 password_expiry_time = now.tv_sec + password_max_age_seconds;
1982 }
1983
1984 return rc;
1985}
1986
1987int cryptfs_verify_passwd(const char* passwd) {
1988 struct crypt_mnt_ftr crypt_ftr;
1989 unsigned char decrypted_master_key[MAX_KEY_LEN];
1990 char encrypted_state[PROPERTY_VALUE_MAX];
1991 int rc;
1992
1993 property_get("ro.crypto.state", encrypted_state, "");
1994 if (strcmp(encrypted_state, "encrypted")) {
1995 SLOGE("device not encrypted, aborting");
1996 return -2;
1997 }
1998
1999 if (!master_key_saved) {
2000 SLOGE("encrypted fs not yet mounted, aborting");
2001 return -1;
2002 }
2003
2004 if (!saved_mount_point) {
2005 SLOGE("encrypted fs failed to save mount point, aborting");
2006 return -1;
2007 }
2008
2009 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2010 SLOGE("Error getting crypt footer and key\n");
2011 return -1;
2012 }
2013
2014 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2015 /* If the device has no password, then just say the password is valid */
2016 rc = 0;
2017 } else {
2018 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2019 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2020 /* They match, the password is correct */
2021 rc = 0;
2022 } else {
2023 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2024 sleep(1);
2025 rc = 1;
2026 }
2027 }
2028
2029 return rc;
2030}
2031
2032/* Initialize a crypt_mnt_ftr structure. The keysize is
2033 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
2034 * Presumably, at a minimum, the caller will update the
2035 * filesystem size and crypto_type_name after calling this function.
2036 */
2037static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
2038 off64_t off;
2039
2040 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
2041 ftr->magic = CRYPT_MNT_MAGIC;
2042 ftr->major_version = CURRENT_MAJOR_VERSION;
2043 ftr->minor_version = CURRENT_MINOR_VERSION;
2044 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
2045 ftr->keysize = get_crypto_type().get_keysize();
2046
2047 switch (keymaster_check_compatibility()) {
2048 case 1:
2049 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2050 break;
2051
2052 case 0:
2053 ftr->kdf_type = KDF_SCRYPT;
2054 break;
2055
2056 default:
2057 SLOGE("keymaster_check_compatibility failed");
2058 return -1;
2059 }
2060
2061 get_device_scrypt_params(ftr);
2062
2063 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2064 if (get_crypt_ftr_info(NULL, &off) == 0) {
2065 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2066 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
2067 }
2068
2069 return 0;
2070}
2071
2072#define FRAMEWORK_BOOT_WAIT 60
2073
2074static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2075 int fd = open(filename, O_RDONLY | O_CLOEXEC);
2076 if (fd == -1) {
2077 SLOGE("Error opening file %s", filename);
2078 return -1;
2079 }
2080
2081 char block[CRYPT_INPLACE_BUFSIZE];
2082 memset(block, 0, sizeof(block));
2083 if (unix_read(fd, block, sizeof(block)) < 0) {
2084 SLOGE("Error reading file %s", filename);
2085 close(fd);
2086 return -1;
2087 }
2088
2089 close(fd);
2090
2091 SHA256_CTX c;
2092 SHA256_Init(&c);
2093 SHA256_Update(&c, block, sizeof(block));
2094 SHA256_Final(buf, &c);
2095
2096 return 0;
2097}
2098
2099static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2100 const char* real_blkdev, int previously_encrypted_upto) {
2101 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
2102 int rc = -1;
2103
2104 /* The size of the userdata partition, and add in the vold volumes below */
2105 tot_encryption_size = crypt_ftr->fs_size;
2106
2107 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
2108 tot_encryption_size, previously_encrypted_upto, true);
2109
2110 if (rc == ENABLE_INPLACE_ERR_DEV) {
2111 /* Hack for b/17898962 */
2112 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2113 cryptfs_reboot(RebootType::reboot);
2114 }
2115
2116 if (!rc) {
2117 crypt_ftr->encrypted_upto = cur_encryption_done;
2118 }
2119
2120 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2121 /* The inplace routine never actually sets the progress to 100% due
2122 * to the round down nature of integer division, so set it here */
2123 property_set("vold.encrypt_progress", "100");
2124 }
2125
2126 return rc;
2127}
2128
2129// static int vold_unmountAll(void) {
2130// VolumeManager* vm = VolumeManager::Instance();
2131// return vm->unmountAll();
2132// }
2133
2134int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
2135 std::string crypto_blkdev;
2136 std::string real_blkdev;
2137 unsigned char decrypted_master_key[MAX_KEY_LEN];
2138 int rc = -1, i;
2139 struct crypt_mnt_ftr crypt_ftr;
2140 struct crypt_persist_data* pdata;
2141 char encrypted_state[PROPERTY_VALUE_MAX];
2142 char lockid[32] = {0};
2143 std::string key_loc;
2144 int num_vols;
2145 off64_t previously_encrypted_upto = 0;
2146 bool rebootEncryption = false;
2147 bool onlyCreateHeader = false;
2148 // std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
2149
2150 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
2151 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2152 /* An encryption was underway and was interrupted */
2153 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2154 crypt_ftr.encrypted_upto = 0;
2155 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2156
2157 /* At this point, we are in an inconsistent state. Until we successfully
2158 complete encryption, a reboot will leave us broken. So mark the
2159 encryption failed in case that happens.
2160 On successfully completing encryption, remove this flag */
2161 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2162
2163 put_crypt_ftr_and_key(&crypt_ftr);
2164 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2165 if (!check_ftr_sha(&crypt_ftr)) {
2166 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2167 put_crypt_ftr_and_key(&crypt_ftr);
2168 goto error_unencrypted;
2169 }
2170
2171 /* Doing a reboot-encryption*/
2172 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2173 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2174 rebootEncryption = true;
2175 }
2176 } else {
2177 // We don't want to accidentally reference invalid data.
2178 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2179 }
2180
2181 property_get("ro.crypto.state", encrypted_state, "");
2182 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2183 SLOGE("Device is already running encrypted, aborting");
2184 goto error_unencrypted;
2185 }
2186
2187 get_crypt_info(&key_loc, &real_blkdev);
2188
2189 /* Get the size of the real block device */
2190 uint64_t nr_sec;
2191 if (::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
2192 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
2193 goto error_unencrypted;
2194 }
2195
2196 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
2197 if (key_loc == KEY_IN_FOOTER) {
2198 uint64_t fs_size_sec, max_fs_size_sec;
2199 fs_size_sec = get_fs_size(real_blkdev.c_str());
2200 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
2201
2202 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2203
2204 if (fs_size_sec > max_fs_size_sec) {
2205 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2206 goto error_unencrypted;
2207 }
2208 }
2209
2210 /* Get a wakelock as this may take a while, and we don't want the
2211 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2212 * wants to keep the screen on, it can grab a full wakelock.
2213 */
2214 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
2215 // wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
2216
2217 /* The init files are setup to stop the class main and late start when
2218 * vold sets trigger_shutdown_framework.
2219 */
2220 property_set("vold.decrypt", "trigger_shutdown_framework");
2221 SLOGD("Just asked init to shut down class main\n");
2222
2223 /* Ask vold to unmount all devices that it manages */
2224 // if (vold_unmountAll()) {
2225 // SLOGE("Failed to unmount all vold managed devices");
2226 // }
2227
2228 /* no_ui means we are being called from init, not settings.
2229 Now we always reboot from settings, so !no_ui means reboot
2230 */
2231 if (!no_ui) {
2232 /* Try fallback, which is to reboot and try there */
2233 onlyCreateHeader = true;
2234 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2235 if (breadcrumb == 0) {
2236 SLOGE("Failed to create breadcrumb file");
2237 goto error_shutting_down;
2238 }
2239 fclose(breadcrumb);
2240 }
2241
2242 /* Do extra work for a better UX when doing the long inplace encryption */
2243 if (!onlyCreateHeader) {
2244 /* Now that /data is unmounted, we need to mount a tmpfs
2245 * /data, set a property saying we're doing inplace encryption,
2246 * and restart the framework.
2247 */
2248 wait_and_unmount(DATA_MNT_POINT, true);
2249 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2250 goto error_shutting_down;
2251 }
2252 /* Tells the framework that inplace encryption is starting */
2253 property_set("vold.encrypt_progress", "0");
2254
2255 /* restart the framework. */
2256 /* Create necessary paths on /data */
2257 prep_data_fs();
2258
2259 /* Ugh, shutting down the framework is not synchronous, so until it
2260 * can be fixed, this horrible hack will wait a moment for it all to
2261 * shut down before proceeding. Without it, some devices cannot
2262 * restart the graphics services.
2263 */
2264 sleep(2);
2265 }
2266
2267 /* Start the actual work of making an encrypted filesystem */
2268 /* Initialize a crypt_mnt_ftr for the partition */
2269 if (previously_encrypted_upto == 0 && !rebootEncryption) {
2270 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2271 goto error_shutting_down;
2272 }
2273
2274 if (key_loc == KEY_IN_FOOTER) {
2275 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2276 } else {
2277 crypt_ftr.fs_size = nr_sec;
2278 }
2279 /* At this point, we are in an inconsistent state. Until we successfully
2280 complete encryption, a reboot will leave us broken. So mark the
2281 encryption failed in case that happens.
2282 On successfully completing encryption, remove this flag */
2283 if (onlyCreateHeader) {
2284 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2285 } else {
2286 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2287 }
2288 crypt_ftr.crypt_type = crypt_type;
2289 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
2290 MAX_CRYPTO_TYPE_NAME_LEN);
2291
2292 /* Make an encrypted master key */
2293 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2294 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2295 SLOGE("Cannot create encrypted master key\n");
2296 goto error_shutting_down;
2297 }
2298
2299 /* Replace scrypted intermediate key if we are preparing for a reboot */
2300 if (onlyCreateHeader) {
2301 unsigned char fake_master_key[MAX_KEY_LEN];
2302 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
2303 memset(fake_master_key, 0, sizeof(fake_master_key));
2304 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2305 &crypt_ftr);
2306 }
2307
2308 /* Write the key to the end of the partition */
2309 put_crypt_ftr_and_key(&crypt_ftr);
2310
2311 /* If any persistent data has been remembered, save it.
2312 * If none, create a valid empty table and save that.
2313 */
2314 if (!persist_data) {
2315 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2316 if (pdata) {
2317 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2318 persist_data = pdata;
2319 }
2320 }
2321 if (persist_data) {
2322 save_persistent_data();
2323 }
2324 }
2325
2326 if (onlyCreateHeader) {
2327 sleep(2);
2328 cryptfs_reboot(RebootType::reboot);
2329 }
2330
2331 if (!no_ui || rebootEncryption) {
2332 /* startup service classes main and late_start */
2333 property_set("vold.decrypt", "trigger_restart_min_framework");
2334 SLOGD("Just triggered restart_min_framework\n");
2335
2336 /* OK, the framework is restarted and will soon be showing a
2337 * progress bar. Time to setup an encrypted mapping, and
2338 * either write a new filesystem, or encrypt in place updating
2339 * the progress bar as we work.
2340 */
2341 }
2342
2343 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2344 ALOGE("cryptfs_enable_internal\n");
2345 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
2346 CRYPTO_BLOCK_DEVICE, 0);
2347
2348 /* If we are continuing, check checksums match */
2349 rc = 0;
2350 if (previously_encrypted_upto) {
2351 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2352 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
2353
2354 if (!rc &&
2355 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
2356 SLOGE("Checksums do not match - trigger wipe");
2357 rc = -1;
2358 }
2359 }
2360
2361 if (!rc) {
2362 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
2363 previously_encrypted_upto);
2364 }
2365
2366 /* Calculate checksum if we are not finished */
2367 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
2368 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
2369 if (rc) {
2370 SLOGE("Error calculating checksum for continuing encryption");
2371 rc = -1;
2372 }
2373 }
2374
2375 /* Undo the dm-crypt mapping whether we succeed or not */
2376 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2377
2378 if (!rc) {
2379 /* Success */
2380 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
2381
2382 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
2383 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2384 crypt_ftr.encrypted_upto);
2385 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2386 }
2387
2388 put_crypt_ftr_and_key(&crypt_ftr);
2389
2390 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2391 char value[PROPERTY_VALUE_MAX];
2392 property_get("ro.crypto.state", value, "");
2393 if (!strcmp(value, "")) {
2394 /* default encryption - continue first boot sequence */
2395 property_set("ro.crypto.state", "encrypted");
2396 property_set("ro.crypto.type", "block");
2397 // wakeLock.reset(nullptr);
2398 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2399 // Bring up cryptkeeper that will check the password and set it
2400 property_set("vold.decrypt", "trigger_shutdown_framework");
2401 sleep(2);
2402 property_set("vold.encrypt_progress", "");
2403 cryptfs_trigger_restart_min_framework();
2404 } else {
2405 cryptfs_check_passwd(DEFAULT_PASSWORD);
2406 cryptfs_restart_internal(1);
2407 }
2408 return 0;
2409 } else {
2410 sleep(2); /* Give the UI a chance to show 100% progress */
2411 cryptfs_reboot(RebootType::reboot);
2412 }
2413 } else {
2414 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
2415 cryptfs_reboot(RebootType::shutdown);
2416 }
2417 } else {
2418 char value[PROPERTY_VALUE_MAX];
2419
2420 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
2421 if (!strcmp(value, "1")) {
2422 /* wipe data if encryption failed */
2423 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2424 std::string err;
2425 const std::vector<std::string> options = {
2426 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
2427 if (!write_bootloader_message(options, &err)) {
2428 SLOGE("could not write bootloader message: %s", err.c_str());
2429 }
2430 cryptfs_reboot(RebootType::recovery);
2431 } else {
2432 /* set property to trigger dialog */
2433 property_set("vold.encrypt_progress", "error_partially_encrypted");
2434 }
2435 return -1;
2436 }
2437
2438 /* hrm, the encrypt step claims success, but the reboot failed.
2439 * This should not happen.
2440 * Set the property and return. Hope the framework can deal with it.
2441 */
2442 property_set("vold.encrypt_progress", "error_reboot_failed");
2443 return rc;
2444
2445error_unencrypted:
2446 property_set("vold.encrypt_progress", "error_not_encrypted");
2447 return -1;
2448
2449error_shutting_down:
2450 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2451 * but the framework is stopped and not restarted to show the error, so it's up to
2452 * vold to restart the system.
2453 */
2454 SLOGE(
2455 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2456 "system");
2457 cryptfs_reboot(RebootType::reboot);
2458
2459 /* shouldn't get here */
2460 property_set("vold.encrypt_progress", "error_shutting_down");
2461 return -1;
2462}
2463
2464int cryptfs_enable(int type, const char* passwd, int no_ui) {
2465 return cryptfs_enable_internal(type, passwd, no_ui);
2466}
2467
2468int cryptfs_enable_default(int no_ui) {
2469 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
2470}
2471
2472int cryptfs_changepw(int crypt_type, const char* newpw) {
2473 if (fscrypt_is_native()) {
2474 SLOGE("cryptfs_changepw not valid for file encryption");
2475 return -1;
2476 }
2477
2478 struct crypt_mnt_ftr crypt_ftr;
2479 int rc;
2480
2481 /* This is only allowed after we've successfully decrypted the master key */
2482 if (!master_key_saved) {
2483 SLOGE("Key not saved, aborting");
2484 return -1;
2485 }
2486
2487 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2488 SLOGE("Invalid crypt_type %d", crypt_type);
2489 return -1;
2490 }
2491
2492 /* get key */
2493 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2494 SLOGE("Error getting crypt footer and key");
2495 return -1;
2496 }
2497
2498 crypt_ftr.crypt_type = crypt_type;
2499
2500 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2501 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
2502 if (rc) {
2503 SLOGE("Encrypt master key failed: %d", rc);
2504 return -1;
2505 }
2506 /* save the key */
2507 put_crypt_ftr_and_key(&crypt_ftr);
2508
2509 return 0;
2510}
2511
2512static unsigned int persist_get_max_entries(int encrypted) {
2513 struct crypt_mnt_ftr crypt_ftr;
2514 unsigned int dsize;
2515
2516 /* If encrypted, use the values from the crypt_ftr, otherwise
2517 * use the values for the current spec.
2518 */
2519 if (encrypted) {
2520 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2521 /* Something is wrong, assume no space for entries */
2522 return 0;
2523 }
2524 dsize = crypt_ftr.persist_data_size;
2525 } else {
2526 dsize = CRYPT_PERSIST_DATA_SIZE;
2527 }
2528
2529 if (dsize > sizeof(struct crypt_persist_data)) {
2530 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2531 } else {
2532 return 0;
2533 }
2534}
2535
2536static int persist_get_key(const char* fieldname, char* value) {
2537 unsigned int i;
2538
2539 if (persist_data == NULL) {
2540 return -1;
2541 }
2542 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2543 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2544 /* We found it! */
2545 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2546 return 0;
2547 }
2548 }
2549
2550 return -1;
2551}
2552
2553static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
2554 unsigned int i;
2555 unsigned int num;
2556 unsigned int max_persistent_entries;
2557
2558 if (persist_data == NULL) {
2559 return -1;
2560 }
2561
2562 max_persistent_entries = persist_get_max_entries(encrypted);
2563
2564 num = persist_data->persist_valid_entries;
2565
2566 for (i = 0; i < num; i++) {
2567 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2568 /* We found an existing entry, update it! */
2569 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2570 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2571 return 0;
2572 }
2573 }
2574
2575 /* We didn't find it, add it to the end, if there is room */
2576 if (persist_data->persist_valid_entries < max_persistent_entries) {
2577 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2578 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2579 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2580 persist_data->persist_valid_entries++;
2581 return 0;
2582 }
2583
2584 return -1;
2585}
2586
2587/**
2588 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2589 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2590 */
2591int match_multi_entry(const char* key, const char* field, unsigned index) {
2592 std::string key_ = key;
2593 std::string field_ = field;
2594
2595 std::string parsed_field;
2596 unsigned parsed_index;
2597
2598 std::string::size_type split = key_.find_last_of('_');
2599 if (split == std::string::npos) {
2600 parsed_field = key_;
2601 parsed_index = 0;
2602 } else {
2603 parsed_field = key_.substr(0, split);
2604 parsed_index = std::stoi(key_.substr(split + 1));
2605 }
2606
2607 return parsed_field == field_ && parsed_index >= index;
2608}
2609
2610/*
2611 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2612 * remaining entries starting from index will be deleted.
2613 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2614 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2615 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2616 *
2617 */
2618static int persist_del_keys(const char* fieldname, unsigned index) {
2619 unsigned int i;
2620 unsigned int j;
2621 unsigned int num;
2622
2623 if (persist_data == NULL) {
2624 return PERSIST_DEL_KEY_ERROR_OTHER;
2625 }
2626
2627 num = persist_data->persist_valid_entries;
2628
2629 j = 0; // points to the end of non-deleted entries.
2630 // Filter out to-be-deleted entries in place.
2631 for (i = 0; i < num; i++) {
2632 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2633 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2634 j++;
2635 }
2636 }
2637
2638 if (j < num) {
2639 persist_data->persist_valid_entries = j;
2640 // Zeroise the remaining entries
2641 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2642 return PERSIST_DEL_KEY_OK;
2643 } else {
2644 // Did not find an entry matching the given fieldname
2645 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2646 }
2647}
2648
2649static int persist_count_keys(const char* fieldname) {
2650 unsigned int i;
2651 unsigned int count;
2652
2653 if (persist_data == NULL) {
2654 return -1;
2655 }
2656
2657 count = 0;
2658 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2659 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2660 count++;
2661 }
2662 }
2663
2664 return count;
2665}
2666
2667/* Return the value of the specified field. */
2668int cryptfs_getfield(const char* fieldname, char* value, int len) {
2669 if (fscrypt_is_native()) {
2670 SLOGE("Cannot get field when file encrypted");
2671 return -1;
2672 }
2673
2674 char temp_value[PROPERTY_VALUE_MAX];
2675 /* CRYPTO_GETFIELD_OK is success,
2676 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2677 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2678 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
2679 */
2680 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2681 int i;
2682 char temp_field[PROPERTY_KEY_MAX];
2683
2684 if (persist_data == NULL) {
2685 load_persistent_data();
2686 if (persist_data == NULL) {
2687 SLOGE("Getfield error, cannot load persistent data");
2688 goto out;
2689 }
2690 }
2691
2692 // Read value from persistent entries. If the original value is split into multiple entries,
2693 // stitch them back together.
2694 if (!persist_get_key(fieldname, temp_value)) {
2695 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2696 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
2697 // value too small
2698 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2699 goto out;
2700 }
2701 rc = CRYPTO_GETFIELD_OK;
2702
2703 for (i = 1; /* break explicitly */; i++) {
2704 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2705 (int)sizeof(temp_field)) {
2706 // If the fieldname is very long, we stop as soon as it begins to overflow the
2707 // maximum field length. At this point we have in fact fully read out the original
2708 // value because cryptfs_setfield would not allow fields with longer names to be
2709 // written in the first place.
2710 break;
2711 }
2712 if (!persist_get_key(temp_field, temp_value)) {
2713 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2714 // value too small.
2715 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2716 goto out;
2717 }
2718 } else {
2719 // Exhaust all entries.
2720 break;
2721 }
2722 }
2723 } else {
2724 /* Sadness, it's not there. Return the error */
2725 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
2726 }
2727
2728out:
2729 return rc;
2730}
2731
2732/* Set the value of the specified field. */
2733int cryptfs_setfield(const char* fieldname, const char* value) {
2734 if (fscrypt_is_native()) {
2735 SLOGE("Cannot set field when file encrypted");
2736 return -1;
2737 }
2738
2739 char encrypted_state[PROPERTY_VALUE_MAX];
2740 /* 0 is success, negative values are error */
2741 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
2742 int encrypted = 0;
2743 unsigned int field_id;
2744 char temp_field[PROPERTY_KEY_MAX];
2745 unsigned int num_entries;
2746 unsigned int max_keylen;
2747
2748 if (persist_data == NULL) {
2749 load_persistent_data();
2750 if (persist_data == NULL) {
2751 SLOGE("Setfield error, cannot load persistent data");
2752 goto out;
2753 }
2754 }
2755
2756 property_get("ro.crypto.state", encrypted_state, "");
2757 if (!strcmp(encrypted_state, "encrypted")) {
2758 encrypted = 1;
2759 }
2760
2761 // Compute the number of entries required to store value, each entry can store up to
2762 // (PROPERTY_VALUE_MAX - 1) chars
2763 if (strlen(value) == 0) {
2764 // Empty value also needs one entry to store.
2765 num_entries = 1;
2766 } else {
2767 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2768 }
2769
2770 max_keylen = strlen(fieldname);
2771 if (num_entries > 1) {
2772 // Need an extra "_%d" suffix.
2773 max_keylen += 1 + log10(num_entries);
2774 }
2775 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2776 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
2777 goto out;
2778 }
2779
2780 // Make sure we have enough space to write the new value
2781 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2782 persist_get_max_entries(encrypted)) {
2783 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2784 goto out;
2785 }
2786
2787 // Now that we know persist_data has enough space for value, let's delete the old field first
2788 // to make up space.
2789 persist_del_keys(fieldname, 0);
2790
2791 if (persist_set_key(fieldname, value, encrypted)) {
2792 // fail to set key, should not happen as we have already checked the available space
2793 SLOGE("persist_set_key() error during setfield()");
2794 goto out;
2795 }
2796
2797 for (field_id = 1; field_id < num_entries; field_id++) {
2798 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
2799
2800 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2801 // fail to set key, should not happen as we have already checked the available space.
2802 SLOGE("persist_set_key() error during setfield()");
2803 goto out;
2804 }
2805 }
2806
2807 /* If we are running encrypted, save the persistent data now */
2808 if (encrypted) {
2809 if (save_persistent_data()) {
2810 SLOGE("Setfield error, cannot save persistent data");
2811 goto out;
2812 }
2813 }
2814
2815 rc = CRYPTO_SETFIELD_OK;
2816
2817out:
2818 return rc;
2819}
2820
2821/* Checks userdata. Attempt to mount the volume if default-
2822 * encrypted.
2823 * On success trigger next init phase and return 0.
2824 * Currently do not handle failure - see TODO below.
2825 */
2826int cryptfs_mount_default_encrypted(void) {
2827 int crypt_type = cryptfs_get_password_type();
2828 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2829 SLOGE("Bad crypt type - error");
2830 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2831 SLOGD(
2832 "Password is not default - "
2833 "starting min framework to prompt");
2834 property_set("vold.decrypt", "trigger_restart_min_framework");
2835 return 0;
2836 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2837 SLOGD("Password is default - restarting filesystem");
2838 cryptfs_restart_internal(0);
2839 return 0;
2840 } else {
2841 SLOGE("Encrypted, default crypt type but can't decrypt");
2842 }
2843
2844 /** Corrupt. Allow us to boot into framework, which will detect bad
2845 crypto when it calls do_crypto_complete, then do a factory reset
2846 */
2847 property_set("vold.decrypt", "trigger_restart_min_framework");
2848 return 0;
2849}
2850
2851/* Returns type of the password, default, pattern, pin or password.
2852 */
2853int cryptfs_get_password_type(void) {
2854 if (fscrypt_is_native()) {
2855 SLOGE("cryptfs_get_password_type not valid for file encryption");
2856 return -1;
2857 }
2858
2859 struct crypt_mnt_ftr crypt_ftr;
2860
2861 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2862 SLOGE("Error getting crypt footer and key\n");
2863 return -1;
2864 }
2865
2866 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2867 return -1;
2868 }
2869
2870 return crypt_ftr.crypt_type;
2871}
2872
2873const char* cryptfs_get_password() {
2874 if (fscrypt_is_native()) {
2875 SLOGE("cryptfs_get_password not valid for file encryption");
2876 return 0;
2877 }
2878
2879 struct timespec now;
2880 clock_gettime(CLOCK_BOOTTIME, &now);
2881 if (now.tv_sec < password_expiry_time) {
2882 return password;
2883 } else {
2884 cryptfs_clear_password();
2885 return 0;
2886 }
2887}
2888
2889void cryptfs_clear_password() {
2890 if (password) {
2891 size_t len = strlen(password);
2892 memset(password, 0, len);
2893 free(password);
2894 password = 0;
2895 password_expiry_time = 0;
2896 }
2897}
2898
2899int cryptfs_isConvertibleToFBE() {
2900 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2901 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
2902}