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