blob: 496b35638f6a6940d1ef8dbb67745fdfa624dec2 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
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
Logan Chiend557d762018-05-02 11:36:45 +080017#define LOG_TAG "Cryptfs"
18
19#include "cryptfs.h"
20
Daniel Rosenberg4f684712018-08-28 01:58:49 -070021#include "Checkpoint.h"
Paul Crowley220567c2020-02-07 12:45:20 -080022#include "CryptoType.h"
Logan Chiend557d762018-05-02 11:36:45 +080023#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070024#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080025#include "Keymaster.h"
26#include "Process.h"
27#include "ScryptParameters.h"
Paul Crowley298fa322018-10-30 15:59:24 -070028#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080029#include "VoldUtil.h"
30#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080031
Eric Biggersed45ec32019-01-25 10:47:55 -080032#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080033#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080034#include <android-base/stringprintf.h>
Hyangseok Chae79b03ff2020-02-27 18:21:50 +090035#include <android-base/strings.h>
Logan Chiend557d762018-05-02 11:36:45 +080036#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080037#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070039#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080040#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070042#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070043#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080044#include <log/log.h>
Ken Sumralle550f782013-08-20 13:48:23 -070045#include <logwrap/logwrap.h>
Logan Chiend557d762018-05-02 11:36:45 +080046#include <openssl/evp.h>
47#include <openssl/sha.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080048#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070049#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080050
51#include <ctype.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <inttypes.h>
55#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080056#include <linux/kdev_t.h>
57#include <math.h>
Hyangseok Chae79b03ff2020-02-27 18:21:50 +090058#include <mntent.h>
Logan Chiend557d762018-05-02 11:36:45 +080059#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080062#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
Martijn Coenen26ad7b32020-02-13 16:20:52 +010070#include <chrono>
71#include <thread>
72
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053073#ifdef CONFIG_HW_DISK_ENCRYPTION
Neeraj Soni73b46952019-09-12 16:47:27 +053074#include <linux/dm-ioctl.h>
75#include <sys/ioctl.h>
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053076#include <cryptfs_hw.h>
77#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080078extern "C" {
79#include <crypto_scrypt.h>
80}
Mark Salyzyn3e971272014-01-21 13:27:04 -080081
Eric Biggersed45ec32019-01-25 10:47:55 -080082using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080083using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080084using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080085using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080086using android::vold::KeyBuffer;
Paul Crowleyb3d018a2020-02-12 11:04:05 -080087using android::vold::KeyGeneration;
David Andersonb9224732019-05-13 13:02:54 -070088using namespace android::dm;
Paul Crowley298fa322018-10-30 15:59:24 -070089using namespace std::chrono_literals;
90
Paul Crowley73be12d2020-02-03 12:22:03 -080091/* The current cryptfs version */
92#define CURRENT_MAJOR_VERSION 1
93#define CURRENT_MINOR_VERSION 3
94
95#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
96#define CRYPT_PERSIST_DATA_SIZE 0x1000
97
98#define MAX_CRYPTO_TYPE_NAME_LEN 64
99
100#define MAX_KEY_LEN 48
101#define SALT_LEN 16
102#define SCRYPT_LEN 32
103
104/* definitions of flags in the structure below */
105#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
106#define CRYPT_ENCRYPTION_IN_PROGRESS \
107 0x2 /* Encryption partially completed, \
108 encrypted_upto valid*/
109#define CRYPT_INCONSISTENT_STATE \
110 0x4 /* Set when starting encryption, clear when \
111 exit cleanly, either through success or \
112 correctly marked partial encryption */
113#define CRYPT_DATA_CORRUPT \
114 0x8 /* Set when encryption is fine, but the \
115 underlying volume is corrupt */
116#define CRYPT_FORCE_ENCRYPTION \
117 0x10 /* Set when it is time to encrypt this \
118 volume on boot. Everything in this \
119 structure is set up correctly as \
120 though device is encrypted except \
121 that the master key is encrypted with the \
122 default password. */
123#define CRYPT_FORCE_COMPLETE \
124 0x20 /* Set when the above encryption cycle is \
125 complete. On next cryptkeeper entry, match \
126 the password. If it matches fix the master \
127 key and remove this flag. */
128
129/* Allowed values for type in the structure below */
130#define CRYPT_TYPE_PASSWORD \
131 0 /* master_key is encrypted with a password \
132 * Must be zero to be compatible with pre-L \
133 * devices where type is always password.*/
134#define CRYPT_TYPE_DEFAULT \
135 1 /* master_key is encrypted with default \
136 * password */
137#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
138#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
139#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
140
141#define CRYPT_MNT_MAGIC 0xD0B5B1C4
142#define PERSIST_DATA_MAGIC 0xE950CD44
143
144/* Key Derivation Function algorithms */
145#define KDF_PBKDF2 1
146#define KDF_SCRYPT 2
147/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
148#define KDF_SCRYPT_KEYMASTER 5
149
150/* Maximum allowed keymaster blob size. */
151#define KEYMASTER_BLOB_SIZE 2048
152
153/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
154#define __le8 unsigned char
155
156#if !defined(SHA256_DIGEST_LENGTH)
157#define SHA256_DIGEST_LENGTH 32
158#endif
159
160/* This structure starts 16,384 bytes before the end of a hardware
161 * partition that is encrypted, or in a separate partition. It's location
162 * is specified by a property set in init.<device>.rc.
163 * The structure allocates 48 bytes for a key, but the real key size is
164 * specified in the struct. Currently, the code is hardcoded to use 128
165 * bit keys.
166 * The fields after salt are only valid in rev 1.1 and later stuctures.
167 * Obviously, the filesystem does not include the last 16 kbytes
168 * of the partition if the crypt_mnt_ftr lives at the end of the
169 * partition.
170 */
171
172struct crypt_mnt_ftr {
173 __le32 magic; /* See above */
174 __le16 major_version;
175 __le16 minor_version;
176 __le32 ftr_size; /* in bytes, not including key following */
177 __le32 flags; /* See above */
178 __le32 keysize; /* in bytes */
179 __le32 crypt_type; /* how master_key is encrypted. Must be a
180 * CRYPT_TYPE_XXX value */
181 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
182 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
183 mount, set to 0 on successful mount */
184 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
185 needed to decrypt this
186 partition, null terminated */
187 __le32 spare2; /* ignored */
188 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
189 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
190 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
191 * on device with that info, either the footer of the
192 * real_blkdevice or the metadata partition. */
193
194 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
195 * persistent data table*/
196
197 __le8 kdf_type; /* The key derivation function used. */
198
199 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
200 __le8 N_factor; /* (1 << N) */
201 __le8 r_factor; /* (1 << r) */
202 __le8 p_factor; /* (1 << p) */
203 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
204 we have to stop (e.g. power low) this is the last
205 encrypted 512 byte sector.*/
206 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
207 set, hash of first block, used
208 to validate before continuing*/
209
210 /* key_master key, used to sign the derived key which is then used to generate
211 * the intermediate key
212 * This key should be used for no other purposes! We use this key to sign unpadded
213 * data, which is acceptable but only if the key is not reused elsewhere. */
214 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
215 __le32 keymaster_blob_size;
216
217 /* Store scrypt of salted intermediate key. When decryption fails, we can
218 check if this matches, and if it does, we know that the problem is with the
219 drive, and there is no point in asking the user for more passwords.
220
221 Note that if any part of this structure is corrupt, this will not match and
222 we will continue to believe the user entered the wrong password. In that
223 case the only solution is for the user to enter a password enough times to
224 force a wipe.
225
226 Note also that there is no need to worry about migration. If this data is
227 wrong, we simply won't recognise a right password, and will continue to
228 prompt. On the first password change, this value will be populated and
229 then we will be OK.
230 */
231 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
232
233 /* sha of this structure with this element set to zero
234 Used when encrypting on reboot to validate structure before doing something
235 fatal
236 */
237 unsigned char sha256[SHA256_DIGEST_LENGTH];
238};
239
240/* Persistant data that should be available before decryption.
241 * Things like airplane mode, locale and timezone are kept
242 * here and can be retrieved by the CryptKeeper UI to properly
243 * configure the phone before asking for the password
244 * This is only valid if the major and minor version above
245 * is set to 1.1 or higher.
246 *
247 * This is a 4K structure. There are 2 copies, and the code alternates
248 * writing one and then clearing the previous one. The reading
249 * code reads the first valid copy it finds, based on the magic number.
250 * The absolute offset to the first of the two copies is kept in rev 1.1
251 * and higher crypt_mnt_ftr structures.
252 */
253struct crypt_persist_entry {
254 char key[PROPERTY_KEY_MAX];
255 char val[PROPERTY_VALUE_MAX];
256};
257
258/* Should be exactly 4K in size */
259struct crypt_persist_data {
260 __le32 persist_magic;
261 __le32 persist_valid_entries;
262 __le32 persist_spare[30];
263 struct crypt_persist_entry persist_entry[0];
264};
265
266static int wait_and_unmount(const char* mountpoint, bool kill);
267
268typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
269 void* params);
270
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800271#define UNUSED __attribute__((unused))
272
Jason parks70a4b3f2011-01-28 10:10:47 -0600273#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800274
275constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
276constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700277constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800278
279// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700280static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600281
Paul Crowley14c8c072018-09-18 13:30:21 -0700282#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700283
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530284#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700285#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800286
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800287#define CRYPTO_BLOCK_DEVICE "userdata"
288
289#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
290
Ken Sumrall29d8da82011-05-18 17:20:07 -0700291#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700292#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700293
Ken Sumralle919efe2012-09-29 17:07:41 -0700294#define TABLE_LOAD_RETRIES 10
295
Shawn Willden47ba10d2014-09-03 17:07:06 -0600296#define RSA_KEY_SIZE 2048
297#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
298#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600299#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530300#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700301
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700302#define RETRY_MOUNT_ATTEMPTS 10
303#define RETRY_MOUNT_DELAY_SECONDS 1
304
Paul Crowley5afbc622017-11-27 09:42:17 -0800305#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
306
Paul Crowley73473332017-11-21 15:43:51 -0800307static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
308
Greg Kaiser59ad0182018-02-16 13:01:36 -0800309static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700310static char* saved_mount_point;
311static int master_key_saved = 0;
312static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800313
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530314static int previous_type;
315
316#ifdef CONFIG_HW_DISK_ENCRYPTION
317static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
318 unsigned char *ikey, void *params);
319static void convert_key_to_hex_ascii(const unsigned char *master_key,
320 unsigned int keysize, char *master_key_ascii);
321static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
322static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
323 const char *passwd, const char *mount_point, const char *label);
324int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
325 const char *newpw);
326int cryptfs_check_passwd_hw(char *passwd);
327int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
328 unsigned char* master_key);
329
330static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
331 unsigned int keysize, char *master_key_ascii)
332{
333 unsigned int i, a;
334 unsigned char nibble;
335
336 for (i = 0, a = 0; i < keysize; i++, a += 2) {
337 /* For each byte, write out two ascii hex digits */
338 nibble = (master_key[i] >> 4) & 0xf;
339 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
340
341 nibble = master_key[i] & 0xf;
342 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
343 }
344
345 /* Add the null termination */
346 master_key_ascii[a] = '\0';
347}
348
349static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
350 unsigned char* salt,
351 const struct crypt_mnt_ftr *ftr)
352{
353 /* if newpw updated, return 0
354 * if newpw not updated return -1
355 */
356 int rc = -1;
357
358 if (should_use_keymaster()) {
359 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
360 SLOGE("scrypt failed");
361 } else {
362 rc = 0;
363 }
364 }
365
366 return rc;
367}
368
369static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
370{
371 unsigned char newpw[32] = {0};
372 int key_index;
373 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
374 key_index = set_hw_device_encryption_key(passwd,
375 (char*) crypt_ftr->crypto_type_name);
376 else
377 key_index = set_hw_device_encryption_key((const char*)newpw,
378 (char*) crypt_ftr->crypto_type_name);
379 return key_index;
380}
381
382static int verify_and_update_hw_fde_passwd(const char *passwd,
383 struct crypt_mnt_ftr* crypt_ftr)
384{
385 char* new_passwd = NULL;
386 unsigned char newpw[32] = {0};
387 int key_index = -1;
388 int passwd_updated = -1;
389 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
390
391 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
392 if (key_index < 0) {
393 ++crypt_ftr->failed_decrypt_count;
394
395 if (ascii_passwd_updated) {
396 SLOGI("Ascii password was updated");
397 } else {
398 /* Code in else part would execute only once:
399 * When device is upgraded from L->M release.
400 * Once upgraded, code flow should never come here.
401 * L release passed actual password in hex, so try with hex
402 * Each nible of passwd was encoded as a byte, so allocate memory
403 * twice of password len plus one more byte for null termination
404 */
405 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
406 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
407 if (new_passwd == NULL) {
408 SLOGE("System out of memory. Password verification incomplete");
409 goto out;
410 }
411 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
412 } else {
413 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
414 if (new_passwd == NULL) {
415 SLOGE("System out of memory. Password verification incomplete");
416 goto out;
417 }
418 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
419 strlen(passwd), new_passwd);
420 }
421 key_index = set_hw_device_encryption_key((const char*)new_passwd,
422 (char*) crypt_ftr->crypto_type_name);
423 if (key_index >=0) {
424 crypt_ftr->failed_decrypt_count = 0;
425 SLOGI("Hex password verified...will try to update with Ascii value");
426 /* Before updating password, tie that with keymaster to tie with ROT */
427
428 if (get_keymaster_hw_fde_passwd(passwd, newpw,
429 crypt_ftr->salt, crypt_ftr)) {
430 passwd_updated = update_hw_device_encryption_key(new_passwd,
431 passwd, (char*)crypt_ftr->crypto_type_name);
432 } else {
433 passwd_updated = update_hw_device_encryption_key(new_passwd,
434 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
435 }
436
437 if (passwd_updated >= 0) {
438 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
439 SLOGI("Ascii password recorded and updated");
440 } else {
441 SLOGI("Passwd verified, could not update...Will try next time");
442 }
443 } else {
444 ++crypt_ftr->failed_decrypt_count;
445 }
446 free(new_passwd);
447 }
448 } else {
449 if (!ascii_passwd_updated)
450 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
451 }
452out:
453 // update footer before leaving
454 put_crypt_ftr_and_key(crypt_ftr);
455 return key_index;
456}
457#endif
458
Paul Crowley220567c2020-02-07 12:45:20 -0800459constexpr CryptoType aes_128_cbc = CryptoType()
460 .set_config_name("AES-128-CBC")
461 .set_kernel_name("aes-cbc-essiv:sha256")
462 .set_keysize(16);
463
464constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
465
466static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
467 array_length(supported_crypto_types)),
468 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
469 "incompletely constructed.");
470
471static const CryptoType& get_crypto_type() {
472 // We only want to parse this read-only property once. But we need to wait
473 // until the system is initialized before we can read it. So we use a static
474 // scoped within this function to get it only once.
475 static CryptoType crypto_type =
476 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
477 aes_128_cbc, "ro.crypto.fde_algorithm");
478 return crypto_type;
479}
480
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800481const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800482 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800483}
484
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700485/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700486static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000487 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700488}
489
490/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700491static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800492 if (ftr->keymaster_blob_size) {
493 SLOGI("Already have key");
494 return 0;
495 }
496
Paul Crowley14c8c072018-09-18 13:30:21 -0700497 int rc = keymaster_create_key_for_cryptfs_scrypt(
498 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
499 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000500 if (rc) {
501 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800502 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000503 ftr->keymaster_blob_size = 0;
504 }
505 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700506 return -1;
507 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000508 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700509}
510
Shawn Willdene17a9c42014-09-08 13:04:08 -0600511/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700512static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
513 const size_t object_size, unsigned char** signature,
514 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600515 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600516 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600517 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600518
Shawn Willdene17a9c42014-09-08 13:04:08 -0600519 // To sign a message with RSA, the message must satisfy two
520 // constraints:
521 //
522 // 1. The message, when interpreted as a big-endian numeric value, must
523 // be strictly less than the public modulus of the RSA key. Note
524 // that because the most significant bit of the public modulus is
525 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
526 // key), an n-bit message with most significant bit 0 always
527 // satisfies this requirement.
528 //
529 // 2. The message must have the same length in bits as the public
530 // modulus of the RSA key. This requirement isn't mathematically
531 // necessary, but is necessary to ensure consistency in
532 // implementations.
533 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600534 case KDF_SCRYPT_KEYMASTER:
535 // This ensures the most significant byte of the signed message
536 // is zero. We could have zero-padded to the left instead, but
537 // this approach is slightly more robust against changes in
538 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600539 // so) because we really should be using a proper deterministic
540 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800541 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600542 SLOGI("Signing safely-padded object");
543 break;
544 default:
545 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000546 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600547 }
Paul Crowley73473332017-11-21 15:43:51 -0800548 for (;;) {
549 auto result = keymaster_sign_object_for_cryptfs_scrypt(
550 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
551 to_sign_size, signature, signature_size);
552 switch (result) {
553 case KeymasterSignResult::ok:
554 return 0;
555 case KeymasterSignResult::upgrade:
556 break;
557 default:
558 return -1;
559 }
560 SLOGD("Upgrading key");
561 if (keymaster_upgrade_key_for_cryptfs_scrypt(
562 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
563 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
564 &ftr->keymaster_blob_size) != 0) {
565 SLOGE("Failed to upgrade key");
566 return -1;
567 }
568 if (put_crypt_ftr_and_key(ftr) != 0) {
569 SLOGE("Failed to write upgraded key to disk");
570 }
571 SLOGD("Key upgraded successfully");
572 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600573}
574
Paul Lawrence399317e2014-03-10 13:20:50 -0700575/* Store password when userdata is successfully decrypted and mounted.
576 * Cleared by cryptfs_clear_password
577 *
578 * To avoid a double prompt at boot, we need to store the CryptKeeper
579 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
580 * Since the entire framework is torn down and rebuilt after encryption,
581 * we have to use a daemon or similar to store the password. Since vold
582 * is secured against IPC except from system processes, it seems a reasonable
583 * place to store this.
584 *
585 * password should be cleared once it has been used.
586 *
587 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800588 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700589static char* password = 0;
590static int password_expiry_time = 0;
591static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800592
Paul Crowley14c8c072018-09-18 13:30:21 -0700593enum class RebootType { reboot, recovery, shutdown };
594static void cryptfs_reboot(RebootType rt) {
595 switch (rt) {
596 case RebootType::reboot:
597 property_set(ANDROID_RB_PROPERTY, "reboot");
598 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800599
Paul Crowley14c8c072018-09-18 13:30:21 -0700600 case RebootType::recovery:
601 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
602 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800603
Paul Crowley14c8c072018-09-18 13:30:21 -0700604 case RebootType::shutdown:
605 property_set(ANDROID_RB_PROPERTY, "shutdown");
606 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700607 }
Paul Lawrence87999172014-02-20 12:21:31 -0800608
Ken Sumralladfba362013-06-04 16:37:52 -0700609 sleep(20);
610
611 /* Shouldn't get here, reboot should happen before sleep times out */
612 return;
613}
614
Kenny Rootc4c70f12013-06-14 12:11:38 -0700615/**
616 * Gets the default device scrypt parameters for key derivation time tuning.
617 * The parameters should lead to about one second derivation time for the
618 * given device.
619 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700620static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700621 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000622 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700623
Paul Crowley63c18d32016-02-10 14:02:47 +0000624 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
625 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
626 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
627 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700628 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000629 ftr->N_factor = Nf;
630 ftr->r_factor = rf;
631 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700632}
633
Tom Cherry4c5bde22019-01-29 14:34:01 -0800634static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800635 int fd, block_size;
636 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200637 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800638
Paul Crowley14c8c072018-09-18 13:30:21 -0700639 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800640 SLOGE("Cannot open device to get filesystem size ");
641 return 0;
642 }
643
644 if (lseek64(fd, 1024, SEEK_SET) < 0) {
645 SLOGE("Cannot seek to superblock");
646 return 0;
647 }
648
649 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
650 SLOGE("Cannot read superblock");
651 return 0;
652 }
653
654 close(fd);
655
Daniel Rosenberge82df162014-08-15 22:19:23 +0000656 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
657 SLOGE("Not a valid ext4 superblock");
658 return 0;
659 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800660 block_size = 1024 << sb.s_log_block_size;
661 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200662 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800663
664 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200665 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800666}
667
Tom Cherry4c5bde22019-01-29 14:34:01 -0800668static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
669 for (const auto& entry : fstab_default) {
670 if (!entry.fs_mgr_flags.vold_managed &&
671 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
672 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
673 if (key_loc != nullptr) {
674 *key_loc = entry.key_loc;
675 }
676 if (real_blk_device != nullptr) {
677 *real_blk_device = entry.blk_device;
678 }
679 return;
680 }
681 }
682}
683
Paul Crowley14c8c072018-09-18 13:30:21 -0700684static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
685 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200686 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700687 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700688 char key_loc[PROPERTY_VALUE_MAX];
689 char real_blkdev[PROPERTY_VALUE_MAX];
690 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700691
Paul Crowley14c8c072018-09-18 13:30:21 -0700692 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800693 std::string key_loc;
694 std::string real_blkdev;
695 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700696
Tom Cherry4c5bde22019-01-29 14:34:01 -0800697 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200698 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700699 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
700 * encryption info footer and key, and plenty of bytes to spare for future
701 * growth.
702 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800703 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200704 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700705 cached_data = 1;
706 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800707 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700708 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700709 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800710 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700711 cached_off = 0;
712 cached_data = 1;
713 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700714 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700715
Paul Crowley14c8c072018-09-18 13:30:21 -0700716 if (cached_data) {
717 if (metadata_fname) {
718 *metadata_fname = cached_metadata_fname;
719 }
720 if (off) {
721 *off = cached_off;
722 }
723 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700724 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700725
Paul Crowley14c8c072018-09-18 13:30:21 -0700726 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700727}
728
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800729/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700730static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800731 SHA256_CTX c;
732 SHA256_Init(&c);
733 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
734 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
735 SHA256_Final(crypt_ftr->sha256, &c);
736}
737
Ken Sumralle8744072011-01-18 22:01:55 -0800738/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800739 * update the failed mount count but not change the key.
740 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700741static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
742 int fd;
743 unsigned int cnt;
744 /* starting_off is set to the SEEK_SET offset
745 * where the crypto structure starts
746 */
747 off64_t starting_off;
748 int rc = -1;
749 char* fname = NULL;
750 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800751
Paul Crowley14c8c072018-09-18 13:30:21 -0700752 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800753
Paul Crowley14c8c072018-09-18 13:30:21 -0700754 if (get_crypt_ftr_info(&fname, &starting_off)) {
755 SLOGE("Unable to get crypt_ftr_info\n");
756 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800757 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700758 if (fname[0] != '/') {
759 SLOGE("Unexpected value for crypto key location\n");
760 return -1;
761 }
762 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
763 SLOGE("Cannot open footer file %s for put\n", fname);
764 return -1;
765 }
Ken Sumralle8744072011-01-18 22:01:55 -0800766
Paul Crowley14c8c072018-09-18 13:30:21 -0700767 /* Seek to the start of the crypt footer */
768 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
769 SLOGE("Cannot seek to real block device footer\n");
770 goto errout;
771 }
772
773 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
774 SLOGE("Cannot write real block device footer\n");
775 goto errout;
776 }
777
778 fstat(fd, &statbuf);
779 /* If the keys are kept on a raw block device, do not try to truncate it. */
780 if (S_ISREG(statbuf.st_mode)) {
781 if (ftruncate(fd, 0x4000)) {
782 SLOGE("Cannot set footer file size\n");
783 goto errout;
784 }
785 }
786
787 /* Success! */
788 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800789
790errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700791 close(fd);
792 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800793}
794
Paul Crowley14c8c072018-09-18 13:30:21 -0700795static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800796 struct crypt_mnt_ftr copy;
797 memcpy(&copy, crypt_ftr, sizeof(copy));
798 set_ftr_sha(&copy);
799 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
800}
801
Paul Crowley14c8c072018-09-18 13:30:21 -0700802static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700803 return TEMP_FAILURE_RETRY(read(fd, buff, len));
804}
805
Paul Crowley14c8c072018-09-18 13:30:21 -0700806static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700807 return TEMP_FAILURE_RETRY(write(fd, buff, len));
808}
809
Paul Crowley14c8c072018-09-18 13:30:21 -0700810static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700811 memset(pdata, 0, len);
812 pdata->persist_magic = PERSIST_DATA_MAGIC;
813 pdata->persist_valid_entries = 0;
814}
815
816/* A routine to update the passed in crypt_ftr to the lastest version.
817 * fd is open read/write on the device that holds the crypto footer and persistent
818 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
819 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
820 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700821static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700822 int orig_major = crypt_ftr->major_version;
823 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700824
Kenny Root7434b312013-06-14 11:29:53 -0700825 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700826 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700827 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700828
Kenny Rootc4c70f12013-06-14 12:11:38 -0700829 SLOGW("upgrading crypto footer to 1.1");
830
Paul Crowley14c8c072018-09-18 13:30:21 -0700831 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700832 if (pdata == NULL) {
833 SLOGE("Cannot allocate persisent data\n");
834 return;
835 }
836 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
837
838 /* Need to initialize the persistent data area */
839 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
840 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100841 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700842 return;
843 }
844 /* Write all zeros to the first copy, making it invalid */
845 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
846
847 /* Write a valid but empty structure to the second copy */
848 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
849 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
850
851 /* Update the footer */
852 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
853 crypt_ftr->persist_data_offset[0] = pdata_offset;
854 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
855 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100856 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700857 }
858
Paul Lawrencef4faa572014-01-29 13:31:03 -0800859 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700860 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800861 /* But keep the old kdf_type.
862 * It will get updated later to KDF_SCRYPT after the password has been verified.
863 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700864 crypt_ftr->kdf_type = KDF_PBKDF2;
865 get_device_scrypt_params(crypt_ftr);
866 crypt_ftr->minor_version = 2;
867 }
868
Paul Lawrencef4faa572014-01-29 13:31:03 -0800869 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
870 SLOGW("upgrading crypto footer to 1.3");
871 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
872 crypt_ftr->minor_version = 3;
873 }
874
Kenny Root7434b312013-06-14 11:29:53 -0700875 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
876 if (lseek64(fd, offset, SEEK_SET) == -1) {
877 SLOGE("Cannot seek to crypt footer\n");
878 return;
879 }
880 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700881 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700882}
883
Paul Crowley14c8c072018-09-18 13:30:21 -0700884static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
885 int fd;
886 unsigned int cnt;
887 off64_t starting_off;
888 int rc = -1;
889 char* fname = NULL;
890 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700891
Paul Crowley14c8c072018-09-18 13:30:21 -0700892 if (get_crypt_ftr_info(&fname, &starting_off)) {
893 SLOGE("Unable to get crypt_ftr_info\n");
894 return -1;
895 }
896 if (fname[0] != '/') {
897 SLOGE("Unexpected value for crypto key location\n");
898 return -1;
899 }
900 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
901 SLOGE("Cannot open footer file %s for get\n", fname);
902 return -1;
903 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800904
Paul Crowley14c8c072018-09-18 13:30:21 -0700905 /* Make sure it's 16 Kbytes in length */
906 fstat(fd, &statbuf);
907 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
908 SLOGE("footer file %s is not the expected size!\n", fname);
909 goto errout;
910 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700911
Paul Crowley14c8c072018-09-18 13:30:21 -0700912 /* Seek to the start of the crypt footer */
913 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
914 SLOGE("Cannot seek to real block device footer\n");
915 goto errout;
916 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700917
Paul Crowley14c8c072018-09-18 13:30:21 -0700918 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
919 SLOGE("Cannot read real block device footer\n");
920 goto errout;
921 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800922
Paul Crowley14c8c072018-09-18 13:30:21 -0700923 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
924 SLOGE("Bad magic for real block device %s\n", fname);
925 goto errout;
926 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800927
Paul Crowley14c8c072018-09-18 13:30:21 -0700928 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
929 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
930 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
931 goto errout;
932 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800933
Paul Crowley14c8c072018-09-18 13:30:21 -0700934 // We risk buffer overflows with oversized keys, so we just reject them.
935 // 0-sized keys are problematic (essentially by-passing encryption), and
936 // AES-CBC key wrapping only works for multiples of 16 bytes.
937 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
938 (crypt_ftr->keysize > MAX_KEY_LEN)) {
939 SLOGE(
940 "Invalid keysize (%u) for block device %s; Must be non-zero, "
941 "divisible by 16, and <= %d\n",
942 crypt_ftr->keysize, fname, MAX_KEY_LEN);
943 goto errout;
944 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800945
Paul Crowley14c8c072018-09-18 13:30:21 -0700946 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
947 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
948 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
949 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800950
Paul Crowley14c8c072018-09-18 13:30:21 -0700951 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
952 * copy on disk before returning.
953 */
954 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
955 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
956 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800957
Paul Crowley14c8c072018-09-18 13:30:21 -0700958 /* Success! */
959 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800960
961errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700962 close(fd);
963 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800964}
965
Paul Crowley14c8c072018-09-18 13:30:21 -0700966static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700967 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
968 crypt_ftr->persist_data_offset[1]) {
969 SLOGE("Crypt_ftr persist data regions overlap");
970 return -1;
971 }
972
973 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
974 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
975 return -1;
976 }
977
978 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700979 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700980 CRYPT_FOOTER_OFFSET) {
981 SLOGE("Persistent data extends past crypto footer");
982 return -1;
983 }
984
985 return 0;
986}
987
Paul Crowley14c8c072018-09-18 13:30:21 -0700988static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700989 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700990 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700991 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700992 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700993 int found = 0;
994 int fd;
995 int ret;
996 int i;
997
998 if (persist_data) {
999 /* Nothing to do, we've already loaded or initialized it */
1000 return 0;
1001 }
1002
Ken Sumrall160b4d62013-04-22 12:15:39 -07001003 /* If not encrypted, just allocate an empty table and initialize it */
1004 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001005 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -08001006 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001007 if (pdata) {
1008 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1009 persist_data = pdata;
1010 return 0;
1011 }
1012 return -1;
1013 }
1014
Paul Crowley14c8c072018-09-18 13:30:21 -07001015 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001016 return -1;
1017 }
1018
Paul Crowley14c8c072018-09-18 13:30:21 -07001019 if ((crypt_ftr.major_version < 1) ||
1020 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001021 SLOGE("Crypt_ftr version doesn't support persistent data");
1022 return -1;
1023 }
1024
1025 if (get_crypt_ftr_info(&fname, NULL)) {
1026 return -1;
1027 }
1028
1029 ret = validate_persistent_data_storage(&crypt_ftr);
1030 if (ret) {
1031 return -1;
1032 }
1033
Paul Crowley14c8c072018-09-18 13:30:21 -07001034 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001035 if (fd < 0) {
1036 SLOGE("Cannot open %s metadata file", fname);
1037 return -1;
1038 }
1039
Wei Wang4375f1b2017-02-24 17:43:01 -08001040 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -08001041 if (pdata == NULL) {
1042 SLOGE("Cannot allocate memory for persistent data");
1043 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001044 }
1045
1046 for (i = 0; i < 2; i++) {
1047 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
1048 SLOGE("Cannot seek to read persistent data on %s", fname);
1049 goto err2;
1050 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001051 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001052 SLOGE("Error reading persistent data on iteration %d", i);
1053 goto err2;
1054 }
1055 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1056 found = 1;
1057 break;
1058 }
1059 }
1060
1061 if (!found) {
1062 SLOGI("Could not find valid persistent data, creating");
1063 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
1064 }
1065
1066 /* Success */
1067 persist_data = pdata;
1068 close(fd);
1069 return 0;
1070
1071err2:
1072 free(pdata);
1073
1074err:
1075 close(fd);
1076 return -1;
1077}
1078
Paul Crowley14c8c072018-09-18 13:30:21 -07001079static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001080 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001081 struct crypt_persist_data* pdata;
1082 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001083 off64_t write_offset;
1084 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001085 int fd;
1086 int ret;
1087
1088 if (persist_data == NULL) {
1089 SLOGE("No persistent data to save");
1090 return -1;
1091 }
1092
Paul Crowley14c8c072018-09-18 13:30:21 -07001093 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001094 return -1;
1095 }
1096
Paul Crowley14c8c072018-09-18 13:30:21 -07001097 if ((crypt_ftr.major_version < 1) ||
1098 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001099 SLOGE("Crypt_ftr version doesn't support persistent data");
1100 return -1;
1101 }
1102
1103 ret = validate_persistent_data_storage(&crypt_ftr);
1104 if (ret) {
1105 return -1;
1106 }
1107
1108 if (get_crypt_ftr_info(&fname, NULL)) {
1109 return -1;
1110 }
1111
Paul Crowley14c8c072018-09-18 13:30:21 -07001112 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001113 if (fd < 0) {
1114 SLOGE("Cannot open %s metadata file", fname);
1115 return -1;
1116 }
1117
Wei Wang4375f1b2017-02-24 17:43:01 -08001118 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001119 if (pdata == NULL) {
1120 SLOGE("Cannot allocate persistant data");
1121 goto err;
1122 }
1123
1124 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1125 SLOGE("Cannot seek to read persistent data on %s", fname);
1126 goto err2;
1127 }
1128
1129 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001130 SLOGE("Error reading persistent data before save");
1131 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001132 }
1133
1134 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1135 /* The first copy is the curent valid copy, so write to
1136 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001137 write_offset = crypt_ftr.persist_data_offset[1];
1138 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001139 } else {
1140 /* The second copy must be the valid copy, so write to
1141 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001142 write_offset = crypt_ftr.persist_data_offset[0];
1143 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001144 }
1145
1146 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001147 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001148 SLOGE("Cannot seek to write persistent data");
1149 goto err2;
1150 }
1151 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001152 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001153 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001154 SLOGE("Cannot seek to erase previous persistent data");
1155 goto err2;
1156 }
1157 fsync(fd);
1158 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001159 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001160 SLOGE("Cannot write to erase previous persistent data");
1161 goto err2;
1162 }
1163 fsync(fd);
1164 } else {
1165 SLOGE("Cannot write to save persistent data");
1166 goto err2;
1167 }
1168
1169 /* Success */
1170 free(pdata);
1171 close(fd);
1172 return 0;
1173
1174err2:
1175 free(pdata);
1176err:
1177 close(fd);
1178 return -1;
1179}
1180
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001181/* Convert a binary key of specified length into an ascii hex string equivalent,
1182 * without the leading 0x and with null termination
1183 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001184static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1185 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001186 unsigned int i, a;
1187 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001188
Paul Crowley14c8c072018-09-18 13:30:21 -07001189 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001190 /* For each byte, write out two ascii hex digits */
1191 nibble = (master_key[i] >> 4) & 0xf;
1192 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001193
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001194 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001195 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001196 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001197
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001198 /* Add the null termination */
1199 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001200}
1201
Eric Biggersed45ec32019-01-25 10:47:55 -08001202/*
1203 * If the ro.crypto.fde_sector_size system property is set, append the
1204 * parameters to make dm-crypt use the specified crypto sector size and round
1205 * the crypto device size down to a crypto sector boundary.
1206 */
David Andersonb9224732019-05-13 13:02:54 -07001207static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001208 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001209 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001210
Eric Biggersed45ec32019-01-25 10:47:55 -08001211 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1212 unsigned int sector_size;
1213
1214 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1215 (sector_size & (sector_size - 1)) != 0) {
1216 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1217 DM_CRYPT_SECTOR_SIZE, value);
1218 return -1;
1219 }
1220
David Andersonb9224732019-05-13 13:02:54 -07001221 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001222
1223 // With this option, IVs will match the sector numbering, instead
1224 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001225 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001226
1227 // Round the crypto device size down to a crypto sector boundary.
1228 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001229 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001230 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001231}
1232
Neeraj Soni73b46952019-09-12 16:47:27 +05301233#if defined(CONFIG_HW_DISK_ENCRYPTION) && !defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1234#define DM_CRYPT_BUF_SIZE 4096
1235
1236static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
1237 memset(io, 0, dataSize);
1238 io->data_size = dataSize;
1239 io->data_start = sizeof(struct dm_ioctl);
1240 io->version[0] = 4;
1241 io->version[1] = 0;
1242 io->version[2] = 0;
1243 io->flags = flags;
1244 if (name) {
1245 strlcpy(io->name, name, sizeof(io->name));
1246 }
1247}
1248
1249static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1250 const unsigned char* master_key, const char* real_blk_name,
1251 const char* name, int fd, const char* extra_params) {
1252 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1253 struct dm_ioctl* io;
1254 struct dm_target_spec* tgt;
1255 char* crypt_params;
1256 // We need two ASCII characters to represent each byte, and need space for
1257 // the '\0' terminator.
1258 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1259 size_t buff_offset;
1260 int i;
1261
1262 io = (struct dm_ioctl*)buffer;
1263
1264 /* Load the mapping table for this device */
1265 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
1266
1267 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1268 io->target_count = 1;
1269 tgt->status = 0;
1270 tgt->sector_start = 0;
1271 tgt->length = crypt_ftr->fs_size;
1272 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1273 buff_offset = crypt_params - buffer;
1274 SLOGI(
1275 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1276 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1277 extra_params);
1278 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1279 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1280 if (is_ice_enabled())
1281 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1282 else
1283 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1284 }
1285 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1286 crypt_ftr->crypto_type_name, master_key_ascii,
1287 real_blk_name, extra_params);
1288
1289 SLOGI("target_type = %s", tgt->target_type);
1290 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1291
1292 crypt_params += strlen(crypt_params) + 1;
1293 crypt_params =
1294 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1295 tgt->next = crypt_params - buffer;
1296
1297 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1298 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1299 break;
1300 }
1301 usleep(500000);
1302 }
1303
1304 if (i == TABLE_LOAD_RETRIES) {
1305 /* We failed to load the table, return an error */
1306 return -1;
1307 } else {
1308 return i + 1;
1309 }
1310}
1311
1312static int create_crypto_blk_dev_hw(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1313 const char* real_blk_name, char* crypto_blk_name, const char* name,
1314 uint32_t flags) {
1315 char buffer[DM_CRYPT_BUF_SIZE];
1316 struct dm_ioctl* io;
1317 unsigned int minor;
1318 int fd = 0;
1319 int err;
1320 int retval = -1;
1321 int version[3];
1322 int load_count;
1323 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1324 char progress[PROPERTY_VALUE_MAX] = {0};
1325 const char *extra_params;
1326
1327 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1328 SLOGE("Cannot open device-mapper\n");
1329 goto errout;
1330 }
1331
1332 io = (struct dm_ioctl*)buffer;
1333
1334 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1335 err = ioctl(fd, DM_DEV_CREATE, io);
1336 if (err) {
1337 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1338 goto errout;
1339 }
1340
1341 /* Get the device status, in particular, the name of it's device file */
1342 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1343 if (ioctl(fd, DM_DEV_STATUS, io)) {
1344 SLOGE("Cannot retrieve dm-crypt device status\n");
1345 goto errout;
1346 }
1347 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1348 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1349
1350 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1351 /* Set fde_enabled if either FDE completed or in-progress */
1352 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1353 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1354 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1355 if (is_ice_enabled()) {
1356 extra_params = "fde_enabled ice allow_encrypt_override";
1357 } else {
1358 extra_params = "fde_enabled allow_encrypt_override";
1359 }
1360 } else {
1361 extra_params = "fde_enabled allow_encrypt_override";
1362 }
1363 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1364 extra_params);
1365 }
1366
1367 if (load_count < 0) {
1368 SLOGE("Cannot load dm-crypt mapping table.\n");
1369 goto errout;
1370 } else if (load_count > 1) {
1371 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1372 }
1373
1374 /* Resume this device to activate it */
1375 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1376
1377 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1378 SLOGE("Cannot resume the dm-crypt device\n");
1379 goto errout;
1380 }
1381
1382 /* Ensure the dm device has been created before returning. */
1383 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1384 // WaitForFile generates a suitable log message
1385 goto errout;
1386 }
1387
1388 /* We made it here with no errors. Woot! */
1389 retval = 0;
1390
1391errout:
1392 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1393
1394 return retval;
1395}
1396#endif
1397
Paul Crowley5afbc622017-11-27 09:42:17 -08001398static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001399 const char* real_blk_name, std::string* crypto_blk_name,
1400 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001401 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001402
David Andersonb9224732019-05-13 13:02:54 -07001403 // We need two ASCII characters to represent each byte, and need space for
1404 // the '\0' terminator.
1405 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1406 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001407
David Andersonb9224732019-05-13 13:02:54 -07001408 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1409 (const char*)crypt_ftr->crypto_type_name,
1410 master_key_ascii, 0, real_blk_name, 0);
1411 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001412
Paul Crowley5afbc622017-11-27 09:42:17 -08001413 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001414 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001415 }
David Andersonb9224732019-05-13 13:02:54 -07001416 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001417 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001418 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001419 }
David Andersonb9224732019-05-13 13:02:54 -07001420
1421 DmTable table;
1422 table.AddTarget(std::move(target));
1423
1424 int load_count = 1;
1425 while (load_count < TABLE_LOAD_RETRIES) {
1426 if (dm.CreateDevice(name, table)) {
1427 break;
1428 }
1429 load_count++;
1430 }
1431
1432 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001433 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001434 return -1;
1435 }
1436 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001437 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1438 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001439
Paul Crowley81796e92020-02-07 11:27:49 -08001440 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001441 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1442 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001443 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444
Paul Crowley298fa322018-10-30 15:59:24 -07001445 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001446 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowley298fa322018-10-30 15:59:24 -07001447 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001448 return -1;
Paul Crowley298fa322018-10-30 15:59:24 -07001449 }
David Andersonb9224732019-05-13 13:02:54 -07001450 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001451}
1452
David Andersonb9224732019-05-13 13:02:54 -07001453static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001454 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001455 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001456 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1457 // to delete the device fails with EBUSY; for now, work around this by retrying.
1458 int tries = 5;
1459 while (tries-- > 0) {
1460 ret = dm.DeleteDevice(name);
1461 if (ret || errno != EBUSY) {
1462 break;
1463 }
1464 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1465 strerror(errno));
1466 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1467 }
1468 if (!ret) {
1469 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001470 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001471 }
David Andersonb9224732019-05-13 13:02:54 -07001472 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001473}
1474
Paul Crowley14c8c072018-09-18 13:30:21 -07001475static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1476 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001477 SLOGI("Using pbkdf2 for cryptfs KDF");
1478
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001479 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001480 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1481 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001482}
1483
Paul Crowley14c8c072018-09-18 13:30:21 -07001484static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001485 SLOGI("Using scrypt for cryptfs KDF");
1486
Paul Crowley14c8c072018-09-18 13:30:21 -07001487 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001488
1489 int N = 1 << ftr->N_factor;
1490 int r = 1 << ftr->r_factor;
1491 int p = 1 << ftr->p_factor;
1492
1493 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001494 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001495 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001496
Paul Crowley14c8c072018-09-18 13:30:21 -07001497 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001498}
1499
Paul Crowley14c8c072018-09-18 13:30:21 -07001500static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1501 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001502 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1503
1504 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001505 size_t signature_size;
1506 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001507 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001508
1509 int N = 1 << ftr->N_factor;
1510 int r = 1 << ftr->r_factor;
1511 int p = 1 << ftr->p_factor;
1512
Paul Crowley14c8c072018-09-18 13:30:21 -07001513 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001514 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001515
1516 if (rc) {
1517 SLOGE("scrypt failed");
1518 return -1;
1519 }
1520
Paul Crowley14c8c072018-09-18 13:30:21 -07001521 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001522 SLOGE("Signing failed");
1523 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001524 }
1525
Paul Crowley14c8c072018-09-18 13:30:21 -07001526 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1527 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001528 free(signature);
1529
1530 if (rc) {
1531 SLOGE("scrypt failed");
1532 return -1;
1533 }
1534
1535 return 0;
1536}
1537
Paul Crowley14c8c072018-09-18 13:30:21 -07001538static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1539 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001540 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1541 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001542 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001543 EVP_CIPHER_CTX e_ctx;
1544 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001545 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001546
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001547 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001548 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001549
1550 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001551 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001552 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001553 SLOGE("keymaster_create_key failed");
1554 return -1;
1555 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001556
Paul Crowley14c8c072018-09-18 13:30:21 -07001557 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1558 SLOGE("scrypt failed");
1559 return -1;
1560 }
1561 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001562
Paul Crowley14c8c072018-09-18 13:30:21 -07001563 case KDF_SCRYPT:
1564 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1565 SLOGE("scrypt failed");
1566 return -1;
1567 }
1568 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001569
Paul Crowley14c8c072018-09-18 13:30:21 -07001570 default:
1571 SLOGE("Invalid kdf_type");
1572 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001573 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001574
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001575 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001576 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001577 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1578 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001579 SLOGE("EVP_EncryptInit failed\n");
1580 return -1;
1581 }
1582 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001583
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001585 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1586 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587 SLOGE("EVP_EncryptUpdate failed\n");
1588 return -1;
1589 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001590 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001591 SLOGE("EVP_EncryptFinal failed\n");
1592 return -1;
1593 }
1594
Greg Kaiser59ad0182018-02-16 13:01:36 -08001595 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1597 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001599
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001600 /* Store the scrypt of the intermediate key, so we can validate if it's a
1601 password error or mount error when things go wrong.
1602 Note there's no need to check for errors, since if this is incorrect, we
1603 simply won't wipe userdata, which is the correct default behavior
1604 */
1605 int N = 1 << crypt_ftr->N_factor;
1606 int r = 1 << crypt_ftr->r_factor;
1607 int p = 1 << crypt_ftr->p_factor;
1608
Paul Crowley14c8c072018-09-18 13:30:21 -07001609 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1610 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001611 sizeof(crypt_ftr->scrypted_intermediate_key));
1612
1613 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001614 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001615 }
1616
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001617 EVP_CIPHER_CTX_cleanup(&e_ctx);
1618
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001619 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620}
1621
Paul Crowley14c8c072018-09-18 13:30:21 -07001622static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1623 const unsigned char* encrypted_master_key, size_t keysize,
1624 unsigned char* decrypted_master_key, kdf_func kdf,
1625 void* kdf_params, unsigned char** intermediate_key,
1626 size_t* intermediate_key_size) {
1627 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1628 EVP_CIPHER_CTX d_ctx;
1629 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001630
Paul Crowley14c8c072018-09-18 13:30:21 -07001631 /* Turn the password into an intermediate key and IV that can decrypt the
1632 master key */
1633 if (kdf(passwd, salt, ikey, kdf_params)) {
1634 SLOGE("kdf failed");
1635 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001636 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001637
Paul Crowley14c8c072018-09-18 13:30:21 -07001638 /* Initialize the decryption engine */
1639 EVP_CIPHER_CTX_init(&d_ctx);
1640 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1641 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1642 return -1;
1643 }
1644 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1645 /* Decrypt the master key */
1646 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1647 keysize)) {
1648 return -1;
1649 }
1650 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1651 return -1;
1652 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001653
Paul Crowley14c8c072018-09-18 13:30:21 -07001654 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1655 return -1;
1656 }
1657
1658 /* Copy intermediate key if needed by params */
1659 if (intermediate_key && intermediate_key_size) {
1660 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1661 if (*intermediate_key) {
1662 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1663 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1664 }
1665 }
1666
1667 EVP_CIPHER_CTX_cleanup(&d_ctx);
1668
1669 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001670}
1671
Paul Crowley14c8c072018-09-18 13:30:21 -07001672static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001673 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001674 *kdf = scrypt_keymaster;
1675 *kdf_params = ftr;
1676 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001677 *kdf = scrypt;
1678 *kdf_params = ftr;
1679 } else {
1680 *kdf = pbkdf2;
1681 *kdf_params = NULL;
1682 }
1683}
1684
Paul Crowley14c8c072018-09-18 13:30:21 -07001685static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1686 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1687 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001688 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001689 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001690 int ret;
1691
1692 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001693 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1694 decrypted_master_key, kdf, kdf_params, intermediate_key,
1695 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001696 if (ret != 0) {
1697 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001698 }
1699
1700 return ret;
1701}
1702
Paul Crowley14c8c072018-09-18 13:30:21 -07001703static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1704 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001705 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001706
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001707 /* Get some random bits for a key and salt */
1708 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1709 return -1;
1710 }
1711 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1712 return -1;
1713 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001714
1715 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301716 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001717}
1718
Hyangseok Chae79b03ff2020-02-27 18:21:50 +09001719static void ensure_subdirectory_unmounted(const char *prefix) {
1720 std::vector<std::string> umount_points;
1721 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1722 if (!mnts) {
1723 SLOGW("could not read mount files");
1724 return;
1725 }
1726
1727 //Find sudirectory mount point
1728 mntent* mentry;
1729 std::string top_directory(prefix);
1730 if (!android::base::EndsWith(prefix, "/")) {
1731 top_directory = top_directory + "/";
1732 }
1733 while ((mentry = getmntent(mnts.get())) != nullptr) {
1734 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1735 continue;
1736 }
1737
1738 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1739 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1740 umount_points.push_back(mentry->mnt_dir);
1741 }
1742 }
1743
1744 //Sort by path length to umount longest path first
1745 std::sort(std::begin(umount_points), std::end(umount_points),
1746 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1747
1748 for (std::string& mount_point : umount_points) {
1749 umount(mount_point.c_str());
1750 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1751 }
1752}
1753
Paul Crowley73be12d2020-02-03 12:22:03 -08001754static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001755 int i, err, rc;
Hyangseok Chae79b03ff2020-02-27 18:21:50 +09001756
1757 // Subdirectory mount will cause a failure of umount.
1758 ensure_subdirectory_unmounted(mountpoint);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301759#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001760
1761 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001762 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001763 if (umount(mountpoint) == 0) {
1764 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001765 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001766
1767 if (errno == EINVAL) {
1768 /* EINVAL is returned if the directory is not a mountpoint,
1769 * i.e. there is no filesystem mounted there. So just get out.
1770 */
1771 break;
1772 }
1773
1774 err = errno;
1775
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301776 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001777 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301778 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001779 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001780 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301781 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001782 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001783 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001784 }
1785 }
1786
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301787 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001788 }
1789
1790 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001791 SLOGD("unmounting %s succeeded\n", mountpoint);
1792 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001793 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001794 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1795 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1796 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001797 }
1798
1799 return rc;
1800}
1801
Paul Crowley14c8c072018-09-18 13:30:21 -07001802static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001803 // NOTE: post_fs_data results in init calling back around to vold, so all
1804 // callers to this method must be async
1805
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001806 /* Do the prep of the /data filesystem */
1807 property_set("vold.post_fs_data_done", "0");
1808 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001809 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001810
Ken Sumrallc5872692013-05-14 15:26:31 -07001811 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001812 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001813 /* We timed out to prep /data in time. Continue wait. */
1814 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001815 }
Wei Wang42e38102017-06-07 10:46:12 -07001816 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001817}
1818
Paul Crowley14c8c072018-09-18 13:30:21 -07001819static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001820 // Mark the footer as bad
1821 struct crypt_mnt_ftr crypt_ftr;
1822 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1823 SLOGE("Failed to get crypto footer - panic");
1824 return;
1825 }
1826
1827 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1828 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1829 SLOGE("Failed to set crypto footer - panic");
1830 return;
1831 }
1832}
1833
Paul Crowley14c8c072018-09-18 13:30:21 -07001834static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001835 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001836 SLOGE("Failed to mount tmpfs on data - panic");
1837 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001838 }
1839
1840 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1841 SLOGE("Failed to trigger post fs data - panic");
1842 return;
1843 }
1844
1845 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1846 SLOGE("Failed to trigger restart min framework - panic");
1847 return;
1848 }
1849}
1850
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001851/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001852static int cryptfs_restart_internal(int restart_main) {
Yifan Hong804afe12019-02-07 12:56:47 -08001853 std::string crypto_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301854#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001855 std::string blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301856#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001857 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001858 static int restart_successful = 0;
1859
1860 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001861 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001862 SLOGE("Encrypted filesystem not validated, aborting");
1863 return -1;
1864 }
1865
1866 if (restart_successful) {
1867 SLOGE("System already restarted with encrypted disk, aborting");
1868 return -1;
1869 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001870
Paul Lawrencef4faa572014-01-29 13:31:03 -08001871 if (restart_main) {
1872 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001873 * start all services in one of these classes: core, early_hal, hal,
1874 * main and late_start. To get to the minimal UI for PIN entry, we
1875 * need to start core, early_hal, hal and main. When we want to
1876 * shutdown the framework again, we need to stop most of the services in
1877 * these classes, but only those services that were started after
1878 * /data was mounted. This excludes critical services like vold and
1879 * ueventd, which need to keep running. We could possible stop
1880 * even fewer services, but because we want services to pick up APEX
1881 * libraries from the real /data, restarting is better, as it makes
1882 * these devices consistent with FBE devices and lets them use the
1883 * most recent code.
1884 *
1885 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001886 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001887 * We then restart the class core, hal, main, and also the class
1888 * late_start.
1889 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001890 * At the moment, I've only put a few things in late_start that I know
1891 * are not needed to bring up the framework, and that also cause problems
1892 * with unmounting the tmpfs /data, but I hope to add add more services
1893 * to the late_start class as we optimize this to decrease the delay
1894 * till the user is asked for the password to the filesystem.
1895 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001896
Martijn Coenenf629b002019-04-24 10:41:11 +02001897 /* The init files are setup to stop the right set of services when
1898 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001899 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001900 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001901 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001902
Paul Lawrencef4faa572014-01-29 13:31:03 -08001903 /* Ugh, shutting down the framework is not synchronous, so until it
1904 * can be fixed, this horrible hack will wait a moment for it all to
1905 * shut down before proceeding. Without it, some devices cannot
1906 * restart the graphics services.
1907 */
1908 sleep(2);
1909 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001910
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911 /* Now that the framework is shutdown, we should be able to umount()
1912 * the tmpfs filesystem, and mount the real one.
1913 */
1914
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301915#if defined(CONFIG_HW_DISK_ENCRYPTION)
1916#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1917 if (is_ice_enabled()) {
Yifan Hong804afe12019-02-07 12:56:47 -08001918 get_crypt_info(nullptr, &blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301919 if (set_ice_param(START_ENCDEC)) {
1920 SLOGE("Failed to set ICE data");
1921 return -1;
1922 }
1923 }
1924#else
Yifan Hong804afe12019-02-07 12:56:47 -08001925 blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1926 if (blkdev.empty()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301927 SLOGE("fs_crypto_blkdev not set\n");
1928 return -1;
1929 }
1930 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1931#endif
1932#else
Yifan Hong804afe12019-02-07 12:56:47 -08001933 crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1934 if (crypto_blkdev.empty()) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001935 SLOGE("fs_crypto_blkdev not set\n");
1936 return -1;
1937 }
1938
Paul Crowley14c8c072018-09-18 13:30:21 -07001939 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301940#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001941 /* If ro.crypto.readonly is set to 1, mount the decrypted
1942 * filesystem readonly. This is used when /data is mounted by
1943 * recovery mode.
1944 */
1945 char ro_prop[PROPERTY_VALUE_MAX];
1946 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001947 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001948 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1949 if (entry != nullptr) {
1950 entry->flags |= MS_RDONLY;
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001951 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001952 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001953
Ken Sumralle5032c42012-04-01 23:58:44 -07001954 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001955 int retries = RETRY_MOUNT_ATTEMPTS;
1956 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001957
1958 /*
1959 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1960 * partitions in the fsck domain.
1961 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001962 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001963 SLOGE("Failed to setexeccon");
1964 return -1;
1965 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001966 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301967#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001968 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev.data(), 0,
Paul Lawrence67f90442020-06-12 08:12:48 -07001969 needs_cp, false)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301970#else
Yifan Hong804afe12019-02-07 12:56:47 -08001971 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev.data(), 0,
Steven Laver60b2b8d2020-06-19 08:37:05 -07001972 needs_cp, false)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301973#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001974 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1975 /* TODO: invoke something similar to
1976 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1977 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301978#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001979 SLOGI("Failed to mount %s because it is busy - waiting", blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301980#else
Yifan Hong804afe12019-02-07 12:56:47 -08001981 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301982#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001983 if (--retries) {
1984 sleep(RETRY_MOUNT_DELAY_SECONDS);
1985 } else {
1986 /* Let's hope that a reboot clears away whatever is keeping
1987 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001988 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001989 }
1990 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301991#ifdef CONFIG_HW_DISK_ENCRYPTION
1992 if (--retries) {
1993 sleep(RETRY_MOUNT_DELAY_SECONDS);
1994 } else {
1995 SLOGE("Failed to mount decrypted data");
1996 cryptfs_set_corrupt();
1997 cryptfs_trigger_restart_min_framework();
1998 SLOGI("Started framework to offer wipe");
1999 return -1;
2000 }
2001#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002002 SLOGE("Failed to mount decrypted data");
2003 cryptfs_set_corrupt();
2004 cryptfs_trigger_restart_min_framework();
2005 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002006 if (setexeccon(NULL)) {
2007 SLOGE("Failed to setexeccon");
2008 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002009 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302010#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002011 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002012 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002013 if (setexeccon(NULL)) {
2014 SLOGE("Failed to setexeccon");
2015 return -1;
2016 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002017
Ken Sumralle5032c42012-04-01 23:58:44 -07002018 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002019 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09002020 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07002021
2022 /* startup service classes main and late_start */
2023 property_set("vold.decrypt", "trigger_restart_framework");
2024 SLOGD("Just triggered restart_framework\n");
2025
2026 /* Give it a few moments to get started */
2027 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302028#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002029 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302030#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002031
Ken Sumrall0cc16632011-01-18 20:32:26 -08002032 if (rc == 0) {
2033 restart_successful = 1;
2034 }
2035
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002036 return rc;
2037}
2038
Paul Crowley14c8c072018-09-18 13:30:21 -07002039int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002040 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07002041 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002042 SLOGE("cryptfs_restart not valid for file encryption:");
2043 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002044 }
2045
Paul Lawrencef4faa572014-01-29 13:31:03 -08002046 /* Call internal implementation forcing a restart of main service group */
2047 return cryptfs_restart_internal(1);
2048}
2049
Paul Crowley14c8c072018-09-18 13:30:21 -07002050static int do_crypto_complete(const char* mount_point) {
2051 struct crypt_mnt_ftr crypt_ftr;
2052 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002053
Paul Crowley14c8c072018-09-18 13:30:21 -07002054 property_get("ro.crypto.state", encrypted_state, "");
2055 if (strcmp(encrypted_state, "encrypted")) {
2056 SLOGE("not running with encryption, aborting");
2057 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08002058 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002059
Paul Crowley14c8c072018-09-18 13:30:21 -07002060 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07002061 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002062 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2063 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002064
Paul Crowley14c8c072018-09-18 13:30:21 -07002065 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002066 std::string key_loc;
2067 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002068
Paul Crowley14c8c072018-09-18 13:30:21 -07002069 /*
2070 * Only report this error if key_loc is a file and it exists.
2071 * If the device was never encrypted, and /data is not mountable for
2072 * some reason, returning 1 should prevent the UI from presenting the
2073 * a "enter password" screen, or worse, a "press button to wipe the
2074 * device" screen.
2075 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002076 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002077 SLOGE("master key file does not exist, aborting");
2078 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2079 } else {
2080 SLOGE("Error getting crypt footer and key\n");
2081 return CRYPTO_COMPLETE_BAD_METADATA;
2082 }
2083 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002084
Paul Crowley14c8c072018-09-18 13:30:21 -07002085 // Test for possible error flags
2086 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2087 SLOGE("Encryption process is partway completed\n");
2088 return CRYPTO_COMPLETE_PARTIAL;
2089 }
2090
2091 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2092 SLOGE("Encryption process was interrupted but cannot continue\n");
2093 return CRYPTO_COMPLETE_INCONSISTENT;
2094 }
2095
2096 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
2097 SLOGE("Encryption is successful but data is corrupt\n");
2098 return CRYPTO_COMPLETE_CORRUPT;
2099 }
2100
2101 /* We passed the test! We shall diminish, and return to the west */
2102 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002103}
2104
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302105#ifdef CONFIG_HW_DISK_ENCRYPTION
2106static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2107 const char *passwd, const char *mount_point, const char *label)
2108{
Bill Peckham0db11972018-10-10 10:25:42 -07002109 /* Allocate enough space for a 256 bit key, but we may use less */
2110 unsigned char decrypted_master_key[32];
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002111 char crypto_blkdev_hw[MAXPATHLEN];
2112 std::string crypto_blkdev;
Yifan Hong804afe12019-02-07 12:56:47 -08002113 std::string real_blkdev;
Bill Peckham0db11972018-10-10 10:25:42 -07002114 unsigned int orig_failed_decrypt_count;
2115 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302116
Bill Peckham0db11972018-10-10 10:25:42 -07002117 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2118 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302119
Yifan Hong804afe12019-02-07 12:56:47 -08002120 get_crypt_info(nullptr, &real_blkdev);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302121
Bill Peckham0db11972018-10-10 10:25:42 -07002122 int key_index = 0;
2123 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2124 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2125 if (key_index < 0) {
2126 rc = crypt_ftr->failed_decrypt_count;
2127 goto errout;
2128 }
2129 else {
2130 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302131#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Neeraj Soni73b46952019-09-12 16:47:27 +05302132 if (create_crypto_blk_dev_hw(crypt_ftr, (unsigned char*)&key_index,
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002133 real_blkdev.c_str(), crypto_blkdev_hw, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002134 SLOGE("Error creating decrypted block device");
2135 rc = -1;
2136 goto errout;
2137 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302138#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002139 } else {
2140 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002141 real_blkdev.c_str(), &crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002142 SLOGE("Error creating decrypted block device");
2143 rc = -1;
2144 goto errout;
2145 }
2146 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302147 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302148 }
2149
Bill Peckham0db11972018-10-10 10:25:42 -07002150 if (rc == 0) {
2151 crypt_ftr->failed_decrypt_count = 0;
2152 if (orig_failed_decrypt_count != 0) {
2153 put_crypt_ftr_and_key(crypt_ftr);
2154 }
2155
2156 /* Save the name of the crypto block device
2157 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302158#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002159 if (!is_ice_enabled())
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002160 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev_hw);
2161#else
Bill Peckham0db11972018-10-10 10:25:42 -07002162 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002163#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002164 master_key_saved = 1;
2165 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302166
Bill Peckham0db11972018-10-10 10:25:42 -07002167 errout:
2168 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302169}
2170#endif
2171
Paul Crowley14c8c072018-09-18 13:30:21 -07002172static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2173 const char* mount_point, const char* label) {
2174 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08002175 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002176 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002177 char tmp_mount_point[64];
2178 unsigned int orig_failed_decrypt_count;
2179 int rc;
2180 int use_keymaster = 0;
2181 int upgrade = 0;
2182 unsigned char* intermediate_key = 0;
2183 size_t intermediate_key_size = 0;
2184 int N = 1 << crypt_ftr->N_factor;
2185 int r = 1 << crypt_ftr->r_factor;
2186 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302187
Paul Crowley14c8c072018-09-18 13:30:21 -07002188 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2189 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002190
Paul Crowley14c8c072018-09-18 13:30:21 -07002191 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2192 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2193 &intermediate_key_size)) {
2194 SLOGE("Failed to decrypt master key\n");
2195 rc = -1;
2196 goto errout;
2197 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002198 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002199
Tom Cherry4c5bde22019-01-29 14:34:01 -08002200 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002201
Paul Crowley14c8c072018-09-18 13:30:21 -07002202 // Create crypto block device - all (non fatal) code paths
2203 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08002204 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08002205 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002206 SLOGE("Error creating decrypted block device\n");
2207 rc = -1;
2208 goto errout;
2209 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002210
Paul Crowley14c8c072018-09-18 13:30:21 -07002211 /* Work out if the problem is the password or the data */
2212 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002213
Paul Crowley14c8c072018-09-18 13:30:21 -07002214 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2215 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2216 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002217
Paul Crowley14c8c072018-09-18 13:30:21 -07002218 // Does the key match the crypto footer?
2219 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2220 sizeof(scrypted_intermediate_key)) == 0) {
2221 SLOGI("Password matches");
2222 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002223 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002224 /* Try mounting the file system anyway, just in case the problem's with
2225 * the footer, not the key. */
2226 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2227 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08002228 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
2229 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002230 SLOGE("Error temp mounting decrypted block device\n");
2231 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002232
Paul Crowley14c8c072018-09-18 13:30:21 -07002233 rc = ++crypt_ftr->failed_decrypt_count;
2234 put_crypt_ftr_and_key(crypt_ftr);
2235 } else {
2236 /* Success! */
2237 SLOGI("Password did not match but decrypted drive mounted - continue");
2238 umount(tmp_mount_point);
2239 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002240 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002241 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002242
Paul Crowley14c8c072018-09-18 13:30:21 -07002243 if (rc == 0) {
2244 crypt_ftr->failed_decrypt_count = 0;
2245 if (orig_failed_decrypt_count != 0) {
2246 put_crypt_ftr_and_key(crypt_ftr);
2247 }
2248
2249 /* Save the name of the crypto block device
2250 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08002251 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07002252
2253 /* Also save a the master key so we can reencrypted the key
2254 * the key when we want to change the password on it. */
2255 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2256 saved_mount_point = strdup(mount_point);
2257 master_key_saved = 1;
2258 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2259 rc = 0;
2260
2261 // Upgrade if we're not using the latest KDF.
2262 use_keymaster = keymaster_check_compatibility();
2263 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2264 // Don't allow downgrade
2265 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2266 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2267 upgrade = 1;
2268 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2269 crypt_ftr->kdf_type = KDF_SCRYPT;
2270 upgrade = 1;
2271 }
2272
2273 if (upgrade) {
2274 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002275 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002276 if (!rc) {
2277 rc = put_crypt_ftr_and_key(crypt_ftr);
2278 }
2279 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2280
2281 // Do not fail even if upgrade failed - machine is bootable
2282 // Note that if this code is ever hit, there is a *serious* problem
2283 // since KDFs should never fail. You *must* fix the kdf before
2284 // proceeding!
2285 if (rc) {
2286 SLOGW(
2287 "Upgrade failed with error %d,"
2288 " but continuing with previous state",
2289 rc);
2290 rc = 0;
2291 }
2292 }
2293 }
2294
2295errout:
2296 if (intermediate_key) {
2297 memset(intermediate_key, 0, intermediate_key_size);
2298 free(intermediate_key);
2299 }
2300 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002301}
2302
Ken Sumrall29d8da82011-05-18 17:20:07 -07002303/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002304 * Called by vold when it's asked to mount an encrypted external
2305 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002306 * as any metadata is been stored in a separate, small partition. We
2307 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002308 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002309int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08002310 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08002311 auto crypto_type = get_crypto_type();
2312 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08002313 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08002314 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002315 return -1;
2316 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002317 uint64_t nr_sec = 0;
2318 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002319 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002320 return -1;
2321 }
2322
Jeff Sharkey9c484982015-03-31 10:35:33 -07002323 struct crypt_mnt_ftr ext_crypt_ftr;
2324 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2325 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08002326 ext_crypt_ftr.keysize = crypto_type.get_keysize();
2327 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002328 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002329 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002330 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002331 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2332 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002333
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002334 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
2335 real_blkdev, out_crypto_blkdev, label, flags);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002336}
2337
Paul Crowley14c8c072018-09-18 13:30:21 -07002338int cryptfs_crypto_complete(void) {
2339 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002340}
2341
Paul Crowley14c8c072018-09-18 13:30:21 -07002342int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002343 char encrypted_state[PROPERTY_VALUE_MAX];
2344 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002345 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2346 SLOGE(
2347 "encrypted fs already validated or not running with encryption,"
2348 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002349 return -1;
2350 }
2351
2352 if (get_crypt_ftr_and_key(crypt_ftr)) {
2353 SLOGE("Error getting crypt footer and key");
2354 return -1;
2355 }
2356
2357 return 0;
2358}
2359
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302360#ifdef CONFIG_HW_DISK_ENCRYPTION
2361int cryptfs_check_passwd_hw(const char* passwd)
2362{
2363 struct crypt_mnt_ftr crypt_ftr;
2364 int rc;
2365 unsigned char master_key[KEY_LEN_BYTES];
2366
2367 /* get key */
2368 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2369 SLOGE("Error getting crypt footer and key");
2370 return -1;
2371 }
2372
2373 /*
2374 * in case of manual encryption (from GUI), the encryption is done with
2375 * default password
2376 */
2377 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2378 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2379 * which was created with actual password before reboot.
2380 */
2381 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2382 if (rc) {
2383 SLOGE("password doesn't match");
2384 rc = ++crypt_ftr.failed_decrypt_count;
2385 put_crypt_ftr_and_key(&crypt_ftr);
2386 return rc;
2387 }
2388
2389 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2390 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2391
2392 if (rc) {
2393 SLOGE("Default password did not match on reboot encryption");
2394 return rc;
2395 }
2396
2397 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2398 put_crypt_ftr_and_key(&crypt_ftr);
2399 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2400 if (rc) {
2401 SLOGE("Could not change password on reboot encryption");
2402 return rc;
2403 }
2404 } else
2405 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2406 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2407
2408 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2409 cryptfs_clear_password();
2410 password = strdup(passwd);
2411 struct timespec now;
2412 clock_gettime(CLOCK_BOOTTIME, &now);
2413 password_expiry_time = now.tv_sec + password_max_age_seconds;
2414 }
2415
2416 return rc;
2417}
2418#endif
2419
Paul Crowley14c8c072018-09-18 13:30:21 -07002420int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002421 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002422 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002423 SLOGE("cryptfs_check_passwd not valid for file encryption");
2424 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002425 }
2426
Paul Lawrencef4faa572014-01-29 13:31:03 -08002427 struct crypt_mnt_ftr crypt_ftr;
2428 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002429
Paul Lawrencef4faa572014-01-29 13:31:03 -08002430 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002431 if (rc) {
2432 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002433 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002434 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002435
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302436#ifdef CONFIG_HW_DISK_ENCRYPTION
2437 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2438 return cryptfs_check_passwd_hw(passwd);
2439#endif
2440
Paul Crowley14c8c072018-09-18 13:30:21 -07002441 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002442 if (rc) {
2443 SLOGE("Password did not match");
2444 return rc;
2445 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002446
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002447 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2448 // Here we have a default actual password but a real password
2449 // we must test against the scrypted value
2450 // First, we must delete the crypto block device that
2451 // test_mount_encrypted_fs leaves behind as a side effect
2452 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002453 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2454 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002455 if (rc) {
2456 SLOGE("Default password did not match on reboot encryption");
2457 return rc;
2458 }
2459
2460 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2461 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302462 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002463 if (rc) {
2464 SLOGE("Could not change password on reboot encryption");
2465 return rc;
2466 }
2467 }
2468
2469 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002470 cryptfs_clear_password();
2471 password = strdup(passwd);
2472 struct timespec now;
2473 clock_gettime(CLOCK_BOOTTIME, &now);
2474 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002475 }
2476
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002477 return rc;
2478}
2479
Paul Crowley14c8c072018-09-18 13:30:21 -07002480int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002481 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002482 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002483 char encrypted_state[PROPERTY_VALUE_MAX];
2484 int rc;
2485
2486 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002487 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002488 SLOGE("device not encrypted, aborting");
2489 return -2;
2490 }
2491
2492 if (!master_key_saved) {
2493 SLOGE("encrypted fs not yet mounted, aborting");
2494 return -1;
2495 }
2496
2497 if (!saved_mount_point) {
2498 SLOGE("encrypted fs failed to save mount point, aborting");
2499 return -1;
2500 }
2501
Ken Sumrall160b4d62013-04-22 12:15:39 -07002502 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002503 SLOGE("Error getting crypt footer and key\n");
2504 return -1;
2505 }
2506
2507 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2508 /* If the device has no password, then just say the password is valid */
2509 rc = 0;
2510 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302511#ifdef CONFIG_HW_DISK_ENCRYPTION
2512 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2513 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2514 rc = 0;
2515 else
2516 rc = -1;
2517 } else {
2518 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2519 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2520 /* They match, the password is correct */
2521 rc = 0;
2522 } else {
2523 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2524 sleep(1);
2525 rc = 1;
2526 }
2527 }
2528#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002529 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002530 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2531 /* They match, the password is correct */
2532 rc = 0;
2533 } else {
2534 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2535 sleep(1);
2536 rc = 1;
2537 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302538#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002539 }
2540
2541 return rc;
2542}
2543
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002544/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002545 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002546 * Presumably, at a minimum, the caller will update the
2547 * filesystem size and crypto_type_name after calling this function.
2548 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002549static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002550 off64_t off;
2551
2552 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002553 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002554 ftr->major_version = CURRENT_MAJOR_VERSION;
2555 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002556 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002557 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002558
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002559 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002560 case 1:
2561 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2562 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002563
Paul Crowley14c8c072018-09-18 13:30:21 -07002564 case 0:
2565 ftr->kdf_type = KDF_SCRYPT;
2566 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002567
Paul Crowley14c8c072018-09-18 13:30:21 -07002568 default:
2569 SLOGE("keymaster_check_compatibility failed");
2570 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002571 }
2572
Kenny Rootc4c70f12013-06-14 12:11:38 -07002573 get_device_scrypt_params(ftr);
2574
Ken Sumrall160b4d62013-04-22 12:15:39 -07002575 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2576 if (get_crypt_ftr_info(NULL, &off) == 0) {
2577 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002578 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002579 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002580
2581 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002582}
2583
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002584#define FRAMEWORK_BOOT_WAIT 60
2585
Paul Crowley14c8c072018-09-18 13:30:21 -07002586static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2587 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002588 if (fd == -1) {
2589 SLOGE("Error opening file %s", filename);
2590 return -1;
2591 }
2592
2593 char block[CRYPT_INPLACE_BUFSIZE];
2594 memset(block, 0, sizeof(block));
2595 if (unix_read(fd, block, sizeof(block)) < 0) {
2596 SLOGE("Error reading file %s", filename);
2597 close(fd);
2598 return -1;
2599 }
2600
2601 close(fd);
2602
2603 SHA256_CTX c;
2604 SHA256_Init(&c);
2605 SHA256_Update(&c, block, sizeof(block));
2606 SHA256_Final(buf, &c);
2607
2608 return 0;
2609}
2610
Paul Crowley81796e92020-02-07 11:27:49 -08002611static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2612 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002613 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002614 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002615
Paul Lawrence87999172014-02-20 12:21:31 -08002616 /* The size of the userdata partition, and add in the vold volumes below */
2617 tot_encryption_size = crypt_ftr->fs_size;
2618
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002619 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002620 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002621
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002622 if (rc == ENABLE_INPLACE_ERR_DEV) {
2623 /* Hack for b/17898962 */
2624 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2625 cryptfs_reboot(RebootType::reboot);
2626 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002627
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002628 if (!rc) {
2629 crypt_ftr->encrypted_upto = cur_encryption_done;
2630 }
Paul Lawrence87999172014-02-20 12:21:31 -08002631
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002632 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2633 /* The inplace routine never actually sets the progress to 100% due
2634 * to the round down nature of integer division, so set it here */
2635 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002636 }
2637
2638 return rc;
2639}
2640
Paul Crowleyb64933a2017-10-31 08:25:55 -07002641static int vold_unmountAll(void) {
2642 VolumeManager* vm = VolumeManager::Instance();
2643 return vm->unmountAll();
2644}
2645
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002646int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002647 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002648 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002649 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002650 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002651 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002652 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002653 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002654 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002655 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002656 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002657 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002658 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002659 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302660#ifdef CONFIG_HW_DISK_ENCRYPTION
2661 unsigned char newpw[32];
2662 int key_index = 0;
2663#endif
2664 int index = 0;
Tri Vo15bbe222019-06-21 12:21:48 -07002665 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302666
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002667 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002668 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2669 /* An encryption was underway and was interrupted */
2670 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2671 crypt_ftr.encrypted_upto = 0;
2672 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002673
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002674 /* At this point, we are in an inconsistent state. Until we successfully
2675 complete encryption, a reboot will leave us broken. So mark the
2676 encryption failed in case that happens.
2677 On successfully completing encryption, remove this flag */
2678 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002679
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002680 put_crypt_ftr_and_key(&crypt_ftr);
2681 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2682 if (!check_ftr_sha(&crypt_ftr)) {
2683 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2684 put_crypt_ftr_and_key(&crypt_ftr);
2685 goto error_unencrypted;
2686 }
2687
2688 /* Doing a reboot-encryption*/
2689 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2690 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2691 rebootEncryption = true;
2692 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002693 } else {
2694 // We don't want to accidentally reference invalid data.
2695 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002696 }
2697
2698 property_get("ro.crypto.state", encrypted_state, "");
2699 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2700 SLOGE("Device is already running encrypted, aborting");
2701 goto error_unencrypted;
2702 }
2703
Tom Cherry4c5bde22019-01-29 14:34:01 -08002704 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002705
Ken Sumrall3ed82362011-01-28 23:31:16 -08002706 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002707 uint64_t nr_sec;
2708 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002709 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002710 goto error_unencrypted;
2711 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002712
2713 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002714 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002715 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002716 fs_size_sec = get_fs_size(real_blkdev.c_str());
2717 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002718
Paul Lawrence87999172014-02-20 12:21:31 -08002719 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002720
2721 if (fs_size_sec > max_fs_size_sec) {
2722 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2723 goto error_unencrypted;
2724 }
2725 }
2726
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002727 /* Get a wakelock as this may take a while, and we don't want the
2728 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2729 * wants to keep the screen on, it can grab a full wakelock.
2730 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002731 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002732 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002733
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002734 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002735 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002736 */
2737 property_set("vold.decrypt", "trigger_shutdown_framework");
2738 SLOGD("Just asked init to shut down class main\n");
2739
Jeff Sharkey9c484982015-03-31 10:35:33 -07002740 /* Ask vold to unmount all devices that it manages */
2741 if (vold_unmountAll()) {
2742 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002743 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002744
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002745 /* no_ui means we are being called from init, not settings.
2746 Now we always reboot from settings, so !no_ui means reboot
2747 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002748 if (!no_ui) {
2749 /* Try fallback, which is to reboot and try there */
2750 onlyCreateHeader = true;
2751 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2752 if (breadcrumb == 0) {
2753 SLOGE("Failed to create breadcrumb file");
2754 goto error_shutting_down;
2755 }
2756 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002757 }
2758
2759 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002760 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002761 /* Now that /data is unmounted, we need to mount a tmpfs
2762 * /data, set a property saying we're doing inplace encryption,
2763 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002764 */
xzj7e38a3a2018-10-12 10:17:11 +08002765 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002766 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002767 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002768 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002769 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002770 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002771
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002772 /* restart the framework. */
2773 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002774 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002775
Ken Sumrall92736ef2012-10-17 20:57:14 -07002776 /* Ugh, shutting down the framework is not synchronous, so until it
2777 * can be fixed, this horrible hack will wait a moment for it all to
2778 * shut down before proceeding. Without it, some devices cannot
2779 * restart the graphics services.
2780 */
2781 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002782 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002783
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002784 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002785 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002786 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002787 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2788 goto error_shutting_down;
2789 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002790
Tom Cherry4c5bde22019-01-29 14:34:01 -08002791 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002792 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002793 } else {
2794 crypt_ftr.fs_size = nr_sec;
2795 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002796 /* At this point, we are in an inconsistent state. Until we successfully
2797 complete encryption, a reboot will leave us broken. So mark the
2798 encryption failed in case that happens.
2799 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002800 if (onlyCreateHeader) {
2801 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2802 } else {
2803 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2804 }
Paul Lawrence87999172014-02-20 12:21:31 -08002805 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302806#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002807 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2808 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302809#else
Paul Crowley220567c2020-02-07 12:45:20 -08002810 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002811 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302812#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002813
Paul Lawrence87999172014-02-20 12:21:31 -08002814 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002815 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2816 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002817 SLOGE("Cannot create encrypted master key\n");
2818 goto error_shutting_down;
2819 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002820
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002821 /* Replace scrypted intermediate key if we are preparing for a reboot */
2822 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002823 unsigned char fake_master_key[MAX_KEY_LEN];
2824 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002825 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002826 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002827 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002828 }
2829
Paul Lawrence87999172014-02-20 12:21:31 -08002830 /* Write the key to the end of the partition */
2831 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002832
Paul Lawrence87999172014-02-20 12:21:31 -08002833 /* If any persistent data has been remembered, save it.
2834 * If none, create a valid empty table and save that.
2835 */
2836 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002837 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2838 if (pdata) {
2839 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2840 persist_data = pdata;
2841 }
Paul Lawrence87999172014-02-20 12:21:31 -08002842 }
2843 if (persist_data) {
2844 save_persistent_data();
2845 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002846 }
2847
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302848 /* When encryption triggered from settings, encryption starts after reboot.
2849 So set the encryption key when the actual encryption starts.
2850 */
2851#ifdef CONFIG_HW_DISK_ENCRYPTION
2852 if (previously_encrypted_upto == 0) {
2853 if (!rebootEncryption)
2854 clear_hw_device_encryption_key();
2855
2856 if (get_keymaster_hw_fde_passwd(
2857 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2858 newpw, crypt_ftr.salt, &crypt_ftr))
2859 key_index = set_hw_device_encryption_key(
2860 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2861 (char*)crypt_ftr.crypto_type_name);
2862 else
2863 key_index = set_hw_device_encryption_key((const char*)newpw,
2864 (char*) crypt_ftr.crypto_type_name);
2865 if (key_index < 0)
2866 goto error_shutting_down;
2867
2868 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2869 put_crypt_ftr_and_key(&crypt_ftr);
2870 }
2871#endif
2872
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002873 if (onlyCreateHeader) {
2874 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002875 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302876 } else {
2877 /* Do extra work for a better UX when doing the long inplace encryption */
2878 /* Now that /data is unmounted, we need to mount a tmpfs
2879 * /data, set a property saying we're doing inplace encryption,
2880 * and restart the framework.
2881 */
2882 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2883 goto error_shutting_down;
2884 }
2885 /* Tells the framework that inplace encryption is starting */
2886 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002887
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302888 /* restart the framework. */
2889 /* Create necessary paths on /data */
2890 prep_data_fs();
2891
2892 /* Ugh, shutting down the framework is not synchronous, so until it
2893 * can be fixed, this horrible hack will wait a moment for it all to
2894 * shut down before proceeding. Without it, some devices cannot
2895 * restart the graphics services.
2896 */
2897 sleep(2);
2898
Ajay Dudani87701e22014-09-17 21:02:52 -07002899 /* startup service classes main and late_start */
2900 property_set("vold.decrypt", "trigger_restart_min_framework");
2901 SLOGD("Just triggered restart_min_framework\n");
2902
2903 /* OK, the framework is restarted and will soon be showing a
2904 * progress bar. Time to setup an encrypted mapping, and
2905 * either write a new filesystem, or encrypt in place updating
2906 * the progress bar as we work.
2907 */
2908 }
2909
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002910 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302911#ifdef CONFIG_HW_DISK_ENCRYPTION
2912 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302913#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002914 crypto_blkdev = real_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302915#else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002916 create_crypto_blk_dev_hw(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302917 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302918#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302919 else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002920 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302921 CRYPTO_BLOCK_DEVICE, 0);
2922#else
Paul Crowley81796e92020-02-07 11:27:49 -08002923 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002924 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302925#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002926
Paul Lawrence87999172014-02-20 12:21:31 -08002927 /* If we are continuing, check checksums match */
2928 rc = 0;
2929 if (previously_encrypted_upto) {
2930 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302931#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2932 if (set_ice_param(START_ENCDEC)) {
2933 SLOGE("Failed to set ICE data");
2934 goto error_shutting_down;
2935 }
2936#endif
Paul Crowley81796e92020-02-07 11:27:49 -08002937 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002938
Paul Crowley14c8c072018-09-18 13:30:21 -07002939 if (!rc &&
2940 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002941 SLOGE("Checksums do not match - trigger wipe");
2942 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002943 }
2944 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002945
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302946#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2947 if (set_ice_param(START_ENC)) {
2948 SLOGE("Failed to set ICE data");
2949 goto error_shutting_down;
2950 }
2951#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002952 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002953 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002954 previously_encrypted_upto);
2955 }
2956
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302957#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2958 if (set_ice_param(START_ENCDEC)) {
2959 SLOGE("Failed to set ICE data");
2960 goto error_shutting_down;
2961 }
2962#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002963 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002964 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002965 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002966 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002967 SLOGE("Error calculating checksum for continuing encryption");
2968 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002969 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002970 }
2971
2972 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302973#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2974 if (!is_ice_enabled())
2975 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2976#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002977 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302978#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002979
Paul Crowley14c8c072018-09-18 13:30:21 -07002980 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002981 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002982 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002983
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002984 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002985 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2986 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002987 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002988 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002989
Paul Lawrence6bfed202014-07-28 12:47:22 -07002990 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002991
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002992 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2993 char value[PROPERTY_VALUE_MAX];
2994 property_get("ro.crypto.state", value, "");
2995 if (!strcmp(value, "")) {
2996 /* default encryption - continue first boot sequence */
2997 property_set("ro.crypto.state", "encrypted");
2998 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002999 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003000 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3001 // Bring up cryptkeeper that will check the password and set it
3002 property_set("vold.decrypt", "trigger_shutdown_framework");
3003 sleep(2);
3004 property_set("vold.encrypt_progress", "");
3005 cryptfs_trigger_restart_min_framework();
3006 } else {
3007 cryptfs_check_passwd(DEFAULT_PASSWORD);
3008 cryptfs_restart_internal(1);
3009 }
3010 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003011 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003012 sleep(2); /* Give the UI a chance to show 100% progress */
3013 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003014 }
Paul Lawrence87999172014-02-20 12:21:31 -08003015 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003016 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07003017 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08003018 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003019 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003020 char value[PROPERTY_VALUE_MAX];
3021
Ken Sumrall319369a2012-06-27 16:30:18 -07003022 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003023 if (!strcmp(value, "1")) {
3024 /* wipe data if encryption failed */
3025 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08003026 std::string err;
3027 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07003028 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08003029 if (!write_bootloader_message(options, &err)) {
3030 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003031 }
Josh Gaofec44372017-08-28 13:22:55 -07003032 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003033 } else {
3034 /* set property to trigger dialog */
3035 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003036 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003037 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003038 }
3039
Ken Sumrall3ed82362011-01-28 23:31:16 -08003040 /* hrm, the encrypt step claims success, but the reboot failed.
3041 * This should not happen.
3042 * Set the property and return. Hope the framework can deal with it.
3043 */
3044 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003045 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003046
3047error_unencrypted:
3048 property_set("vold.encrypt_progress", "error_not_encrypted");
3049 return -1;
3050
3051error_shutting_down:
3052 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3053 * but the framework is stopped and not restarted to show the error, so it's up to
3054 * vold to restart the system.
3055 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003056 SLOGE(
3057 "Error enabling encryption after framework is shutdown, no data changed, restarting "
3058 "system");
Josh Gaofec44372017-08-28 13:22:55 -07003059 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003060
3061 /* shouldn't get here */
3062 property_set("vold.encrypt_progress", "error_shutting_down");
3063 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003064}
3065
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003066int cryptfs_enable(int type, const char* passwd, int no_ui) {
3067 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003068}
3069
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003070int cryptfs_enable_default(int no_ui) {
3071 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003072}
3073
Bill Peckham0db11972018-10-10 10:25:42 -07003074int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07003075 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003076 SLOGE("cryptfs_changepw not valid for file encryption");
3077 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003078 }
3079
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003080 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003081 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003082
3083 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003084 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003085 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086 return -1;
3087 }
3088
Paul Lawrencef4faa572014-01-29 13:31:03 -08003089 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3090 SLOGE("Invalid crypt_type %d", crypt_type);
3091 return -1;
3092 }
3093
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003094 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003095 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003096 SLOGE("Error getting crypt footer and key");
3097 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003098 }
3099
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303100#ifdef CONFIG_HW_DISK_ENCRYPTION
3101 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
3102 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
3103 else {
3104 crypt_ftr.crypt_type = crypt_type;
3105
3106 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
3107 DEFAULT_PASSWORD : newpw,
3108 crypt_ftr.salt,
3109 saved_master_key,
3110 crypt_ftr.master_key,
3111 &crypt_ftr, false);
3112 if (rc) {
3113 SLOGE("Encrypt master key failed: %d", rc);
3114 return -1;
3115 }
3116 /* save the key */
3117 put_crypt_ftr_and_key(&crypt_ftr);
3118
3119 return 0;
3120 }
3121#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003122 crypt_ftr.crypt_type = crypt_type;
3123
Paul Crowley14c8c072018-09-18 13:30:21 -07003124 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07003125 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
3126 false);
JP Abgrall933216c2015-02-11 13:44:32 -08003127 if (rc) {
3128 SLOGE("Encrypt master key failed: %d", rc);
3129 return -1;
3130 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003131 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003132 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003133
3134 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303135#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003136}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003137
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303138#ifdef CONFIG_HW_DISK_ENCRYPTION
3139int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3140{
3141 struct crypt_mnt_ftr crypt_ftr;
3142 int rc;
3143 int previous_type;
3144
3145 /* get key */
3146 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3147 SLOGE("Error getting crypt footer and key");
3148 return -1;
3149 }
3150
3151 previous_type = crypt_ftr.crypt_type;
3152 int rc1;
3153 unsigned char tmp_curpw[32] = {0};
3154 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3155 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3156 crypt_ftr.salt, &crypt_ftr);
3157
3158 crypt_ftr.crypt_type = crypt_type;
3159
3160 int ret, rc2;
3161 unsigned char tmp_newpw[32] = {0};
3162
3163 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3164 DEFAULT_PASSWORD : newpw , tmp_newpw,
3165 crypt_ftr.salt, &crypt_ftr);
3166
3167 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3168 ret = update_hw_device_encryption_key(
3169 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3170 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3171 (char*)crypt_ftr.crypto_type_name);
3172 if (ret) {
3173 SLOGE("Error updating device encryption hardware key ret %d", ret);
3174 return -1;
3175 } else {
3176 SLOGI("Encryption hardware key updated");
3177 }
3178 }
3179
3180 /* save the key */
3181 put_crypt_ftr_and_key(&crypt_ftr);
3182 return 0;
3183}
3184#endif
3185
Rubin Xu85c01f92014-10-13 12:49:54 +01003186static unsigned int persist_get_max_entries(int encrypted) {
3187 struct crypt_mnt_ftr crypt_ftr;
3188 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003189
3190 /* If encrypted, use the values from the crypt_ftr, otherwise
3191 * use the values for the current spec.
3192 */
3193 if (encrypted) {
3194 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003195 /* Something is wrong, assume no space for entries */
3196 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003197 }
3198 dsize = crypt_ftr.persist_data_size;
3199 } else {
3200 dsize = CRYPT_PERSIST_DATA_SIZE;
3201 }
3202
Rubin Xud78181b2018-10-09 16:13:38 +01003203 if (dsize > sizeof(struct crypt_persist_data)) {
3204 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3205 } else {
3206 return 0;
3207 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003208}
3209
Paul Crowley14c8c072018-09-18 13:30:21 -07003210static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003211 unsigned int i;
3212
3213 if (persist_data == NULL) {
3214 return -1;
3215 }
3216 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3217 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3218 /* We found it! */
3219 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3220 return 0;
3221 }
3222 }
3223
3224 return -1;
3225}
3226
Paul Crowley14c8c072018-09-18 13:30:21 -07003227static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003228 unsigned int i;
3229 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003230 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003231
3232 if (persist_data == NULL) {
3233 return -1;
3234 }
3235
Rubin Xu85c01f92014-10-13 12:49:54 +01003236 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003237
3238 num = persist_data->persist_valid_entries;
3239
3240 for (i = 0; i < num; i++) {
3241 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3242 /* We found an existing entry, update it! */
3243 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3244 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3245 return 0;
3246 }
3247 }
3248
3249 /* We didn't find it, add it to the end, if there is room */
3250 if (persist_data->persist_valid_entries < max_persistent_entries) {
3251 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3252 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3253 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3254 persist_data->persist_valid_entries++;
3255 return 0;
3256 }
3257
3258 return -1;
3259}
3260
Rubin Xu85c01f92014-10-13 12:49:54 +01003261/**
3262 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3263 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3264 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003265int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003266 std::string key_ = key;
3267 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003268
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003269 std::string parsed_field;
3270 unsigned parsed_index;
3271
3272 std::string::size_type split = key_.find_last_of('_');
3273 if (split == std::string::npos) {
3274 parsed_field = key_;
3275 parsed_index = 0;
3276 } else {
3277 parsed_field = key_.substr(0, split);
3278 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003279 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003280
3281 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003282}
3283
3284/*
3285 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3286 * remaining entries starting from index will be deleted.
3287 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3288 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3289 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3290 *
3291 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003292static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003293 unsigned int i;
3294 unsigned int j;
3295 unsigned int num;
3296
3297 if (persist_data == NULL) {
3298 return PERSIST_DEL_KEY_ERROR_OTHER;
3299 }
3300
3301 num = persist_data->persist_valid_entries;
3302
Paul Crowley14c8c072018-09-18 13:30:21 -07003303 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003304 // Filter out to-be-deleted entries in place.
3305 for (i = 0; i < num; i++) {
3306 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3307 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3308 j++;
3309 }
3310 }
3311
3312 if (j < num) {
3313 persist_data->persist_valid_entries = j;
3314 // Zeroise the remaining entries
3315 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3316 return PERSIST_DEL_KEY_OK;
3317 } else {
3318 // Did not find an entry matching the given fieldname
3319 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3320 }
3321}
3322
Paul Crowley14c8c072018-09-18 13:30:21 -07003323static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003324 unsigned int i;
3325 unsigned int count;
3326
3327 if (persist_data == NULL) {
3328 return -1;
3329 }
3330
3331 count = 0;
3332 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3333 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3334 count++;
3335 }
3336 }
3337
3338 return count;
3339}
3340
Ken Sumrall160b4d62013-04-22 12:15:39 -07003341/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003342int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003343 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003344 SLOGE("Cannot get field when file encrypted");
3345 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003346 }
3347
Ken Sumrall160b4d62013-04-22 12:15:39 -07003348 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003349 /* CRYPTO_GETFIELD_OK is success,
3350 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3351 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3352 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003353 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003354 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3355 int i;
3356 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003357
3358 if (persist_data == NULL) {
3359 load_persistent_data();
3360 if (persist_data == NULL) {
3361 SLOGE("Getfield error, cannot load persistent data");
3362 goto out;
3363 }
3364 }
3365
Rubin Xu85c01f92014-10-13 12:49:54 +01003366 // Read value from persistent entries. If the original value is split into multiple entries,
3367 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003368 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003369 // We found it, copy it to the caller's buffer and keep going until all entries are read.
Paul Crowley14c8c072018-09-18 13:30:21 -07003370 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003371 // value too small
3372 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3373 goto out;
3374 }
3375 rc = CRYPTO_GETFIELD_OK;
3376
3377 for (i = 1; /* break explicitly */; i++) {
3378 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003379 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003380 // If the fieldname is very long, we stop as soon as it begins to overflow the
3381 // maximum field length. At this point we have in fact fully read out the original
3382 // value because cryptfs_setfield would not allow fields with longer names to be
3383 // written in the first place.
3384 break;
3385 }
3386 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003387 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3388 // value too small.
3389 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3390 goto out;
3391 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003392 } else {
3393 // Exhaust all entries.
3394 break;
3395 }
3396 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003397 } else {
3398 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003399 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003400 }
3401
3402out:
3403 return rc;
3404}
3405
3406/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003407int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003408 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003409 SLOGE("Cannot set field when file encrypted");
3410 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003411 }
3412
Ken Sumrall160b4d62013-04-22 12:15:39 -07003413 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003414 /* 0 is success, negative values are error */
3415 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003416 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003417 unsigned int field_id;
3418 char temp_field[PROPERTY_KEY_MAX];
3419 unsigned int num_entries;
3420 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003421
3422 if (persist_data == NULL) {
3423 load_persistent_data();
3424 if (persist_data == NULL) {
3425 SLOGE("Setfield error, cannot load persistent data");
3426 goto out;
3427 }
3428 }
3429
3430 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003431 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003432 encrypted = 1;
3433 }
3434
Rubin Xu85c01f92014-10-13 12:49:54 +01003435 // Compute the number of entries required to store value, each entry can store up to
3436 // (PROPERTY_VALUE_MAX - 1) chars
3437 if (strlen(value) == 0) {
3438 // Empty value also needs one entry to store.
3439 num_entries = 1;
3440 } else {
3441 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3442 }
3443
3444 max_keylen = strlen(fieldname);
3445 if (num_entries > 1) {
3446 // Need an extra "_%d" suffix.
3447 max_keylen += 1 + log10(num_entries);
3448 }
3449 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3450 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003451 goto out;
3452 }
3453
Rubin Xu85c01f92014-10-13 12:49:54 +01003454 // Make sure we have enough space to write the new value
3455 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3456 persist_get_max_entries(encrypted)) {
3457 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3458 goto out;
3459 }
3460
3461 // Now that we know persist_data has enough space for value, let's delete the old field first
3462 // to make up space.
3463 persist_del_keys(fieldname, 0);
3464
3465 if (persist_set_key(fieldname, value, encrypted)) {
3466 // fail to set key, should not happen as we have already checked the available space
3467 SLOGE("persist_set_key() error during setfield()");
3468 goto out;
3469 }
3470
3471 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003472 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003473
3474 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3475 // fail to set key, should not happen as we have already checked the available space.
3476 SLOGE("persist_set_key() error during setfield()");
3477 goto out;
3478 }
3479 }
3480
Ken Sumrall160b4d62013-04-22 12:15:39 -07003481 /* If we are running encrypted, save the persistent data now */
3482 if (encrypted) {
3483 if (save_persistent_data()) {
3484 SLOGE("Setfield error, cannot save persistent data");
3485 goto out;
3486 }
3487 }
3488
Rubin Xu85c01f92014-10-13 12:49:54 +01003489 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003490
3491out:
3492 return rc;
3493}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003494
3495/* Checks userdata. Attempt to mount the volume if default-
3496 * encrypted.
3497 * On success trigger next init phase and return 0.
3498 * Currently do not handle failure - see TODO below.
3499 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003500int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003501 int crypt_type = cryptfs_get_password_type();
3502 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3503 SLOGE("Bad crypt type - error");
3504 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003505 SLOGD(
3506 "Password is not default - "
3507 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003508 property_set("vold.decrypt", "trigger_restart_min_framework");
3509 return 0;
3510 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3511 SLOGD("Password is default - restarting filesystem");
3512 cryptfs_restart_internal(0);
3513 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003514 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003515 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003516 }
3517
Paul Lawrence6bfed202014-07-28 12:47:22 -07003518 /** Corrupt. Allow us to boot into framework, which will detect bad
3519 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003520 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003521 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003522 return 0;
3523}
3524
3525/* Returns type of the password, default, pattern, pin or password.
3526 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003527int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003528 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003529 SLOGE("cryptfs_get_password_type not valid for file encryption");
3530 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003531 }
3532
Paul Lawrencef4faa572014-01-29 13:31:03 -08003533 struct crypt_mnt_ftr crypt_ftr;
3534
3535 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3536 SLOGE("Error getting crypt footer and key\n");
3537 return -1;
3538 }
3539
Paul Lawrence6bfed202014-07-28 12:47:22 -07003540 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3541 return -1;
3542 }
3543
Paul Lawrencef4faa572014-01-29 13:31:03 -08003544 return crypt_ftr.crypt_type;
3545}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003546
Paul Crowley14c8c072018-09-18 13:30:21 -07003547const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003548 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003549 SLOGE("cryptfs_get_password not valid for file encryption");
3550 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003551 }
3552
Paul Lawrence399317e2014-03-10 13:20:50 -07003553 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003554 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003555 if (now.tv_sec < password_expiry_time) {
3556 return password;
3557 } else {
3558 cryptfs_clear_password();
3559 return 0;
3560 }
3561}
3562
Paul Crowley14c8c072018-09-18 13:30:21 -07003563void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003564 if (password) {
3565 size_t len = strlen(password);
3566 memset(password, 0, len);
3567 free(password);
3568 password = 0;
3569 password_expiry_time = 0;
3570 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003571}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003572
Paul Crowley14c8c072018-09-18 13:30:21 -07003573int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003574 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3575 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003576}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303577
3578int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3579{
3580 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3581 SLOGE("Failed to initialize crypt_ftr");
3582 return -1;
3583 }
3584
3585 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3586 crypt_ftr->salt, crypt_ftr)) {
3587 SLOGE("Cannot create encrypted master key\n");
3588 return -1;
3589 }
3590
3591 //crypt_ftr->keysize = key_length / 8;
3592 return 0;
3593}
3594
3595int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3596 unsigned char* master_key)
3597{
3598 int rc;
3599
3600 unsigned char* intermediate_key = 0;
3601 size_t intermediate_key_size = 0;
3602
3603 if (password == 0 || *password == 0) {
3604 password = DEFAULT_PASSWORD;
3605 }
3606
3607 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3608 &intermediate_key_size);
3609
3610 if (rc) {
3611 SLOGE("Can't calculate intermediate key");
3612 return rc;
3613 }
3614
3615 int N = 1 << ftr->N_factor;
3616 int r = 1 << ftr->r_factor;
3617 int p = 1 << ftr->p_factor;
3618
3619 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3620
3621 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3622 ftr->salt, sizeof(ftr->salt), N, r, p,
3623 scrypted_intermediate_key,
3624 sizeof(scrypted_intermediate_key));
3625
3626 free(intermediate_key);
3627
3628 if (rc) {
3629 SLOGE("Can't scrypt intermediate key");
3630 return rc;
3631 }
3632
3633 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3634 intermediate_key_size);
3635}