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