blob: a4792f21a14143210da3f4cc7c8fe8b88514a7cf [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
Eric Biggersf038c5f2020-11-03 14:11:02 -080098#define CRYPT_SECTOR_SIZE 512
99
Paul Crowley73be12d2020-02-03 12:22:03 -0800100#define MAX_CRYPTO_TYPE_NAME_LEN 64
101
102#define MAX_KEY_LEN 48
103#define SALT_LEN 16
104#define SCRYPT_LEN 32
105
106/* definitions of flags in the structure below */
107#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
Eric Biggersc01995e2020-11-03 14:11:00 -0800108#define CRYPT_ENCRYPTION_IN_PROGRESS 0x2 /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800109#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) */
Eric Biggersc01995e2020-11-03 14:11:00 -0800203 __le64 encrypted_upto; /* no longer used */
204 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800205
206 /* key_master key, used to sign the derived key which is then used to generate
207 * the intermediate key
208 * This key should be used for no other purposes! We use this key to sign unpadded
209 * data, which is acceptable but only if the key is not reused elsewhere. */
210 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
211 __le32 keymaster_blob_size;
212
213 /* Store scrypt of salted intermediate key. When decryption fails, we can
214 check if this matches, and if it does, we know that the problem is with the
215 drive, and there is no point in asking the user for more passwords.
216
217 Note that if any part of this structure is corrupt, this will not match and
218 we will continue to believe the user entered the wrong password. In that
219 case the only solution is for the user to enter a password enough times to
220 force a wipe.
221
222 Note also that there is no need to worry about migration. If this data is
223 wrong, we simply won't recognise a right password, and will continue to
224 prompt. On the first password change, this value will be populated and
225 then we will be OK.
226 */
227 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
228
229 /* sha of this structure with this element set to zero
230 Used when encrypting on reboot to validate structure before doing something
231 fatal
232 */
233 unsigned char sha256[SHA256_DIGEST_LENGTH];
234};
235
236/* Persistant data that should be available before decryption.
237 * Things like airplane mode, locale and timezone are kept
238 * here and can be retrieved by the CryptKeeper UI to properly
239 * configure the phone before asking for the password
240 * This is only valid if the major and minor version above
241 * is set to 1.1 or higher.
242 *
243 * This is a 4K structure. There are 2 copies, and the code alternates
244 * writing one and then clearing the previous one. The reading
245 * code reads the first valid copy it finds, based on the magic number.
246 * The absolute offset to the first of the two copies is kept in rev 1.1
247 * and higher crypt_mnt_ftr structures.
248 */
249struct crypt_persist_entry {
250 char key[PROPERTY_KEY_MAX];
251 char val[PROPERTY_VALUE_MAX];
252};
253
254/* Should be exactly 4K in size */
255struct crypt_persist_data {
256 __le32 persist_magic;
257 __le32 persist_valid_entries;
258 __le32 persist_spare[30];
259 struct crypt_persist_entry persist_entry[0];
260};
261
262static int wait_and_unmount(const char* mountpoint, bool kill);
263
264typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
265 void* params);
266
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800267#define UNUSED __attribute__((unused))
268
Jason parks70a4b3f2011-01-28 10:10:47 -0600269#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800270
271constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
272constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700273constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800274
275// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700276static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600277
Paul Crowley14c8c072018-09-18 13:30:21 -0700278#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700279
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530280#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700281#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800282
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800283#define CRYPTO_BLOCK_DEVICE "userdata"
284
285#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
286
Ken Sumrall29d8da82011-05-18 17:20:07 -0700287#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700288#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700289
Ken Sumralle919efe2012-09-29 17:07:41 -0700290#define TABLE_LOAD_RETRIES 10
291
Shawn Willden47ba10d2014-09-03 17:07:06 -0600292#define RSA_KEY_SIZE 2048
293#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
294#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600295#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530296#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700297
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700298#define RETRY_MOUNT_ATTEMPTS 10
299#define RETRY_MOUNT_DELAY_SECONDS 1
300
Paul Crowley5afbc622017-11-27 09:42:17 -0800301#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
302
Paul Crowley73473332017-11-21 15:43:51 -0800303static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
304
Greg Kaiser59ad0182018-02-16 13:01:36 -0800305static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700306static char* saved_mount_point;
307static int master_key_saved = 0;
308static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800309
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530310static int previous_type;
311
312#ifdef CONFIG_HW_DISK_ENCRYPTION
313static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
314 unsigned char *ikey, void *params);
315static void convert_key_to_hex_ascii(const unsigned char *master_key,
316 unsigned int keysize, char *master_key_ascii);
317static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
318static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
319 const char *passwd, const char *mount_point, const char *label);
320int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
321 const char *newpw);
322int cryptfs_check_passwd_hw(char *passwd);
323int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
324 unsigned char* master_key);
325
326static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
327 unsigned int keysize, char *master_key_ascii)
328{
329 unsigned int i, a;
330 unsigned char nibble;
331
332 for (i = 0, a = 0; i < keysize; i++, a += 2) {
333 /* For each byte, write out two ascii hex digits */
334 nibble = (master_key[i] >> 4) & 0xf;
335 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
336
337 nibble = master_key[i] & 0xf;
338 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
339 }
340
341 /* Add the null termination */
342 master_key_ascii[a] = '\0';
343}
344
345static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
346 unsigned char* salt,
347 const struct crypt_mnt_ftr *ftr)
348{
349 /* if newpw updated, return 0
350 * if newpw not updated return -1
351 */
352 int rc = -1;
353
354 if (should_use_keymaster()) {
355 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
356 SLOGE("scrypt failed");
357 } else {
358 rc = 0;
359 }
360 }
361
362 return rc;
363}
364
365static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
366{
367 unsigned char newpw[32] = {0};
368 int key_index;
369 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
370 key_index = set_hw_device_encryption_key(passwd,
371 (char*) crypt_ftr->crypto_type_name);
372 else
373 key_index = set_hw_device_encryption_key((const char*)newpw,
374 (char*) crypt_ftr->crypto_type_name);
375 return key_index;
376}
377
378static int verify_and_update_hw_fde_passwd(const char *passwd,
379 struct crypt_mnt_ftr* crypt_ftr)
380{
381 char* new_passwd = NULL;
382 unsigned char newpw[32] = {0};
383 int key_index = -1;
384 int passwd_updated = -1;
385 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
386
387 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
388 if (key_index < 0) {
389 ++crypt_ftr->failed_decrypt_count;
390
391 if (ascii_passwd_updated) {
392 SLOGI("Ascii password was updated");
393 } else {
394 /* Code in else part would execute only once:
395 * When device is upgraded from L->M release.
396 * Once upgraded, code flow should never come here.
397 * L release passed actual password in hex, so try with hex
398 * Each nible of passwd was encoded as a byte, so allocate memory
399 * twice of password len plus one more byte for null termination
400 */
401 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
402 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
403 if (new_passwd == NULL) {
404 SLOGE("System out of memory. Password verification incomplete");
405 goto out;
406 }
407 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
408 } else {
409 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
410 if (new_passwd == NULL) {
411 SLOGE("System out of memory. Password verification incomplete");
412 goto out;
413 }
414 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
415 strlen(passwd), new_passwd);
416 }
417 key_index = set_hw_device_encryption_key((const char*)new_passwd,
418 (char*) crypt_ftr->crypto_type_name);
419 if (key_index >=0) {
420 crypt_ftr->failed_decrypt_count = 0;
421 SLOGI("Hex password verified...will try to update with Ascii value");
422 /* Before updating password, tie that with keymaster to tie with ROT */
423
424 if (get_keymaster_hw_fde_passwd(passwd, newpw,
425 crypt_ftr->salt, crypt_ftr)) {
426 passwd_updated = update_hw_device_encryption_key(new_passwd,
427 passwd, (char*)crypt_ftr->crypto_type_name);
428 } else {
429 passwd_updated = update_hw_device_encryption_key(new_passwd,
430 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
431 }
432
433 if (passwd_updated >= 0) {
434 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
435 SLOGI("Ascii password recorded and updated");
436 } else {
437 SLOGI("Passwd verified, could not update...Will try next time");
438 }
439 } else {
440 ++crypt_ftr->failed_decrypt_count;
441 }
442 free(new_passwd);
443 }
444 } else {
445 if (!ascii_passwd_updated)
446 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
447 }
448out:
449 // update footer before leaving
450 put_crypt_ftr_and_key(crypt_ftr);
451 return key_index;
452}
453#endif
454
Paul Crowley220567c2020-02-07 12:45:20 -0800455constexpr CryptoType aes_128_cbc = CryptoType()
456 .set_config_name("AES-128-CBC")
457 .set_kernel_name("aes-cbc-essiv:sha256")
458 .set_keysize(16);
459
460constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
461
462static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
463 array_length(supported_crypto_types)),
464 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
465 "incompletely constructed.");
466
467static const CryptoType& get_crypto_type() {
468 // We only want to parse this read-only property once. But we need to wait
469 // until the system is initialized before we can read it. So we use a static
470 // scoped within this function to get it only once.
471 static CryptoType crypto_type =
472 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
473 aes_128_cbc, "ro.crypto.fde_algorithm");
474 return crypto_type;
475}
476
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800477const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800478 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800479}
480
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700481/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700482static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000483 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700484}
485
486/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700487static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800488 if (ftr->keymaster_blob_size) {
489 SLOGI("Already have key");
490 return 0;
491 }
492
Paul Crowley14c8c072018-09-18 13:30:21 -0700493 int rc = keymaster_create_key_for_cryptfs_scrypt(
494 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
495 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000496 if (rc) {
497 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800498 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000499 ftr->keymaster_blob_size = 0;
500 }
501 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700502 return -1;
503 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000504 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700505}
506
Shawn Willdene17a9c42014-09-08 13:04:08 -0600507/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700508static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
509 const size_t object_size, unsigned char** signature,
510 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600511 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600512 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600513 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600514
Shawn Willdene17a9c42014-09-08 13:04:08 -0600515 // To sign a message with RSA, the message must satisfy two
516 // constraints:
517 //
518 // 1. The message, when interpreted as a big-endian numeric value, must
519 // be strictly less than the public modulus of the RSA key. Note
520 // that because the most significant bit of the public modulus is
521 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
522 // key), an n-bit message with most significant bit 0 always
523 // satisfies this requirement.
524 //
525 // 2. The message must have the same length in bits as the public
526 // modulus of the RSA key. This requirement isn't mathematically
527 // necessary, but is necessary to ensure consistency in
528 // implementations.
529 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600530 case KDF_SCRYPT_KEYMASTER:
531 // This ensures the most significant byte of the signed message
532 // is zero. We could have zero-padded to the left instead, but
533 // this approach is slightly more robust against changes in
534 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600535 // so) because we really should be using a proper deterministic
536 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800537 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600538 SLOGI("Signing safely-padded object");
539 break;
540 default:
541 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000542 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600543 }
Paul Crowley73473332017-11-21 15:43:51 -0800544 for (;;) {
545 auto result = keymaster_sign_object_for_cryptfs_scrypt(
546 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
547 to_sign_size, signature, signature_size);
548 switch (result) {
549 case KeymasterSignResult::ok:
550 return 0;
551 case KeymasterSignResult::upgrade:
552 break;
553 default:
554 return -1;
555 }
556 SLOGD("Upgrading key");
557 if (keymaster_upgrade_key_for_cryptfs_scrypt(
558 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
559 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
560 &ftr->keymaster_blob_size) != 0) {
561 SLOGE("Failed to upgrade key");
562 return -1;
563 }
564 if (put_crypt_ftr_and_key(ftr) != 0) {
565 SLOGE("Failed to write upgraded key to disk");
566 }
567 SLOGD("Key upgraded successfully");
568 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600569}
570
Paul Lawrence399317e2014-03-10 13:20:50 -0700571/* Store password when userdata is successfully decrypted and mounted.
572 * Cleared by cryptfs_clear_password
573 *
574 * To avoid a double prompt at boot, we need to store the CryptKeeper
575 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
576 * Since the entire framework is torn down and rebuilt after encryption,
577 * we have to use a daemon or similar to store the password. Since vold
578 * is secured against IPC except from system processes, it seems a reasonable
579 * place to store this.
580 *
581 * password should be cleared once it has been used.
582 *
583 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800584 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700585static char* password = 0;
586static int password_expiry_time = 0;
587static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800588
Paul Crowley14c8c072018-09-18 13:30:21 -0700589enum class RebootType { reboot, recovery, shutdown };
590static void cryptfs_reboot(RebootType rt) {
591 switch (rt) {
592 case RebootType::reboot:
593 property_set(ANDROID_RB_PROPERTY, "reboot");
594 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800595
Paul Crowley14c8c072018-09-18 13:30:21 -0700596 case RebootType::recovery:
597 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
598 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800599
Paul Crowley14c8c072018-09-18 13:30:21 -0700600 case RebootType::shutdown:
601 property_set(ANDROID_RB_PROPERTY, "shutdown");
602 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700603 }
Paul Lawrence87999172014-02-20 12:21:31 -0800604
Ken Sumralladfba362013-06-04 16:37:52 -0700605 sleep(20);
606
607 /* Shouldn't get here, reboot should happen before sleep times out */
608 return;
609}
610
Kenny Rootc4c70f12013-06-14 12:11:38 -0700611/**
612 * Gets the default device scrypt parameters for key derivation time tuning.
613 * The parameters should lead to about one second derivation time for the
614 * given device.
615 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700616static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700617 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000618 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700619
Paul Crowley63c18d32016-02-10 14:02:47 +0000620 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
621 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
622 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
623 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700624 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000625 ftr->N_factor = Nf;
626 ftr->r_factor = rf;
627 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700628}
629
Tom Cherry4c5bde22019-01-29 14:34:01 -0800630static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800631 int fd, block_size;
632 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200633 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800634
Paul Crowley14c8c072018-09-18 13:30:21 -0700635 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800636 SLOGE("Cannot open device to get filesystem size ");
637 return 0;
638 }
639
640 if (lseek64(fd, 1024, SEEK_SET) < 0) {
641 SLOGE("Cannot seek to superblock");
642 return 0;
643 }
644
645 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
646 SLOGE("Cannot read superblock");
647 return 0;
648 }
649
650 close(fd);
651
Daniel Rosenberge82df162014-08-15 22:19:23 +0000652 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
653 SLOGE("Not a valid ext4 superblock");
654 return 0;
655 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800656 block_size = 1024 << sb.s_log_block_size;
657 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200658 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800659
660 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200661 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800662}
663
Tom Cherry4c5bde22019-01-29 14:34:01 -0800664static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
665 for (const auto& entry : fstab_default) {
666 if (!entry.fs_mgr_flags.vold_managed &&
667 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
668 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
669 if (key_loc != nullptr) {
670 *key_loc = entry.key_loc;
671 }
672 if (real_blk_device != nullptr) {
673 *real_blk_device = entry.blk_device;
674 }
675 return;
676 }
677 }
678}
679
Paul Crowley14c8c072018-09-18 13:30:21 -0700680static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
681 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200682 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700683 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700684 char key_loc[PROPERTY_VALUE_MAX];
685 char real_blkdev[PROPERTY_VALUE_MAX];
686 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700687
Paul Crowley14c8c072018-09-18 13:30:21 -0700688 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800689 std::string key_loc;
690 std::string real_blkdev;
691 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700692
Tom Cherry4c5bde22019-01-29 14:34:01 -0800693 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200694 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700695 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
696 * encryption info footer and key, and plenty of bytes to spare for future
697 * growth.
698 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800699 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200700 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700701 cached_data = 1;
702 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800703 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700704 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700705 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800706 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700707 cached_off = 0;
708 cached_data = 1;
709 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700710 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700711
Paul Crowley14c8c072018-09-18 13:30:21 -0700712 if (cached_data) {
713 if (metadata_fname) {
714 *metadata_fname = cached_metadata_fname;
715 }
716 if (off) {
717 *off = cached_off;
718 }
719 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700720 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700721
Paul Crowley14c8c072018-09-18 13:30:21 -0700722 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723}
724
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800725/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700726static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800727 SHA256_CTX c;
728 SHA256_Init(&c);
729 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
730 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
731 SHA256_Final(crypt_ftr->sha256, &c);
732}
733
Ken Sumralle8744072011-01-18 22:01:55 -0800734/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800735 * update the failed mount count but not change the key.
736 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700737static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
738 int fd;
739 unsigned int cnt;
740 /* starting_off is set to the SEEK_SET offset
741 * where the crypto structure starts
742 */
743 off64_t starting_off;
744 int rc = -1;
745 char* fname = NULL;
746 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800747
Paul Crowley14c8c072018-09-18 13:30:21 -0700748 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800749
Paul Crowley14c8c072018-09-18 13:30:21 -0700750 if (get_crypt_ftr_info(&fname, &starting_off)) {
751 SLOGE("Unable to get crypt_ftr_info\n");
752 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800753 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700754 if (fname[0] != '/') {
755 SLOGE("Unexpected value for crypto key location\n");
756 return -1;
757 }
758 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
759 SLOGE("Cannot open footer file %s for put\n", fname);
760 return -1;
761 }
Ken Sumralle8744072011-01-18 22:01:55 -0800762
Paul Crowley14c8c072018-09-18 13:30:21 -0700763 /* Seek to the start of the crypt footer */
764 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
765 SLOGE("Cannot seek to real block device footer\n");
766 goto errout;
767 }
768
769 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
770 SLOGE("Cannot write real block device footer\n");
771 goto errout;
772 }
773
774 fstat(fd, &statbuf);
775 /* If the keys are kept on a raw block device, do not try to truncate it. */
776 if (S_ISREG(statbuf.st_mode)) {
777 if (ftruncate(fd, 0x4000)) {
778 SLOGE("Cannot set footer file size\n");
779 goto errout;
780 }
781 }
782
783 /* Success! */
784 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800785
786errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700787 close(fd);
788 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800789}
790
Paul Crowley14c8c072018-09-18 13:30:21 -0700791static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800792 struct crypt_mnt_ftr copy;
793 memcpy(&copy, crypt_ftr, sizeof(copy));
794 set_ftr_sha(&copy);
795 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
796}
797
Paul Crowley14c8c072018-09-18 13:30:21 -0700798static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700799 return TEMP_FAILURE_RETRY(read(fd, buff, len));
800}
801
Paul Crowley14c8c072018-09-18 13:30:21 -0700802static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700803 return TEMP_FAILURE_RETRY(write(fd, buff, len));
804}
805
Paul Crowley14c8c072018-09-18 13:30:21 -0700806static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700807 memset(pdata, 0, len);
808 pdata->persist_magic = PERSIST_DATA_MAGIC;
809 pdata->persist_valid_entries = 0;
810}
811
812/* A routine to update the passed in crypt_ftr to the lastest version.
813 * fd is open read/write on the device that holds the crypto footer and persistent
814 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
815 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
816 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700817static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700818 int orig_major = crypt_ftr->major_version;
819 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700820
Kenny Root7434b312013-06-14 11:29:53 -0700821 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700822 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700823 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700824
Kenny Rootc4c70f12013-06-14 12:11:38 -0700825 SLOGW("upgrading crypto footer to 1.1");
826
Paul Crowley14c8c072018-09-18 13:30:21 -0700827 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700828 if (pdata == NULL) {
829 SLOGE("Cannot allocate persisent data\n");
830 return;
831 }
832 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
833
834 /* Need to initialize the persistent data area */
835 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
836 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100837 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700838 return;
839 }
840 /* Write all zeros to the first copy, making it invalid */
841 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
842
843 /* Write a valid but empty structure to the second copy */
844 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
845 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
846
847 /* Update the footer */
848 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
849 crypt_ftr->persist_data_offset[0] = pdata_offset;
850 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
851 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100852 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700853 }
854
Paul Lawrencef4faa572014-01-29 13:31:03 -0800855 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700856 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800857 /* But keep the old kdf_type.
858 * It will get updated later to KDF_SCRYPT after the password has been verified.
859 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700860 crypt_ftr->kdf_type = KDF_PBKDF2;
861 get_device_scrypt_params(crypt_ftr);
862 crypt_ftr->minor_version = 2;
863 }
864
Paul Lawrencef4faa572014-01-29 13:31:03 -0800865 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
866 SLOGW("upgrading crypto footer to 1.3");
867 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
868 crypt_ftr->minor_version = 3;
869 }
870
Kenny Root7434b312013-06-14 11:29:53 -0700871 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
872 if (lseek64(fd, offset, SEEK_SET) == -1) {
873 SLOGE("Cannot seek to crypt footer\n");
874 return;
875 }
876 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700877 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700878}
879
Paul Crowley14c8c072018-09-18 13:30:21 -0700880static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
881 int fd;
882 unsigned int cnt;
883 off64_t starting_off;
884 int rc = -1;
885 char* fname = NULL;
886 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700887
Paul Crowley14c8c072018-09-18 13:30:21 -0700888 if (get_crypt_ftr_info(&fname, &starting_off)) {
889 SLOGE("Unable to get crypt_ftr_info\n");
890 return -1;
891 }
892 if (fname[0] != '/') {
893 SLOGE("Unexpected value for crypto key location\n");
894 return -1;
895 }
896 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
897 SLOGE("Cannot open footer file %s for get\n", fname);
898 return -1;
899 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800900
Paul Crowley14c8c072018-09-18 13:30:21 -0700901 /* Make sure it's 16 Kbytes in length */
902 fstat(fd, &statbuf);
903 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
904 SLOGE("footer file %s is not the expected size!\n", fname);
905 goto errout;
906 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700907
Paul Crowley14c8c072018-09-18 13:30:21 -0700908 /* Seek to the start of the crypt footer */
909 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
910 SLOGE("Cannot seek to real block device footer\n");
911 goto errout;
912 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700913
Paul Crowley14c8c072018-09-18 13:30:21 -0700914 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
915 SLOGE("Cannot read real block device footer\n");
916 goto errout;
917 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800918
Paul Crowley14c8c072018-09-18 13:30:21 -0700919 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
920 SLOGE("Bad magic for real block device %s\n", fname);
921 goto errout;
922 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800923
Paul Crowley14c8c072018-09-18 13:30:21 -0700924 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
925 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
926 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
927 goto errout;
928 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800929
Paul Crowley14c8c072018-09-18 13:30:21 -0700930 // We risk buffer overflows with oversized keys, so we just reject them.
931 // 0-sized keys are problematic (essentially by-passing encryption), and
932 // AES-CBC key wrapping only works for multiples of 16 bytes.
933 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
934 (crypt_ftr->keysize > MAX_KEY_LEN)) {
935 SLOGE(
936 "Invalid keysize (%u) for block device %s; Must be non-zero, "
937 "divisible by 16, and <= %d\n",
938 crypt_ftr->keysize, fname, MAX_KEY_LEN);
939 goto errout;
940 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941
Paul Crowley14c8c072018-09-18 13:30:21 -0700942 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
943 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
944 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
945 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800946
Paul Crowley14c8c072018-09-18 13:30:21 -0700947 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
948 * copy on disk before returning.
949 */
950 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
951 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
952 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953
Paul Crowley14c8c072018-09-18 13:30:21 -0700954 /* Success! */
955 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800956
957errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700958 close(fd);
959 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800960}
961
Paul Crowley14c8c072018-09-18 13:30:21 -0700962static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700963 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
964 crypt_ftr->persist_data_offset[1]) {
965 SLOGE("Crypt_ftr persist data regions overlap");
966 return -1;
967 }
968
969 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
970 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
971 return -1;
972 }
973
974 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700975 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700976 CRYPT_FOOTER_OFFSET) {
977 SLOGE("Persistent data extends past crypto footer");
978 return -1;
979 }
980
981 return 0;
982}
983
Paul Crowley14c8c072018-09-18 13:30:21 -0700984static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700985 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700986 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700987 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700988 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700989 int found = 0;
990 int fd;
991 int ret;
992 int i;
993
994 if (persist_data) {
995 /* Nothing to do, we've already loaded or initialized it */
996 return 0;
997 }
998
Ken Sumrall160b4d62013-04-22 12:15:39 -0700999 /* If not encrypted, just allocate an empty table and initialize it */
1000 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001001 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -08001002 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001003 if (pdata) {
1004 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1005 persist_data = pdata;
1006 return 0;
1007 }
1008 return -1;
1009 }
1010
Paul Crowley14c8c072018-09-18 13:30:21 -07001011 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001012 return -1;
1013 }
1014
Paul Crowley14c8c072018-09-18 13:30:21 -07001015 if ((crypt_ftr.major_version < 1) ||
1016 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001017 SLOGE("Crypt_ftr version doesn't support persistent data");
1018 return -1;
1019 }
1020
1021 if (get_crypt_ftr_info(&fname, NULL)) {
1022 return -1;
1023 }
1024
1025 ret = validate_persistent_data_storage(&crypt_ftr);
1026 if (ret) {
1027 return -1;
1028 }
1029
Paul Crowley14c8c072018-09-18 13:30:21 -07001030 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001031 if (fd < 0) {
1032 SLOGE("Cannot open %s metadata file", fname);
1033 return -1;
1034 }
1035
Wei Wang4375f1b2017-02-24 17:43:01 -08001036 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -08001037 if (pdata == NULL) {
1038 SLOGE("Cannot allocate memory for persistent data");
1039 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001040 }
1041
1042 for (i = 0; i < 2; i++) {
1043 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
1044 SLOGE("Cannot seek to read persistent data on %s", fname);
1045 goto err2;
1046 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001047 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001048 SLOGE("Error reading persistent data on iteration %d", i);
1049 goto err2;
1050 }
1051 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1052 found = 1;
1053 break;
1054 }
1055 }
1056
1057 if (!found) {
1058 SLOGI("Could not find valid persistent data, creating");
1059 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
1060 }
1061
1062 /* Success */
1063 persist_data = pdata;
1064 close(fd);
1065 return 0;
1066
1067err2:
1068 free(pdata);
1069
1070err:
1071 close(fd);
1072 return -1;
1073}
1074
Paul Crowley14c8c072018-09-18 13:30:21 -07001075static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001076 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001077 struct crypt_persist_data* pdata;
1078 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001079 off64_t write_offset;
1080 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001081 int fd;
1082 int ret;
1083
1084 if (persist_data == NULL) {
1085 SLOGE("No persistent data to save");
1086 return -1;
1087 }
1088
Paul Crowley14c8c072018-09-18 13:30:21 -07001089 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001090 return -1;
1091 }
1092
Paul Crowley14c8c072018-09-18 13:30:21 -07001093 if ((crypt_ftr.major_version < 1) ||
1094 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001095 SLOGE("Crypt_ftr version doesn't support persistent data");
1096 return -1;
1097 }
1098
1099 ret = validate_persistent_data_storage(&crypt_ftr);
1100 if (ret) {
1101 return -1;
1102 }
1103
1104 if (get_crypt_ftr_info(&fname, NULL)) {
1105 return -1;
1106 }
1107
Paul Crowley14c8c072018-09-18 13:30:21 -07001108 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001109 if (fd < 0) {
1110 SLOGE("Cannot open %s metadata file", fname);
1111 return -1;
1112 }
1113
Wei Wang4375f1b2017-02-24 17:43:01 -08001114 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001115 if (pdata == NULL) {
1116 SLOGE("Cannot allocate persistant data");
1117 goto err;
1118 }
1119
1120 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1121 SLOGE("Cannot seek to read persistent data on %s", fname);
1122 goto err2;
1123 }
1124
1125 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001126 SLOGE("Error reading persistent data before save");
1127 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001128 }
1129
1130 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1131 /* The first copy is the curent valid copy, so write to
1132 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001133 write_offset = crypt_ftr.persist_data_offset[1];
1134 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001135 } else {
1136 /* The second copy must be the valid copy, so write to
1137 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001138 write_offset = crypt_ftr.persist_data_offset[0];
1139 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001140 }
1141
1142 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001143 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001144 SLOGE("Cannot seek to write persistent data");
1145 goto err2;
1146 }
1147 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001148 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001149 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001150 SLOGE("Cannot seek to erase previous persistent data");
1151 goto err2;
1152 }
1153 fsync(fd);
1154 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001155 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001156 SLOGE("Cannot write to erase previous persistent data");
1157 goto err2;
1158 }
1159 fsync(fd);
1160 } else {
1161 SLOGE("Cannot write to save persistent data");
1162 goto err2;
1163 }
1164
1165 /* Success */
1166 free(pdata);
1167 close(fd);
1168 return 0;
1169
1170err2:
1171 free(pdata);
1172err:
1173 close(fd);
1174 return -1;
1175}
1176
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001177/* Convert a binary key of specified length into an ascii hex string equivalent,
1178 * without the leading 0x and with null termination
1179 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001180static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1181 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001182 unsigned int i, a;
1183 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001184
Paul Crowley14c8c072018-09-18 13:30:21 -07001185 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001186 /* For each byte, write out two ascii hex digits */
1187 nibble = (master_key[i] >> 4) & 0xf;
1188 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001189
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001190 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001191 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001192 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001193
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001194 /* Add the null termination */
1195 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001196}
1197
Eric Biggersed45ec32019-01-25 10:47:55 -08001198/*
1199 * If the ro.crypto.fde_sector_size system property is set, append the
1200 * parameters to make dm-crypt use the specified crypto sector size and round
1201 * the crypto device size down to a crypto sector boundary.
1202 */
David Andersonb9224732019-05-13 13:02:54 -07001203static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001204 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001205 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001206
Eric Biggersed45ec32019-01-25 10:47:55 -08001207 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1208 unsigned int sector_size;
1209
1210 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1211 (sector_size & (sector_size - 1)) != 0) {
1212 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1213 DM_CRYPT_SECTOR_SIZE, value);
1214 return -1;
1215 }
1216
David Andersonb9224732019-05-13 13:02:54 -07001217 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001218
1219 // With this option, IVs will match the sector numbering, instead
1220 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001221 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001222
1223 // Round the crypto device size down to a crypto sector boundary.
1224 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001225 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001226 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001227}
1228
Neeraj Soni73b46952019-09-12 16:47:27 +05301229#if defined(CONFIG_HW_DISK_ENCRYPTION) && !defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1230#define DM_CRYPT_BUF_SIZE 4096
1231
1232static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
1233 memset(io, 0, dataSize);
1234 io->data_size = dataSize;
1235 io->data_start = sizeof(struct dm_ioctl);
1236 io->version[0] = 4;
1237 io->version[1] = 0;
1238 io->version[2] = 0;
1239 io->flags = flags;
1240 if (name) {
1241 strlcpy(io->name, name, sizeof(io->name));
1242 }
1243}
1244
1245static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1246 const unsigned char* master_key, const char* real_blk_name,
1247 const char* name, int fd, const char* extra_params) {
1248 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1249 struct dm_ioctl* io;
1250 struct dm_target_spec* tgt;
1251 char* crypt_params;
1252 // We need two ASCII characters to represent each byte, and need space for
1253 // the '\0' terminator.
1254 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1255 size_t buff_offset;
1256 int i;
1257
1258 io = (struct dm_ioctl*)buffer;
1259
1260 /* Load the mapping table for this device */
1261 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
1262
1263 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1264 io->target_count = 1;
1265 tgt->status = 0;
1266 tgt->sector_start = 0;
1267 tgt->length = crypt_ftr->fs_size;
1268 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1269 buff_offset = crypt_params - buffer;
1270 SLOGI(
1271 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1272 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1273 extra_params);
1274 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1275 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1276 if (is_ice_enabled())
1277 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1278 else
1279 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1280 }
1281 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1282 crypt_ftr->crypto_type_name, master_key_ascii,
1283 real_blk_name, extra_params);
1284
1285 SLOGI("target_type = %s", tgt->target_type);
1286 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1287
1288 crypt_params += strlen(crypt_params) + 1;
1289 crypt_params =
1290 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1291 tgt->next = crypt_params - buffer;
1292
1293 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1294 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1295 break;
1296 }
1297 usleep(500000);
1298 }
1299
1300 if (i == TABLE_LOAD_RETRIES) {
1301 /* We failed to load the table, return an error */
1302 return -1;
1303 } else {
1304 return i + 1;
1305 }
1306}
1307
1308static int create_crypto_blk_dev_hw(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1309 const char* real_blk_name, char* crypto_blk_name, const char* name,
1310 uint32_t flags) {
1311 char buffer[DM_CRYPT_BUF_SIZE];
1312 struct dm_ioctl* io;
1313 unsigned int minor;
1314 int fd = 0;
1315 int err;
1316 int retval = -1;
1317 int version[3];
1318 int load_count;
1319 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1320 char progress[PROPERTY_VALUE_MAX] = {0};
1321 const char *extra_params;
1322
1323 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1324 SLOGE("Cannot open device-mapper\n");
1325 goto errout;
1326 }
1327
1328 io = (struct dm_ioctl*)buffer;
1329
1330 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1331 err = ioctl(fd, DM_DEV_CREATE, io);
1332 if (err) {
1333 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1334 goto errout;
1335 }
1336
1337 /* Get the device status, in particular, the name of it's device file */
1338 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1339 if (ioctl(fd, DM_DEV_STATUS, io)) {
1340 SLOGE("Cannot retrieve dm-crypt device status\n");
1341 goto errout;
1342 }
1343 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1344 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1345
1346 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1347 /* Set fde_enabled if either FDE completed or in-progress */
1348 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1349 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1350 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1351 if (is_ice_enabled()) {
1352 extra_params = "fde_enabled ice allow_encrypt_override";
1353 } else {
1354 extra_params = "fde_enabled allow_encrypt_override";
1355 }
1356 } else {
1357 extra_params = "fde_enabled allow_encrypt_override";
1358 }
1359 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1360 extra_params);
1361 }
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08001362
Neeraj Soni73b46952019-09-12 16:47:27 +05301363 if (load_count < 0) {
1364 SLOGE("Cannot load dm-crypt mapping table.\n");
1365 goto errout;
1366 } else if (load_count > 1) {
1367 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1368 }
1369
1370 /* Resume this device to activate it */
1371 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1372
1373 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1374 SLOGE("Cannot resume the dm-crypt device\n");
1375 goto errout;
1376 }
1377
1378 /* Ensure the dm device has been created before returning. */
1379 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1380 // WaitForFile generates a suitable log message
1381 goto errout;
1382 }
1383
1384 /* We made it here with no errors. Woot! */
1385 retval = 0;
1386
1387errout:
1388 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1389
1390 return retval;
1391}
1392#endif
1393
Paul Crowley5afbc622017-11-27 09:42:17 -08001394static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001395 const char* real_blk_name, std::string* crypto_blk_name,
1396 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001397 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001398
David Andersonb9224732019-05-13 13:02:54 -07001399 // We need two ASCII characters to represent each byte, and need space for
1400 // the '\0' terminator.
1401 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1402 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001403
David Andersonb9224732019-05-13 13:02:54 -07001404 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1405 (const char*)crypt_ftr->crypto_type_name,
1406 master_key_ascii, 0, real_blk_name, 0);
1407 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001408
Paul Crowley5afbc622017-11-27 09:42:17 -08001409 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001410 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001411 }
David Andersonb9224732019-05-13 13:02:54 -07001412 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001413 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001414 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001415 }
David Andersonb9224732019-05-13 13:02:54 -07001416
1417 DmTable table;
1418 table.AddTarget(std::move(target));
1419
1420 int load_count = 1;
1421 while (load_count < TABLE_LOAD_RETRIES) {
1422 if (dm.CreateDevice(name, table)) {
1423 break;
1424 }
1425 load_count++;
1426 }
1427
1428 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001429 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001430 return -1;
1431 }
1432 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001433 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1434 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435
Paul Crowley81796e92020-02-07 11:27:49 -08001436 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001437 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1438 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001439 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001440
Paul Crowley298fa322018-10-30 15:59:24 -07001441 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001442 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowley298fa322018-10-30 15:59:24 -07001443 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001444 return -1;
Paul Crowley298fa322018-10-30 15:59:24 -07001445 }
David Andersonb9224732019-05-13 13:02:54 -07001446 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001447}
1448
David Andersonb9224732019-05-13 13:02:54 -07001449static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001450 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001451 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001452 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1453 // to delete the device fails with EBUSY; for now, work around this by retrying.
1454 int tries = 5;
1455 while (tries-- > 0) {
1456 ret = dm.DeleteDevice(name);
1457 if (ret || errno != EBUSY) {
1458 break;
1459 }
1460 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1461 strerror(errno));
1462 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1463 }
1464 if (!ret) {
1465 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001466 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001467 }
David Andersonb9224732019-05-13 13:02:54 -07001468 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001469}
1470
Paul Crowley14c8c072018-09-18 13:30:21 -07001471static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1472 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001473 SLOGI("Using pbkdf2 for cryptfs KDF");
1474
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001475 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001476 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1477 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001478}
1479
Paul Crowley14c8c072018-09-18 13:30:21 -07001480static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001481 SLOGI("Using scrypt for cryptfs KDF");
1482
Paul Crowley14c8c072018-09-18 13:30:21 -07001483 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001484
1485 int N = 1 << ftr->N_factor;
1486 int r = 1 << ftr->r_factor;
1487 int p = 1 << ftr->p_factor;
1488
1489 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001490 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001491 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001492
Paul Crowley14c8c072018-09-18 13:30:21 -07001493 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001494}
1495
Paul Crowley14c8c072018-09-18 13:30:21 -07001496static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1497 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001498 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1499
1500 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001501 size_t signature_size;
1502 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001503 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001504
1505 int N = 1 << ftr->N_factor;
1506 int r = 1 << ftr->r_factor;
1507 int p = 1 << ftr->p_factor;
1508
Paul Crowley14c8c072018-09-18 13:30:21 -07001509 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001510 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001511
1512 if (rc) {
1513 SLOGE("scrypt failed");
1514 return -1;
1515 }
1516
Paul Crowley14c8c072018-09-18 13:30:21 -07001517 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001518 SLOGE("Signing failed");
1519 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001520 }
1521
Paul Crowley14c8c072018-09-18 13:30:21 -07001522 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1523 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001524 free(signature);
1525
1526 if (rc) {
1527 SLOGE("scrypt failed");
1528 return -1;
1529 }
1530
1531 return 0;
1532}
1533
Paul Crowley14c8c072018-09-18 13:30:21 -07001534static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1535 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001536 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1537 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001538 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001539 EVP_CIPHER_CTX e_ctx;
1540 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001541 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001542
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001543 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001544 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001545
1546 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001547 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001548 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001549 SLOGE("keymaster_create_key failed");
1550 return -1;
1551 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001552
Paul Crowley14c8c072018-09-18 13:30:21 -07001553 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1554 SLOGE("scrypt failed");
1555 return -1;
1556 }
1557 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001558
Paul Crowley14c8c072018-09-18 13:30:21 -07001559 case KDF_SCRYPT:
1560 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1561 SLOGE("scrypt failed");
1562 return -1;
1563 }
1564 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001565
Paul Crowley14c8c072018-09-18 13:30:21 -07001566 default:
1567 SLOGE("Invalid kdf_type");
1568 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001569 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001570
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001572 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001573 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1574 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001575 SLOGE("EVP_EncryptInit failed\n");
1576 return -1;
1577 }
1578 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001579
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001580 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001581 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1582 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583 SLOGE("EVP_EncryptUpdate failed\n");
1584 return -1;
1585 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001586 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587 SLOGE("EVP_EncryptFinal failed\n");
1588 return -1;
1589 }
1590
Greg Kaiser59ad0182018-02-16 13:01:36 -08001591 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001592 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1593 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001594 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001595
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001596 /* Store the scrypt of the intermediate key, so we can validate if it's a
1597 password error or mount error when things go wrong.
1598 Note there's no need to check for errors, since if this is incorrect, we
1599 simply won't wipe userdata, which is the correct default behavior
1600 */
1601 int N = 1 << crypt_ftr->N_factor;
1602 int r = 1 << crypt_ftr->r_factor;
1603 int p = 1 << crypt_ftr->p_factor;
1604
Paul Crowley14c8c072018-09-18 13:30:21 -07001605 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1606 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001607 sizeof(crypt_ftr->scrypted_intermediate_key));
1608
1609 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001610 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001611 }
1612
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001613 EVP_CIPHER_CTX_cleanup(&e_ctx);
1614
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001615 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616}
1617
Paul Crowley14c8c072018-09-18 13:30:21 -07001618static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1619 const unsigned char* encrypted_master_key, size_t keysize,
1620 unsigned char* decrypted_master_key, kdf_func kdf,
1621 void* kdf_params, unsigned char** intermediate_key,
1622 size_t* intermediate_key_size) {
1623 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1624 EVP_CIPHER_CTX d_ctx;
1625 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001626
Paul Crowley14c8c072018-09-18 13:30:21 -07001627 /* Turn the password into an intermediate key and IV that can decrypt the
1628 master key */
1629 if (kdf(passwd, salt, ikey, kdf_params)) {
1630 SLOGE("kdf failed");
1631 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001632 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001633
Paul Crowley14c8c072018-09-18 13:30:21 -07001634 /* Initialize the decryption engine */
1635 EVP_CIPHER_CTX_init(&d_ctx);
1636 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1637 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1638 return -1;
1639 }
1640 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1641 /* Decrypt the master key */
1642 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1643 keysize)) {
1644 return -1;
1645 }
1646 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1647 return -1;
1648 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001649
Paul Crowley14c8c072018-09-18 13:30:21 -07001650 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1651 return -1;
1652 }
1653
1654 /* Copy intermediate key if needed by params */
1655 if (intermediate_key && intermediate_key_size) {
1656 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1657 if (*intermediate_key) {
1658 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1659 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1660 }
1661 }
1662
1663 EVP_CIPHER_CTX_cleanup(&d_ctx);
1664
1665 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001666}
1667
Paul Crowley14c8c072018-09-18 13:30:21 -07001668static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001669 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001670 *kdf = scrypt_keymaster;
1671 *kdf_params = ftr;
1672 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001673 *kdf = scrypt;
1674 *kdf_params = ftr;
1675 } else {
1676 *kdf = pbkdf2;
1677 *kdf_params = NULL;
1678 }
1679}
1680
Paul Crowley14c8c072018-09-18 13:30:21 -07001681static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1682 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1683 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001684 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001685 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001686 int ret;
1687
1688 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001689 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1690 decrypted_master_key, kdf, kdf_params, intermediate_key,
1691 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001692 if (ret != 0) {
1693 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001694 }
1695
1696 return ret;
1697}
1698
Paul Crowley14c8c072018-09-18 13:30:21 -07001699static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1700 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001701 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001702
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001703 /* Get some random bits for a key and salt */
1704 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1705 return -1;
1706 }
1707 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1708 return -1;
1709 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001710
1711 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301712 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001713}
1714
Hyangseok Chae79b03ff2020-02-27 18:21:50 +09001715static void ensure_subdirectory_unmounted(const char *prefix) {
1716 std::vector<std::string> umount_points;
1717 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1718 if (!mnts) {
1719 SLOGW("could not read mount files");
1720 return;
1721 }
1722
1723 //Find sudirectory mount point
1724 mntent* mentry;
1725 std::string top_directory(prefix);
1726 if (!android::base::EndsWith(prefix, "/")) {
1727 top_directory = top_directory + "/";
1728 }
1729 while ((mentry = getmntent(mnts.get())) != nullptr) {
1730 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1731 continue;
1732 }
1733
1734 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1735 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1736 umount_points.push_back(mentry->mnt_dir);
1737 }
1738 }
1739
1740 //Sort by path length to umount longest path first
1741 std::sort(std::begin(umount_points), std::end(umount_points),
1742 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1743
1744 for (std::string& mount_point : umount_points) {
1745 umount(mount_point.c_str());
1746 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1747 }
1748}
1749
Paul Crowley73be12d2020-02-03 12:22:03 -08001750static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001751 int i, err, rc;
Hyangseok Chae79b03ff2020-02-27 18:21:50 +09001752
1753 // Subdirectory mount will cause a failure of umount.
1754 ensure_subdirectory_unmounted(mountpoint);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301755#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001756
1757 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001758 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001759 if (umount(mountpoint) == 0) {
1760 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001761 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001762
1763 if (errno == EINVAL) {
1764 /* EINVAL is returned if the directory is not a mountpoint,
1765 * i.e. there is no filesystem mounted there. So just get out.
1766 */
1767 break;
1768 }
1769
1770 err = errno;
1771
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301772 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001773 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301774 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001775 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001776 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301777 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001778 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001779 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001780 }
1781 }
1782
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301783 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001784 }
1785
1786 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001787 SLOGD("unmounting %s succeeded\n", mountpoint);
1788 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001789 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001790 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1791 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1792 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001793 }
1794
1795 return rc;
1796}
1797
Paul Crowley14c8c072018-09-18 13:30:21 -07001798static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001799 // NOTE: post_fs_data results in init calling back around to vold, so all
1800 // callers to this method must be async
1801
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001802 /* Do the prep of the /data filesystem */
1803 property_set("vold.post_fs_data_done", "0");
1804 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001805 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001806
Ken Sumrallc5872692013-05-14 15:26:31 -07001807 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001808 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001809 /* We timed out to prep /data in time. Continue wait. */
1810 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001811 }
Wei Wang42e38102017-06-07 10:46:12 -07001812 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001813}
1814
Paul Crowley14c8c072018-09-18 13:30:21 -07001815static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001816 // Mark the footer as bad
1817 struct crypt_mnt_ftr crypt_ftr;
1818 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1819 SLOGE("Failed to get crypto footer - panic");
1820 return;
1821 }
1822
1823 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1824 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1825 SLOGE("Failed to set crypto footer - panic");
1826 return;
1827 }
1828}
1829
Paul Crowley14c8c072018-09-18 13:30:21 -07001830static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001831 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001832 SLOGE("Failed to mount tmpfs on data - panic");
1833 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001834 }
1835
1836 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1837 SLOGE("Failed to trigger post fs data - panic");
1838 return;
1839 }
1840
1841 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1842 SLOGE("Failed to trigger restart min framework - panic");
1843 return;
1844 }
1845}
1846
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001847/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001848static int cryptfs_restart_internal(int restart_main) {
Yifan Hong804afe12019-02-07 12:56:47 -08001849 std::string crypto_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301850#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001851 std::string blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301852#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001853 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001854 static int restart_successful = 0;
1855
1856 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001857 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001858 SLOGE("Encrypted filesystem not validated, aborting");
1859 return -1;
1860 }
1861
1862 if (restart_successful) {
1863 SLOGE("System already restarted with encrypted disk, aborting");
1864 return -1;
1865 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001866
Paul Lawrencef4faa572014-01-29 13:31:03 -08001867 if (restart_main) {
1868 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001869 * start all services in one of these classes: core, early_hal, hal,
1870 * main and late_start. To get to the minimal UI for PIN entry, we
1871 * need to start core, early_hal, hal and main. When we want to
1872 * shutdown the framework again, we need to stop most of the services in
1873 * these classes, but only those services that were started after
1874 * /data was mounted. This excludes critical services like vold and
1875 * ueventd, which need to keep running. We could possible stop
1876 * even fewer services, but because we want services to pick up APEX
1877 * libraries from the real /data, restarting is better, as it makes
1878 * these devices consistent with FBE devices and lets them use the
1879 * most recent code.
1880 *
1881 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001882 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001883 * We then restart the class core, hal, main, and also the class
1884 * late_start.
1885 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001886 * At the moment, I've only put a few things in late_start that I know
1887 * are not needed to bring up the framework, and that also cause problems
1888 * with unmounting the tmpfs /data, but I hope to add add more services
1889 * to the late_start class as we optimize this to decrease the delay
1890 * till the user is asked for the password to the filesystem.
1891 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001892
Martijn Coenenf629b002019-04-24 10:41:11 +02001893 /* The init files are setup to stop the right set of services when
1894 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001895 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001896 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001897 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001898
Paul Lawrencef4faa572014-01-29 13:31:03 -08001899 /* Ugh, shutting down the framework is not synchronous, so until it
1900 * can be fixed, this horrible hack will wait a moment for it all to
1901 * shut down before proceeding. Without it, some devices cannot
1902 * restart the graphics services.
1903 */
1904 sleep(2);
1905 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001906
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001907 /* Now that the framework is shutdown, we should be able to umount()
1908 * the tmpfs filesystem, and mount the real one.
1909 */
1910
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301911#if defined(CONFIG_HW_DISK_ENCRYPTION)
1912#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1913 if (is_ice_enabled()) {
Yifan Hong804afe12019-02-07 12:56:47 -08001914 get_crypt_info(nullptr, &blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301915 if (set_ice_param(START_ENCDEC)) {
1916 SLOGE("Failed to set ICE data");
1917 return -1;
1918 }
1919 }
1920#else
Yifan Hong804afe12019-02-07 12:56:47 -08001921 blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1922 if (blkdev.empty()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301923 SLOGE("fs_crypto_blkdev not set\n");
1924 return -1;
1925 }
1926 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1927#endif
1928#else
Yifan Hong804afe12019-02-07 12:56:47 -08001929 crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1930 if (crypto_blkdev.empty()) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001931 SLOGE("fs_crypto_blkdev not set\n");
1932 return -1;
1933 }
1934
Paul Crowley14c8c072018-09-18 13:30:21 -07001935 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301936#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001937 /* If ro.crypto.readonly is set to 1, mount the decrypted
1938 * filesystem readonly. This is used when /data is mounted by
1939 * recovery mode.
1940 */
1941 char ro_prop[PROPERTY_VALUE_MAX];
1942 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001943 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001944 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1945 if (entry != nullptr) {
1946 entry->flags |= MS_RDONLY;
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001947 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001948 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001949
Ken Sumralle5032c42012-04-01 23:58:44 -07001950 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001951 int retries = RETRY_MOUNT_ATTEMPTS;
1952 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001953
1954 /*
1955 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1956 * partitions in the fsck domain.
1957 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001958 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001959 SLOGE("Failed to setexeccon");
1960 return -1;
1961 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001962 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301963#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001964 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev.data(), 0,
Paul Lawrence67f90442020-06-12 08:12:48 -07001965 needs_cp, false)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301966#else
Yifan Hong804afe12019-02-07 12:56:47 -08001967 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev.data(), 0,
Steven Laver60b2b8d2020-06-19 08:37:05 -07001968 needs_cp, false)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301969#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001970 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1971 /* TODO: invoke something similar to
1972 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1973 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301974#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001975 SLOGI("Failed to mount %s because it is busy - waiting", blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301976#else
Yifan Hong804afe12019-02-07 12:56:47 -08001977 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301978#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001979 if (--retries) {
1980 sleep(RETRY_MOUNT_DELAY_SECONDS);
1981 } else {
1982 /* Let's hope that a reboot clears away whatever is keeping
1983 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001984 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001985 }
1986 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301987#ifdef CONFIG_HW_DISK_ENCRYPTION
1988 if (--retries) {
1989 sleep(RETRY_MOUNT_DELAY_SECONDS);
1990 } else {
1991 SLOGE("Failed to mount decrypted data");
1992 cryptfs_set_corrupt();
1993 cryptfs_trigger_restart_min_framework();
1994 SLOGI("Started framework to offer wipe");
1995 return -1;
1996 }
1997#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001998 SLOGE("Failed to mount decrypted data");
1999 cryptfs_set_corrupt();
2000 cryptfs_trigger_restart_min_framework();
2001 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002002 if (setexeccon(NULL)) {
2003 SLOGE("Failed to setexeccon");
2004 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002005 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302006#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002007 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002008 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002009 if (setexeccon(NULL)) {
2010 SLOGE("Failed to setexeccon");
2011 return -1;
2012 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002013
Ken Sumralle5032c42012-04-01 23:58:44 -07002014 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002015 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09002016 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07002017
2018 /* startup service classes main and late_start */
2019 property_set("vold.decrypt", "trigger_restart_framework");
2020 SLOGD("Just triggered restart_framework\n");
2021
2022 /* Give it a few moments to get started */
2023 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302024#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002025 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302026#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002027
Ken Sumrall0cc16632011-01-18 20:32:26 -08002028 if (rc == 0) {
2029 restart_successful = 1;
2030 }
2031
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002032 return rc;
2033}
2034
Paul Crowley14c8c072018-09-18 13:30:21 -07002035int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002036 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07002037 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002038 SLOGE("cryptfs_restart not valid for file encryption:");
2039 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002040 }
2041
Paul Lawrencef4faa572014-01-29 13:31:03 -08002042 /* Call internal implementation forcing a restart of main service group */
2043 return cryptfs_restart_internal(1);
2044}
2045
Paul Crowley14c8c072018-09-18 13:30:21 -07002046static int do_crypto_complete(const char* mount_point) {
2047 struct crypt_mnt_ftr crypt_ftr;
2048 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002049
Paul Crowley14c8c072018-09-18 13:30:21 -07002050 property_get("ro.crypto.state", encrypted_state, "");
2051 if (strcmp(encrypted_state, "encrypted")) {
2052 SLOGE("not running with encryption, aborting");
2053 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08002054 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002055
Paul Crowley14c8c072018-09-18 13:30:21 -07002056 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07002057 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002058 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2059 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002060
Paul Crowley14c8c072018-09-18 13:30:21 -07002061 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002062 std::string key_loc;
2063 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002064
Paul Crowley14c8c072018-09-18 13:30:21 -07002065 /*
2066 * Only report this error if key_loc is a file and it exists.
2067 * If the device was never encrypted, and /data is not mountable for
2068 * some reason, returning 1 should prevent the UI from presenting the
2069 * a "enter password" screen, or worse, a "press button to wipe the
2070 * device" screen.
2071 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002072 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002073 SLOGE("master key file does not exist, aborting");
2074 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2075 } else {
2076 SLOGE("Error getting crypt footer and key\n");
2077 return CRYPTO_COMPLETE_BAD_METADATA;
2078 }
2079 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002080
Paul Crowley14c8c072018-09-18 13:30:21 -07002081 // Test for possible error flags
2082 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2083 SLOGE("Encryption process is partway completed\n");
2084 return CRYPTO_COMPLETE_PARTIAL;
2085 }
2086
2087 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2088 SLOGE("Encryption process was interrupted but cannot continue\n");
2089 return CRYPTO_COMPLETE_INCONSISTENT;
2090 }
2091
2092 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
2093 SLOGE("Encryption is successful but data is corrupt\n");
2094 return CRYPTO_COMPLETE_CORRUPT;
2095 }
2096
2097 /* We passed the test! We shall diminish, and return to the west */
2098 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002099}
2100
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302101#ifdef CONFIG_HW_DISK_ENCRYPTION
2102static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2103 const char *passwd, const char *mount_point, const char *label)
2104{
Bill Peckham0db11972018-10-10 10:25:42 -07002105 /* Allocate enough space for a 256 bit key, but we may use less */
2106 unsigned char decrypted_master_key[32];
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002107 char crypto_blkdev_hw[MAXPATHLEN];
2108 std::string crypto_blkdev;
Yifan Hong804afe12019-02-07 12:56:47 -08002109 std::string real_blkdev;
Bill Peckham0db11972018-10-10 10:25:42 -07002110 unsigned int orig_failed_decrypt_count;
2111 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302112
Bill Peckham0db11972018-10-10 10:25:42 -07002113 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2114 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302115
Yifan Hong804afe12019-02-07 12:56:47 -08002116 get_crypt_info(nullptr, &real_blkdev);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302117
Bill Peckham0db11972018-10-10 10:25:42 -07002118 int key_index = 0;
2119 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2120 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2121 if (key_index < 0) {
2122 rc = crypt_ftr->failed_decrypt_count;
2123 goto errout;
2124 }
2125 else {
2126 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302127#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Neeraj Soni73b46952019-09-12 16:47:27 +05302128 if (create_crypto_blk_dev_hw(crypt_ftr, (unsigned char*)&key_index,
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002129 real_blkdev.c_str(), crypto_blkdev_hw, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002130 SLOGE("Error creating decrypted block device");
2131 rc = -1;
2132 goto errout;
2133 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302134#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002135 } else {
2136 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002137 real_blkdev.c_str(), &crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002138 SLOGE("Error creating decrypted block device");
2139 rc = -1;
2140 goto errout;
2141 }
2142 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302143 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302144 }
2145
Bill Peckham0db11972018-10-10 10:25:42 -07002146 if (rc == 0) {
2147 crypt_ftr->failed_decrypt_count = 0;
2148 if (orig_failed_decrypt_count != 0) {
2149 put_crypt_ftr_and_key(crypt_ftr);
2150 }
2151
2152 /* Save the name of the crypto block device
2153 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302154#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002155 if (!is_ice_enabled())
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002156 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev_hw);
2157#else
Bill Peckham0db11972018-10-10 10:25:42 -07002158 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002159#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002160 master_key_saved = 1;
2161 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302162
Bill Peckham0db11972018-10-10 10:25:42 -07002163 errout:
2164 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302165}
2166#endif
2167
Paul Crowley14c8c072018-09-18 13:30:21 -07002168static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2169 const char* mount_point, const char* label) {
2170 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08002171 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002172 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002173 char tmp_mount_point[64];
2174 unsigned int orig_failed_decrypt_count;
2175 int rc;
2176 int use_keymaster = 0;
2177 int upgrade = 0;
2178 unsigned char* intermediate_key = 0;
2179 size_t intermediate_key_size = 0;
2180 int N = 1 << crypt_ftr->N_factor;
2181 int r = 1 << crypt_ftr->r_factor;
2182 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302183
Paul Crowley14c8c072018-09-18 13:30:21 -07002184 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2185 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002186
Paul Crowley14c8c072018-09-18 13:30:21 -07002187 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2188 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2189 &intermediate_key_size)) {
2190 SLOGE("Failed to decrypt master key\n");
2191 rc = -1;
2192 goto errout;
2193 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002194 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002195
Tom Cherry4c5bde22019-01-29 14:34:01 -08002196 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002197
Paul Crowley14c8c072018-09-18 13:30:21 -07002198 // Create crypto block device - all (non fatal) code paths
2199 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08002200 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08002201 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002202 SLOGE("Error creating decrypted block device\n");
2203 rc = -1;
2204 goto errout;
2205 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002206
Paul Crowley14c8c072018-09-18 13:30:21 -07002207 /* Work out if the problem is the password or the data */
2208 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002209
Paul Crowley14c8c072018-09-18 13:30:21 -07002210 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2211 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2212 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002213
Paul Crowley14c8c072018-09-18 13:30:21 -07002214 // Does the key match the crypto footer?
2215 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2216 sizeof(scrypted_intermediate_key)) == 0) {
2217 SLOGI("Password matches");
2218 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002219 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002220 /* Try mounting the file system anyway, just in case the problem's with
2221 * the footer, not the key. */
2222 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2223 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08002224 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
2225 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002226 SLOGE("Error temp mounting decrypted block device\n");
2227 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002228
Paul Crowley14c8c072018-09-18 13:30:21 -07002229 rc = ++crypt_ftr->failed_decrypt_count;
2230 put_crypt_ftr_and_key(crypt_ftr);
2231 } else {
2232 /* Success! */
2233 SLOGI("Password did not match but decrypted drive mounted - continue");
2234 umount(tmp_mount_point);
2235 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002236 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002237 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002238
Paul Crowley14c8c072018-09-18 13:30:21 -07002239 if (rc == 0) {
2240 crypt_ftr->failed_decrypt_count = 0;
2241 if (orig_failed_decrypt_count != 0) {
2242 put_crypt_ftr_and_key(crypt_ftr);
2243 }
2244
2245 /* Save the name of the crypto block device
2246 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08002247 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07002248
2249 /* Also save a the master key so we can reencrypted the key
2250 * the key when we want to change the password on it. */
2251 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2252 saved_mount_point = strdup(mount_point);
2253 master_key_saved = 1;
2254 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2255 rc = 0;
2256
2257 // Upgrade if we're not using the latest KDF.
2258 use_keymaster = keymaster_check_compatibility();
2259 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2260 // Don't allow downgrade
2261 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2262 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2263 upgrade = 1;
2264 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2265 crypt_ftr->kdf_type = KDF_SCRYPT;
2266 upgrade = 1;
2267 }
2268
2269 if (upgrade) {
2270 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002271 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002272 if (!rc) {
2273 rc = put_crypt_ftr_and_key(crypt_ftr);
2274 }
2275 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2276
2277 // Do not fail even if upgrade failed - machine is bootable
2278 // Note that if this code is ever hit, there is a *serious* problem
2279 // since KDFs should never fail. You *must* fix the kdf before
2280 // proceeding!
2281 if (rc) {
2282 SLOGW(
2283 "Upgrade failed with error %d,"
2284 " but continuing with previous state",
2285 rc);
2286 rc = 0;
2287 }
2288 }
2289 }
2290
2291errout:
2292 if (intermediate_key) {
2293 memset(intermediate_key, 0, intermediate_key_size);
2294 free(intermediate_key);
2295 }
2296 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002297}
2298
Ken Sumrall29d8da82011-05-18 17:20:07 -07002299/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002300 * Called by vold when it's asked to mount an encrypted external
2301 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002302 * as any metadata is been stored in a separate, small partition. We
2303 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002304 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002305int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08002306 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08002307 auto crypto_type = get_crypto_type();
2308 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08002309 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08002310 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002311 return -1;
2312 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002313 uint64_t nr_sec = 0;
2314 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002315 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002316 return -1;
2317 }
2318
Jeff Sharkey9c484982015-03-31 10:35:33 -07002319 struct crypt_mnt_ftr ext_crypt_ftr;
2320 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2321 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08002322 ext_crypt_ftr.keysize = crypto_type.get_keysize();
2323 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002324 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002325 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002326 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002327 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2328 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002329
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002330 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
2331 real_blkdev, out_crypto_blkdev, label, flags);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002332}
2333
Paul Crowley14c8c072018-09-18 13:30:21 -07002334int cryptfs_crypto_complete(void) {
2335 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002336}
2337
Paul Crowley14c8c072018-09-18 13:30:21 -07002338int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002339 char encrypted_state[PROPERTY_VALUE_MAX];
2340 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002341 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2342 SLOGE(
2343 "encrypted fs already validated or not running with encryption,"
2344 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002345 return -1;
2346 }
2347
2348 if (get_crypt_ftr_and_key(crypt_ftr)) {
2349 SLOGE("Error getting crypt footer and key");
2350 return -1;
2351 }
2352
2353 return 0;
2354}
2355
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302356#ifdef CONFIG_HW_DISK_ENCRYPTION
2357int cryptfs_check_passwd_hw(const char* passwd)
2358{
2359 struct crypt_mnt_ftr crypt_ftr;
2360 int rc;
2361 unsigned char master_key[KEY_LEN_BYTES];
2362
2363 /* get key */
2364 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2365 SLOGE("Error getting crypt footer and key");
2366 return -1;
2367 }
2368
2369 /*
2370 * in case of manual encryption (from GUI), the encryption is done with
2371 * default password
2372 */
2373 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2374 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2375 * which was created with actual password before reboot.
2376 */
2377 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2378 if (rc) {
2379 SLOGE("password doesn't match");
2380 rc = ++crypt_ftr.failed_decrypt_count;
2381 put_crypt_ftr_and_key(&crypt_ftr);
2382 return rc;
2383 }
2384
2385 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2386 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2387
2388 if (rc) {
2389 SLOGE("Default password did not match on reboot encryption");
2390 return rc;
2391 }
2392
2393 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2394 put_crypt_ftr_and_key(&crypt_ftr);
2395 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2396 if (rc) {
2397 SLOGE("Could not change password on reboot encryption");
2398 return rc;
2399 }
2400 } else
2401 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2402 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2403
2404 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2405 cryptfs_clear_password();
2406 password = strdup(passwd);
2407 struct timespec now;
2408 clock_gettime(CLOCK_BOOTTIME, &now);
2409 password_expiry_time = now.tv_sec + password_max_age_seconds;
2410 }
2411
2412 return rc;
2413}
2414#endif
2415
Paul Crowley14c8c072018-09-18 13:30:21 -07002416int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002417 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002418 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002419 SLOGE("cryptfs_check_passwd not valid for file encryption");
2420 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002421 }
2422
Paul Lawrencef4faa572014-01-29 13:31:03 -08002423 struct crypt_mnt_ftr crypt_ftr;
2424 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002425
Paul Lawrencef4faa572014-01-29 13:31:03 -08002426 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002427 if (rc) {
2428 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002429 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002430 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002431
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302432#ifdef CONFIG_HW_DISK_ENCRYPTION
2433 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2434 return cryptfs_check_passwd_hw(passwd);
2435#endif
2436
Paul Crowley14c8c072018-09-18 13:30:21 -07002437 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002438 if (rc) {
2439 SLOGE("Password did not match");
2440 return rc;
2441 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002442
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002443 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2444 // Here we have a default actual password but a real password
2445 // we must test against the scrypted value
2446 // First, we must delete the crypto block device that
2447 // test_mount_encrypted_fs leaves behind as a side effect
2448 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002449 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2450 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002451 if (rc) {
2452 SLOGE("Default password did not match on reboot encryption");
2453 return rc;
2454 }
2455
2456 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2457 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302458 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002459 if (rc) {
2460 SLOGE("Could not change password on reboot encryption");
2461 return rc;
2462 }
2463 }
2464
2465 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002466 cryptfs_clear_password();
2467 password = strdup(passwd);
2468 struct timespec now;
2469 clock_gettime(CLOCK_BOOTTIME, &now);
2470 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002471 }
2472
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002473 return rc;
2474}
2475
Paul Crowley14c8c072018-09-18 13:30:21 -07002476int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002477 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002478 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002479 char encrypted_state[PROPERTY_VALUE_MAX];
2480 int rc;
2481
2482 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002483 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002484 SLOGE("device not encrypted, aborting");
2485 return -2;
2486 }
2487
2488 if (!master_key_saved) {
2489 SLOGE("encrypted fs not yet mounted, aborting");
2490 return -1;
2491 }
2492
2493 if (!saved_mount_point) {
2494 SLOGE("encrypted fs failed to save mount point, aborting");
2495 return -1;
2496 }
2497
Ken Sumrall160b4d62013-04-22 12:15:39 -07002498 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002499 SLOGE("Error getting crypt footer and key\n");
2500 return -1;
2501 }
2502
2503 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2504 /* If the device has no password, then just say the password is valid */
2505 rc = 0;
2506 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302507#ifdef CONFIG_HW_DISK_ENCRYPTION
2508 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2509 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2510 rc = 0;
2511 else
2512 rc = -1;
2513 } else {
2514 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2515 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2516 /* They match, the password is correct */
2517 rc = 0;
2518 } else {
2519 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2520 sleep(1);
2521 rc = 1;
2522 }
2523 }
2524#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002525 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002526 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2527 /* They match, the password is correct */
2528 rc = 0;
2529 } else {
2530 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2531 sleep(1);
2532 rc = 1;
2533 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302534#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002535 }
2536
2537 return rc;
2538}
2539
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002540/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002541 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002542 * Presumably, at a minimum, the caller will update the
2543 * filesystem size and crypto_type_name after calling this function.
2544 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002545static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002546 off64_t off;
2547
2548 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002549 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002550 ftr->major_version = CURRENT_MAJOR_VERSION;
2551 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002552 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002553 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002554
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002555 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002556 case 1:
2557 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2558 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002559
Paul Crowley14c8c072018-09-18 13:30:21 -07002560 case 0:
2561 ftr->kdf_type = KDF_SCRYPT;
2562 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002563
Paul Crowley14c8c072018-09-18 13:30:21 -07002564 default:
2565 SLOGE("keymaster_check_compatibility failed");
2566 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002567 }
2568
Kenny Rootc4c70f12013-06-14 12:11:38 -07002569 get_device_scrypt_params(ftr);
2570
Ken Sumrall160b4d62013-04-22 12:15:39 -07002571 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2572 if (get_crypt_ftr_info(NULL, &off) == 0) {
2573 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002574 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002575 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002576
2577 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002578}
2579
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002580#define FRAMEWORK_BOOT_WAIT 60
2581
Paul Crowleyb64933a2017-10-31 08:25:55 -07002582static int vold_unmountAll(void) {
2583 VolumeManager* vm = VolumeManager::Instance();
2584 return vm->unmountAll();
2585}
2586
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002587int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002588 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002589 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002590 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002591 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002592 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002593 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002594 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002595 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002596 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002597 int num_vols;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002598 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002599 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302600#ifdef CONFIG_HW_DISK_ENCRYPTION
2601 unsigned char newpw[32];
2602 int key_index = 0;
2603#endif
2604 int index = 0;
Tri Vo15bbe222019-06-21 12:21:48 -07002605 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302606
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002607 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Eric Biggersc01995e2020-11-03 14:11:00 -08002608 if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002609 if (!check_ftr_sha(&crypt_ftr)) {
2610 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2611 put_crypt_ftr_and_key(&crypt_ftr);
2612 goto error_unencrypted;
2613 }
2614
2615 /* Doing a reboot-encryption*/
2616 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2617 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2618 rebootEncryption = true;
2619 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002620 } else {
2621 // We don't want to accidentally reference invalid data.
2622 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002623 }
2624
2625 property_get("ro.crypto.state", encrypted_state, "");
Eric Biggersc01995e2020-11-03 14:11:00 -08002626 if (!strcmp(encrypted_state, "encrypted")) {
Paul Lawrence87999172014-02-20 12:21:31 -08002627 SLOGE("Device is already running encrypted, aborting");
2628 goto error_unencrypted;
2629 }
2630
Tom Cherry4c5bde22019-01-29 14:34:01 -08002631 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002632
Ken Sumrall3ed82362011-01-28 23:31:16 -08002633 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002634 uint64_t nr_sec;
2635 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002636 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002637 goto error_unencrypted;
2638 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002639
2640 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002641 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002642 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002643 fs_size_sec = get_fs_size(real_blkdev.c_str());
2644 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002645
Paul Lawrence87999172014-02-20 12:21:31 -08002646 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002647
2648 if (fs_size_sec > max_fs_size_sec) {
2649 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2650 goto error_unencrypted;
2651 }
2652 }
2653
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002654 /* Get a wakelock as this may take a while, and we don't want the
2655 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2656 * wants to keep the screen on, it can grab a full wakelock.
2657 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002658 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002659 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002660
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002661 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002662 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002663 */
2664 property_set("vold.decrypt", "trigger_shutdown_framework");
2665 SLOGD("Just asked init to shut down class main\n");
2666
Jeff Sharkey9c484982015-03-31 10:35:33 -07002667 /* Ask vold to unmount all devices that it manages */
2668 if (vold_unmountAll()) {
2669 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002670 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002671
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002672 /* no_ui means we are being called from init, not settings.
2673 Now we always reboot from settings, so !no_ui means reboot
2674 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002675 if (!no_ui) {
2676 /* Try fallback, which is to reboot and try there */
2677 onlyCreateHeader = true;
2678 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2679 if (breadcrumb == 0) {
2680 SLOGE("Failed to create breadcrumb file");
2681 goto error_shutting_down;
2682 }
2683 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002684 }
2685
2686 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002687 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002688 /* Now that /data is unmounted, we need to mount a tmpfs
2689 * /data, set a property saying we're doing inplace encryption,
2690 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002691 */
xzj7e38a3a2018-10-12 10:17:11 +08002692 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002693 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002694 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002695 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002696 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002697 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002698
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002699 /* restart the framework. */
2700 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002701 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002702
Ken Sumrall92736ef2012-10-17 20:57:14 -07002703 /* Ugh, shutting down the framework is not synchronous, so until it
2704 * can be fixed, this horrible hack will wait a moment for it all to
2705 * shut down before proceeding. Without it, some devices cannot
2706 * restart the graphics services.
2707 */
2708 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002709 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002710
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002711 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002712 /* Initialize a crypt_mnt_ftr for the partition */
Eric Biggersc01995e2020-11-03 14:11:00 -08002713 if (!rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002714 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2715 goto error_shutting_down;
2716 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002717
Tom Cherry4c5bde22019-01-29 14:34:01 -08002718 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002719 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002720 } else {
2721 crypt_ftr.fs_size = nr_sec;
2722 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002723 /* At this point, we are in an inconsistent state. Until we successfully
2724 complete encryption, a reboot will leave us broken. So mark the
2725 encryption failed in case that happens.
2726 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002727 if (onlyCreateHeader) {
2728 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2729 } else {
2730 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2731 }
Paul Lawrence87999172014-02-20 12:21:31 -08002732 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302733#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002734 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2735 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302736#else
Paul Crowley220567c2020-02-07 12:45:20 -08002737 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002738 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302739#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002740
Paul Lawrence87999172014-02-20 12:21:31 -08002741 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002742 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2743 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002744 SLOGE("Cannot create encrypted master key\n");
2745 goto error_shutting_down;
2746 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002747
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002748 /* Replace scrypted intermediate key if we are preparing for a reboot */
2749 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002750 unsigned char fake_master_key[MAX_KEY_LEN];
2751 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002752 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002753 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002754 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002755 }
2756
Paul Lawrence87999172014-02-20 12:21:31 -08002757 /* Write the key to the end of the partition */
2758 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002759
Paul Lawrence87999172014-02-20 12:21:31 -08002760 /* If any persistent data has been remembered, save it.
2761 * If none, create a valid empty table and save that.
2762 */
2763 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002764 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2765 if (pdata) {
2766 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2767 persist_data = pdata;
2768 }
Paul Lawrence87999172014-02-20 12:21:31 -08002769 }
2770 if (persist_data) {
2771 save_persistent_data();
2772 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002773 }
2774
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302775 /* When encryption triggered from settings, encryption starts after reboot.
2776 So set the encryption key when the actual encryption starts.
2777 */
2778#ifdef CONFIG_HW_DISK_ENCRYPTION
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002779 if (!rebootEncryption)
2780 clear_hw_device_encryption_key();
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302781
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002782 if (get_keymaster_hw_fde_passwd(
2783 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2784 newpw, crypt_ftr.salt, &crypt_ftr))
2785 key_index = set_hw_device_encryption_key(
2786 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2787 (char*)crypt_ftr.crypto_type_name);
2788 else
2789 key_index = set_hw_device_encryption_key((const char*)newpw,
2790 (char*) crypt_ftr.crypto_type_name);
2791 if (key_index < 0)
2792 goto error_shutting_down;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302793
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002794 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2795 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302796#endif
2797
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002798 if (onlyCreateHeader) {
2799 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002800 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302801 } else {
2802 /* Do extra work for a better UX when doing the long inplace encryption */
2803 /* Now that /data is unmounted, we need to mount a tmpfs
2804 * /data, set a property saying we're doing inplace encryption,
2805 * and restart the framework.
2806 */
2807 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2808 goto error_shutting_down;
2809 }
2810 /* Tells the framework that inplace encryption is starting */
2811 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002812
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302813 /* restart the framework. */
2814 /* Create necessary paths on /data */
2815 prep_data_fs();
2816
2817 /* Ugh, shutting down the framework is not synchronous, so until it
2818 * can be fixed, this horrible hack will wait a moment for it all to
2819 * shut down before proceeding. Without it, some devices cannot
2820 * restart the graphics services.
2821 */
2822 sleep(2);
2823
Ajay Dudani87701e22014-09-17 21:02:52 -07002824 /* startup service classes main and late_start */
2825 property_set("vold.decrypt", "trigger_restart_min_framework");
2826 SLOGD("Just triggered restart_min_framework\n");
2827
2828 /* OK, the framework is restarted and will soon be showing a
2829 * progress bar. Time to setup an encrypted mapping, and
2830 * either write a new filesystem, or encrypt in place updating
2831 * the progress bar as we work.
2832 */
2833 }
2834
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002835 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302836#ifdef CONFIG_HW_DISK_ENCRYPTION
2837 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302838#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002839 crypto_blkdev = real_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302840#else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002841 create_crypto_blk_dev_hw(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302842 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302843#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302844 else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002845 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302846 CRYPTO_BLOCK_DEVICE, 0);
2847#else
Paul Crowley81796e92020-02-07 11:27:49 -08002848 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002849 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302850#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002851
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302852#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2853 if (set_ice_param(START_ENC)) {
2854 SLOGE("Failed to set ICE data");
2855 goto error_shutting_down;
2856 }
2857#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002858 if (!rc) {
Eric Biggersf038c5f2020-11-03 14:11:02 -08002859 if (encrypt_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size, true)) {
2860 crypt_ftr.encrypted_upto = crypt_ftr.fs_size;
2861 rc = 0;
2862 } else {
Paul Lawrence87999172014-02-20 12:21:31 -08002863 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002864 }
Eric Biggers88f993b2020-11-03 14:11:00 -08002865 /* Undo the dm-crypt mapping whether we succeed or not */
2866 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002867 }
2868
Paul Crowley14c8c072018-09-18 13:30:21 -07002869 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002870 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002871 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002872
Paul Lawrence6bfed202014-07-28 12:47:22 -07002873 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002874
Eric Biggersc01995e2020-11-03 14:11:00 -08002875 char value[PROPERTY_VALUE_MAX];
2876 property_get("ro.crypto.state", value, "");
2877 if (!strcmp(value, "")) {
2878 /* default encryption - continue first boot sequence */
2879 property_set("ro.crypto.state", "encrypted");
2880 property_set("ro.crypto.type", "block");
2881 wakeLock.reset(nullptr);
2882 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2883 // Bring up cryptkeeper that will check the password and set it
2884 property_set("vold.decrypt", "trigger_shutdown_framework");
2885 sleep(2);
2886 property_set("vold.encrypt_progress", "");
2887 cryptfs_trigger_restart_min_framework();
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002888 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002889 cryptfs_check_passwd(DEFAULT_PASSWORD);
2890 cryptfs_restart_internal(1);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002891 }
Eric Biggersc01995e2020-11-03 14:11:00 -08002892 return 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002893 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002894 sleep(2); /* Give the UI a chance to show 100% progress */
2895 cryptfs_reboot(RebootType::reboot);
Paul Lawrence87999172014-02-20 12:21:31 -08002896 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002897 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002898 char value[PROPERTY_VALUE_MAX];
2899
Ken Sumrall319369a2012-06-27 16:30:18 -07002900 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002901 if (!strcmp(value, "1")) {
2902 /* wipe data if encryption failed */
2903 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002904 std::string err;
2905 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002906 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002907 if (!write_bootloader_message(options, &err)) {
2908 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002909 }
Josh Gaofec44372017-08-28 13:22:55 -07002910 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002911 } else {
2912 /* set property to trigger dialog */
2913 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002914 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002915 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002916 }
2917
Ken Sumrall3ed82362011-01-28 23:31:16 -08002918 /* hrm, the encrypt step claims success, but the reboot failed.
2919 * This should not happen.
2920 * Set the property and return. Hope the framework can deal with it.
2921 */
2922 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002923 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002924
2925error_unencrypted:
2926 property_set("vold.encrypt_progress", "error_not_encrypted");
2927 return -1;
2928
2929error_shutting_down:
2930 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2931 * but the framework is stopped and not restarted to show the error, so it's up to
2932 * vold to restart the system.
2933 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002934 SLOGE(
2935 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2936 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002937 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002938
2939 /* shouldn't get here */
2940 property_set("vold.encrypt_progress", "error_shutting_down");
2941 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002942}
2943
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002944int cryptfs_enable(int type, const char* passwd, int no_ui) {
2945 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002946}
2947
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002948int cryptfs_enable_default(int no_ui) {
2949 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002950}
2951
Bill Peckham0db11972018-10-10 10:25:42 -07002952int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002953 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002954 SLOGE("cryptfs_changepw not valid for file encryption");
2955 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002956 }
2957
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002958 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002959 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002960
2961 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002962 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002963 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002964 return -1;
2965 }
2966
Paul Lawrencef4faa572014-01-29 13:31:03 -08002967 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2968 SLOGE("Invalid crypt_type %d", crypt_type);
2969 return -1;
2970 }
2971
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002972 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002973 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002974 SLOGE("Error getting crypt footer and key");
2975 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002976 }
2977
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302978#ifdef CONFIG_HW_DISK_ENCRYPTION
2979 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2980 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
2981 else {
2982 crypt_ftr.crypt_type = crypt_type;
2983
2984 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
2985 DEFAULT_PASSWORD : newpw,
2986 crypt_ftr.salt,
2987 saved_master_key,
2988 crypt_ftr.master_key,
2989 &crypt_ftr, false);
2990 if (rc) {
2991 SLOGE("Encrypt master key failed: %d", rc);
2992 return -1;
2993 }
2994 /* save the key */
2995 put_crypt_ftr_and_key(&crypt_ftr);
2996
2997 return 0;
2998 }
2999#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003000 crypt_ftr.crypt_type = crypt_type;
3001
Paul Crowley14c8c072018-09-18 13:30:21 -07003002 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07003003 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
3004 false);
JP Abgrall933216c2015-02-11 13:44:32 -08003005 if (rc) {
3006 SLOGE("Encrypt master key failed: %d", rc);
3007 return -1;
3008 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003009 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003010 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003011
3012 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303013#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003014}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003015
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303016#ifdef CONFIG_HW_DISK_ENCRYPTION
3017int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3018{
3019 struct crypt_mnt_ftr crypt_ftr;
3020 int rc;
3021 int previous_type;
3022
3023 /* get key */
3024 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3025 SLOGE("Error getting crypt footer and key");
3026 return -1;
3027 }
3028
3029 previous_type = crypt_ftr.crypt_type;
3030 int rc1;
3031 unsigned char tmp_curpw[32] = {0};
3032 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3033 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3034 crypt_ftr.salt, &crypt_ftr);
3035
3036 crypt_ftr.crypt_type = crypt_type;
3037
3038 int ret, rc2;
3039 unsigned char tmp_newpw[32] = {0};
3040
3041 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3042 DEFAULT_PASSWORD : newpw , tmp_newpw,
3043 crypt_ftr.salt, &crypt_ftr);
3044
3045 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3046 ret = update_hw_device_encryption_key(
3047 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3048 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3049 (char*)crypt_ftr.crypto_type_name);
3050 if (ret) {
3051 SLOGE("Error updating device encryption hardware key ret %d", ret);
3052 return -1;
3053 } else {
3054 SLOGI("Encryption hardware key updated");
3055 }
3056 }
3057
3058 /* save the key */
3059 put_crypt_ftr_and_key(&crypt_ftr);
3060 return 0;
3061}
3062#endif
3063
Rubin Xu85c01f92014-10-13 12:49:54 +01003064static unsigned int persist_get_max_entries(int encrypted) {
3065 struct crypt_mnt_ftr crypt_ftr;
3066 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003067
3068 /* If encrypted, use the values from the crypt_ftr, otherwise
3069 * use the values for the current spec.
3070 */
3071 if (encrypted) {
3072 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003073 /* Something is wrong, assume no space for entries */
3074 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003075 }
3076 dsize = crypt_ftr.persist_data_size;
3077 } else {
3078 dsize = CRYPT_PERSIST_DATA_SIZE;
3079 }
3080
Rubin Xud78181b2018-10-09 16:13:38 +01003081 if (dsize > sizeof(struct crypt_persist_data)) {
3082 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3083 } else {
3084 return 0;
3085 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003086}
3087
Paul Crowley14c8c072018-09-18 13:30:21 -07003088static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003089 unsigned int i;
3090
3091 if (persist_data == NULL) {
3092 return -1;
3093 }
3094 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3095 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3096 /* We found it! */
3097 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3098 return 0;
3099 }
3100 }
3101
3102 return -1;
3103}
3104
Paul Crowley14c8c072018-09-18 13:30:21 -07003105static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003106 unsigned int i;
3107 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003108 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003109
3110 if (persist_data == NULL) {
3111 return -1;
3112 }
3113
Rubin Xu85c01f92014-10-13 12:49:54 +01003114 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003115
3116 num = persist_data->persist_valid_entries;
3117
3118 for (i = 0; i < num; i++) {
3119 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3120 /* We found an existing entry, update it! */
3121 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3122 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3123 return 0;
3124 }
3125 }
3126
3127 /* We didn't find it, add it to the end, if there is room */
3128 if (persist_data->persist_valid_entries < max_persistent_entries) {
3129 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3130 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3131 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3132 persist_data->persist_valid_entries++;
3133 return 0;
3134 }
3135
3136 return -1;
3137}
3138
Rubin Xu85c01f92014-10-13 12:49:54 +01003139/**
3140 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3141 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3142 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003143int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003144 std::string key_ = key;
3145 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003146
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003147 std::string parsed_field;
3148 unsigned parsed_index;
3149
3150 std::string::size_type split = key_.find_last_of('_');
3151 if (split == std::string::npos) {
3152 parsed_field = key_;
3153 parsed_index = 0;
3154 } else {
3155 parsed_field = key_.substr(0, split);
3156 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003157 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003158
3159 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003160}
3161
3162/*
3163 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3164 * remaining entries starting from index will be deleted.
3165 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3166 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3167 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3168 *
3169 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003170static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003171 unsigned int i;
3172 unsigned int j;
3173 unsigned int num;
3174
3175 if (persist_data == NULL) {
3176 return PERSIST_DEL_KEY_ERROR_OTHER;
3177 }
3178
3179 num = persist_data->persist_valid_entries;
3180
Paul Crowley14c8c072018-09-18 13:30:21 -07003181 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003182 // Filter out to-be-deleted entries in place.
3183 for (i = 0; i < num; i++) {
3184 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3185 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3186 j++;
3187 }
3188 }
3189
3190 if (j < num) {
3191 persist_data->persist_valid_entries = j;
3192 // Zeroise the remaining entries
3193 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3194 return PERSIST_DEL_KEY_OK;
3195 } else {
3196 // Did not find an entry matching the given fieldname
3197 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3198 }
3199}
3200
Paul Crowley14c8c072018-09-18 13:30:21 -07003201static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003202 unsigned int i;
3203 unsigned int count;
3204
3205 if (persist_data == NULL) {
3206 return -1;
3207 }
3208
3209 count = 0;
3210 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3211 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3212 count++;
3213 }
3214 }
3215
3216 return count;
3217}
3218
Ken Sumrall160b4d62013-04-22 12:15:39 -07003219/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003220int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003221 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003222 SLOGE("Cannot get field when file encrypted");
3223 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003224 }
3225
Ken Sumrall160b4d62013-04-22 12:15:39 -07003226 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003227 /* CRYPTO_GETFIELD_OK is success,
3228 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3229 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3230 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003231 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003232 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3233 int i;
3234 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003235
3236 if (persist_data == NULL) {
3237 load_persistent_data();
3238 if (persist_data == NULL) {
3239 SLOGE("Getfield error, cannot load persistent data");
3240 goto out;
3241 }
3242 }
3243
Rubin Xu85c01f92014-10-13 12:49:54 +01003244 // Read value from persistent entries. If the original value is split into multiple entries,
3245 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003246 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003247 // 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 -07003248 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003249 // value too small
3250 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3251 goto out;
3252 }
3253 rc = CRYPTO_GETFIELD_OK;
3254
3255 for (i = 1; /* break explicitly */; i++) {
3256 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003257 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003258 // If the fieldname is very long, we stop as soon as it begins to overflow the
3259 // maximum field length. At this point we have in fact fully read out the original
3260 // value because cryptfs_setfield would not allow fields with longer names to be
3261 // written in the first place.
3262 break;
3263 }
3264 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003265 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3266 // value too small.
3267 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3268 goto out;
3269 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003270 } else {
3271 // Exhaust all entries.
3272 break;
3273 }
3274 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003275 } else {
3276 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003277 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003278 }
3279
3280out:
3281 return rc;
3282}
3283
3284/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003285int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003286 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003287 SLOGE("Cannot set field when file encrypted");
3288 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003289 }
3290
Ken Sumrall160b4d62013-04-22 12:15:39 -07003291 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003292 /* 0 is success, negative values are error */
3293 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003294 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003295 unsigned int field_id;
3296 char temp_field[PROPERTY_KEY_MAX];
3297 unsigned int num_entries;
3298 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003299
3300 if (persist_data == NULL) {
3301 load_persistent_data();
3302 if (persist_data == NULL) {
3303 SLOGE("Setfield error, cannot load persistent data");
3304 goto out;
3305 }
3306 }
3307
3308 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003309 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003310 encrypted = 1;
3311 }
3312
Rubin Xu85c01f92014-10-13 12:49:54 +01003313 // Compute the number of entries required to store value, each entry can store up to
3314 // (PROPERTY_VALUE_MAX - 1) chars
3315 if (strlen(value) == 0) {
3316 // Empty value also needs one entry to store.
3317 num_entries = 1;
3318 } else {
3319 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3320 }
3321
3322 max_keylen = strlen(fieldname);
3323 if (num_entries > 1) {
3324 // Need an extra "_%d" suffix.
3325 max_keylen += 1 + log10(num_entries);
3326 }
3327 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3328 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003329 goto out;
3330 }
3331
Rubin Xu85c01f92014-10-13 12:49:54 +01003332 // Make sure we have enough space to write the new value
3333 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3334 persist_get_max_entries(encrypted)) {
3335 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3336 goto out;
3337 }
3338
3339 // Now that we know persist_data has enough space for value, let's delete the old field first
3340 // to make up space.
3341 persist_del_keys(fieldname, 0);
3342
3343 if (persist_set_key(fieldname, value, encrypted)) {
3344 // fail to set key, should not happen as we have already checked the available space
3345 SLOGE("persist_set_key() error during setfield()");
3346 goto out;
3347 }
3348
3349 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003350 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003351
3352 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3353 // fail to set key, should not happen as we have already checked the available space.
3354 SLOGE("persist_set_key() error during setfield()");
3355 goto out;
3356 }
3357 }
3358
Ken Sumrall160b4d62013-04-22 12:15:39 -07003359 /* If we are running encrypted, save the persistent data now */
3360 if (encrypted) {
3361 if (save_persistent_data()) {
3362 SLOGE("Setfield error, cannot save persistent data");
3363 goto out;
3364 }
3365 }
3366
Rubin Xu85c01f92014-10-13 12:49:54 +01003367 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003368
3369out:
3370 return rc;
3371}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003372
3373/* Checks userdata. Attempt to mount the volume if default-
3374 * encrypted.
3375 * On success trigger next init phase and return 0.
3376 * Currently do not handle failure - see TODO below.
3377 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003378int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003379 int crypt_type = cryptfs_get_password_type();
3380 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3381 SLOGE("Bad crypt type - error");
3382 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003383 SLOGD(
3384 "Password is not default - "
3385 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003386 property_set("vold.decrypt", "trigger_restart_min_framework");
3387 return 0;
3388 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3389 SLOGD("Password is default - restarting filesystem");
3390 cryptfs_restart_internal(0);
3391 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003392 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003393 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003394 }
3395
Paul Lawrence6bfed202014-07-28 12:47:22 -07003396 /** Corrupt. Allow us to boot into framework, which will detect bad
3397 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003398 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003399 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003400 return 0;
3401}
3402
3403/* Returns type of the password, default, pattern, pin or password.
3404 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003405int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003406 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003407 SLOGE("cryptfs_get_password_type not valid for file encryption");
3408 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003409 }
3410
Paul Lawrencef4faa572014-01-29 13:31:03 -08003411 struct crypt_mnt_ftr crypt_ftr;
3412
3413 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3414 SLOGE("Error getting crypt footer and key\n");
3415 return -1;
3416 }
3417
Paul Lawrence6bfed202014-07-28 12:47:22 -07003418 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3419 return -1;
3420 }
3421
Paul Lawrencef4faa572014-01-29 13:31:03 -08003422 return crypt_ftr.crypt_type;
3423}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003424
Paul Crowley14c8c072018-09-18 13:30:21 -07003425const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003426 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003427 SLOGE("cryptfs_get_password not valid for file encryption");
3428 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003429 }
3430
Paul Lawrence399317e2014-03-10 13:20:50 -07003431 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003432 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003433 if (now.tv_sec < password_expiry_time) {
3434 return password;
3435 } else {
3436 cryptfs_clear_password();
3437 return 0;
3438 }
3439}
3440
Paul Crowley14c8c072018-09-18 13:30:21 -07003441void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003442 if (password) {
3443 size_t len = strlen(password);
3444 memset(password, 0, len);
3445 free(password);
3446 password = 0;
3447 password_expiry_time = 0;
3448 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003449}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003450
Paul Crowley14c8c072018-09-18 13:30:21 -07003451int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003452 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3453 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003454}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303455
3456int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3457{
3458 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3459 SLOGE("Failed to initialize crypt_ftr");
3460 return -1;
3461 }
3462
3463 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3464 crypt_ftr->salt, crypt_ftr)) {
3465 SLOGE("Cannot create encrypted master key\n");
3466 return -1;
3467 }
3468
3469 //crypt_ftr->keysize = key_length / 8;
3470 return 0;
3471}
3472
3473int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3474 unsigned char* master_key)
3475{
3476 int rc;
3477
3478 unsigned char* intermediate_key = 0;
3479 size_t intermediate_key_size = 0;
3480
3481 if (password == 0 || *password == 0) {
3482 password = DEFAULT_PASSWORD;
3483 }
3484
3485 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3486 &intermediate_key_size);
3487
3488 if (rc) {
3489 SLOGE("Can't calculate intermediate key");
3490 return rc;
3491 }
3492
3493 int N = 1 << ftr->N_factor;
3494 int r = 1 << ftr->r_factor;
3495 int p = 1 << ftr->p_factor;
3496
3497 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3498
3499 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3500 ftr->salt, sizeof(ftr->salt), N, r, p,
3501 scrypted_intermediate_key,
3502 sizeof(scrypted_intermediate_key));
3503
3504 free(intermediate_key);
3505
3506 if (rc) {
3507 SLOGE("Can't scrypt intermediate key");
3508 return rc;
3509 }
3510
3511 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3512 intermediate_key_size);
3513}