blob: 738003b14eea54c812c4753e2d98834959c2befe [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
482/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700483static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800484 if (ftr->keymaster_blob_size) {
485 SLOGI("Already have key");
486 return 0;
487 }
488
Paul Crowley14c8c072018-09-18 13:30:21 -0700489 int rc = keymaster_create_key_for_cryptfs_scrypt(
490 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
491 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000492 if (rc) {
493 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800494 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000495 ftr->keymaster_blob_size = 0;
496 }
497 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700498 return -1;
499 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000500 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700501}
502
Shawn Willdene17a9c42014-09-08 13:04:08 -0600503/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700504static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
505 const size_t object_size, unsigned char** signature,
506 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600507 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600508 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600509 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600510
Shawn Willdene17a9c42014-09-08 13:04:08 -0600511 // To sign a message with RSA, the message must satisfy two
512 // constraints:
513 //
514 // 1. The message, when interpreted as a big-endian numeric value, must
515 // be strictly less than the public modulus of the RSA key. Note
516 // that because the most significant bit of the public modulus is
517 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
518 // key), an n-bit message with most significant bit 0 always
519 // satisfies this requirement.
520 //
521 // 2. The message must have the same length in bits as the public
522 // modulus of the RSA key. This requirement isn't mathematically
523 // necessary, but is necessary to ensure consistency in
524 // implementations.
525 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600526 case KDF_SCRYPT_KEYMASTER:
527 // This ensures the most significant byte of the signed message
528 // is zero. We could have zero-padded to the left instead, but
529 // this approach is slightly more robust against changes in
530 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600531 // so) because we really should be using a proper deterministic
532 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800533 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600534 SLOGI("Signing safely-padded object");
535 break;
536 default:
537 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000538 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600539 }
Scott Lobdell3d4eed12021-04-23 21:04:09 +0000540 for (;;) {
541 auto result = keymaster_sign_object_for_cryptfs_scrypt(
542 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
543 to_sign_size, signature, signature_size);
544 switch (result) {
545 case KeymasterSignResult::ok:
546 return 0;
547 case KeymasterSignResult::upgrade:
548 break;
549 default:
550 return -1;
551 }
552 SLOGD("Upgrading key");
553 if (keymaster_upgrade_key_for_cryptfs_scrypt(
554 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
555 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
556 &ftr->keymaster_blob_size) != 0) {
557 SLOGE("Failed to upgrade key");
558 return -1;
559 }
560 if (put_crypt_ftr_and_key(ftr) != 0) {
561 SLOGE("Failed to write upgraded key to disk");
562 }
563 SLOGD("Key upgraded successfully");
564 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600565}
566
Paul Lawrence399317e2014-03-10 13:20:50 -0700567/* Store password when userdata is successfully decrypted and mounted.
568 * Cleared by cryptfs_clear_password
569 *
570 * To avoid a double prompt at boot, we need to store the CryptKeeper
571 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
572 * Since the entire framework is torn down and rebuilt after encryption,
573 * we have to use a daemon or similar to store the password. Since vold
574 * is secured against IPC except from system processes, it seems a reasonable
575 * place to store this.
576 *
577 * password should be cleared once it has been used.
578 *
579 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800580 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700581static char* password = 0;
582static int password_expiry_time = 0;
583static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800584
Paul Crowley14c8c072018-09-18 13:30:21 -0700585enum class RebootType { reboot, recovery, shutdown };
586static void cryptfs_reboot(RebootType rt) {
587 switch (rt) {
588 case RebootType::reboot:
589 property_set(ANDROID_RB_PROPERTY, "reboot");
590 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800591
Paul Crowley14c8c072018-09-18 13:30:21 -0700592 case RebootType::recovery:
593 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
594 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800595
Paul Crowley14c8c072018-09-18 13:30:21 -0700596 case RebootType::shutdown:
597 property_set(ANDROID_RB_PROPERTY, "shutdown");
598 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700599 }
Paul Lawrence87999172014-02-20 12:21:31 -0800600
Ken Sumralladfba362013-06-04 16:37:52 -0700601 sleep(20);
602
603 /* Shouldn't get here, reboot should happen before sleep times out */
604 return;
605}
606
Kenny Rootc4c70f12013-06-14 12:11:38 -0700607/**
608 * Gets the default device scrypt parameters for key derivation time tuning.
609 * The parameters should lead to about one second derivation time for the
610 * given device.
611 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700612static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700613 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000614 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700615
Paul Crowley63c18d32016-02-10 14:02:47 +0000616 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
617 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
618 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
619 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700620 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000621 ftr->N_factor = Nf;
622 ftr->r_factor = rf;
623 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700624}
625
Tom Cherry4c5bde22019-01-29 14:34:01 -0800626static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800627 int fd, block_size;
628 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200629 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800630
Paul Crowley14c8c072018-09-18 13:30:21 -0700631 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800632 SLOGE("Cannot open device to get filesystem size ");
633 return 0;
634 }
635
636 if (lseek64(fd, 1024, SEEK_SET) < 0) {
637 SLOGE("Cannot seek to superblock");
638 return 0;
639 }
640
641 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
642 SLOGE("Cannot read superblock");
643 return 0;
644 }
645
646 close(fd);
647
Daniel Rosenberge82df162014-08-15 22:19:23 +0000648 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
649 SLOGE("Not a valid ext4 superblock");
650 return 0;
651 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800652 block_size = 1024 << sb.s_log_block_size;
653 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200654 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800655
656 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200657 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800658}
659
Tom Cherry4c5bde22019-01-29 14:34:01 -0800660static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
661 for (const auto& entry : fstab_default) {
662 if (!entry.fs_mgr_flags.vold_managed &&
663 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
664 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
665 if (key_loc != nullptr) {
666 *key_loc = entry.key_loc;
667 }
668 if (real_blk_device != nullptr) {
669 *real_blk_device = entry.blk_device;
670 }
671 return;
672 }
673 }
674}
675
Paul Crowley14c8c072018-09-18 13:30:21 -0700676static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
677 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200678 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700679 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700680 char key_loc[PROPERTY_VALUE_MAX];
681 char real_blkdev[PROPERTY_VALUE_MAX];
682 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700683
Paul Crowley14c8c072018-09-18 13:30:21 -0700684 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800685 std::string key_loc;
686 std::string real_blkdev;
687 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700688
Tom Cherry4c5bde22019-01-29 14:34:01 -0800689 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200690 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700691 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
692 * encryption info footer and key, and plenty of bytes to spare for future
693 * growth.
694 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800695 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200696 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700697 cached_data = 1;
698 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800699 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700700 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700701 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800702 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700703 cached_off = 0;
704 cached_data = 1;
705 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700706 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700707
Paul Crowley14c8c072018-09-18 13:30:21 -0700708 if (cached_data) {
709 if (metadata_fname) {
710 *metadata_fname = cached_metadata_fname;
711 }
712 if (off) {
713 *off = cached_off;
714 }
715 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700716 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700717
Paul Crowley14c8c072018-09-18 13:30:21 -0700718 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700719}
720
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800721/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700722static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800723 SHA256_CTX c;
724 SHA256_Init(&c);
725 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
726 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
727 SHA256_Final(crypt_ftr->sha256, &c);
728}
729
Ken Sumralle8744072011-01-18 22:01:55 -0800730/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800731 * update the failed mount count but not change the key.
732 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700733static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
734 int fd;
735 unsigned int cnt;
736 /* starting_off is set to the SEEK_SET offset
737 * where the crypto structure starts
738 */
739 off64_t starting_off;
740 int rc = -1;
741 char* fname = NULL;
742 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800743
Paul Crowley14c8c072018-09-18 13:30:21 -0700744 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800745
Paul Crowley14c8c072018-09-18 13:30:21 -0700746 if (get_crypt_ftr_info(&fname, &starting_off)) {
747 SLOGE("Unable to get crypt_ftr_info\n");
748 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800749 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700750 if (fname[0] != '/') {
751 SLOGE("Unexpected value for crypto key location\n");
752 return -1;
753 }
754 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
755 SLOGE("Cannot open footer file %s for put\n", fname);
756 return -1;
757 }
Ken Sumralle8744072011-01-18 22:01:55 -0800758
Paul Crowley14c8c072018-09-18 13:30:21 -0700759 /* Seek to the start of the crypt footer */
760 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
761 SLOGE("Cannot seek to real block device footer\n");
762 goto errout;
763 }
764
765 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
766 SLOGE("Cannot write real block device footer\n");
767 goto errout;
768 }
769
770 fstat(fd, &statbuf);
771 /* If the keys are kept on a raw block device, do not try to truncate it. */
772 if (S_ISREG(statbuf.st_mode)) {
773 if (ftruncate(fd, 0x4000)) {
774 SLOGE("Cannot set footer file size\n");
775 goto errout;
776 }
777 }
778
779 /* Success! */
780 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800781
782errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700783 close(fd);
784 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800785}
786
Paul Crowley14c8c072018-09-18 13:30:21 -0700787static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800788 struct crypt_mnt_ftr copy;
789 memcpy(&copy, crypt_ftr, sizeof(copy));
790 set_ftr_sha(&copy);
791 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
792}
793
Paul Crowley14c8c072018-09-18 13:30:21 -0700794static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700795 return TEMP_FAILURE_RETRY(read(fd, buff, len));
796}
797
Paul Crowley14c8c072018-09-18 13:30:21 -0700798static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700799 return TEMP_FAILURE_RETRY(write(fd, buff, len));
800}
801
Paul Crowley14c8c072018-09-18 13:30:21 -0700802static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700803 memset(pdata, 0, len);
804 pdata->persist_magic = PERSIST_DATA_MAGIC;
805 pdata->persist_valid_entries = 0;
806}
807
808/* A routine to update the passed in crypt_ftr to the lastest version.
809 * fd is open read/write on the device that holds the crypto footer and persistent
810 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
811 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
812 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700813static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700814 int orig_major = crypt_ftr->major_version;
815 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700816
Kenny Root7434b312013-06-14 11:29:53 -0700817 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700818 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700819 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700820
Kenny Rootc4c70f12013-06-14 12:11:38 -0700821 SLOGW("upgrading crypto footer to 1.1");
822
Paul Crowley14c8c072018-09-18 13:30:21 -0700823 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700824 if (pdata == NULL) {
825 SLOGE("Cannot allocate persisent data\n");
826 return;
827 }
828 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
829
830 /* Need to initialize the persistent data area */
831 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
832 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100833 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700834 return;
835 }
836 /* Write all zeros to the first copy, making it invalid */
837 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
838
839 /* Write a valid but empty structure to the second copy */
840 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
841 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
842
843 /* Update the footer */
844 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
845 crypt_ftr->persist_data_offset[0] = pdata_offset;
846 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
847 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100848 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700849 }
850
Paul Lawrencef4faa572014-01-29 13:31:03 -0800851 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700852 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800853 /* But keep the old kdf_type.
854 * It will get updated later to KDF_SCRYPT after the password has been verified.
855 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700856 crypt_ftr->kdf_type = KDF_PBKDF2;
857 get_device_scrypt_params(crypt_ftr);
858 crypt_ftr->minor_version = 2;
859 }
860
Paul Lawrencef4faa572014-01-29 13:31:03 -0800861 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
862 SLOGW("upgrading crypto footer to 1.3");
863 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
864 crypt_ftr->minor_version = 3;
865 }
866
Kenny Root7434b312013-06-14 11:29:53 -0700867 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
868 if (lseek64(fd, offset, SEEK_SET) == -1) {
869 SLOGE("Cannot seek to crypt footer\n");
870 return;
871 }
872 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700873 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700874}
875
Paul Crowley14c8c072018-09-18 13:30:21 -0700876static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
877 int fd;
878 unsigned int cnt;
879 off64_t starting_off;
880 int rc = -1;
881 char* fname = NULL;
882 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700883
Paul Crowley14c8c072018-09-18 13:30:21 -0700884 if (get_crypt_ftr_info(&fname, &starting_off)) {
885 SLOGE("Unable to get crypt_ftr_info\n");
886 return -1;
887 }
888 if (fname[0] != '/') {
889 SLOGE("Unexpected value for crypto key location\n");
890 return -1;
891 }
892 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
893 SLOGE("Cannot open footer file %s for get\n", fname);
894 return -1;
895 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800896
Paul Crowley14c8c072018-09-18 13:30:21 -0700897 /* Make sure it's 16 Kbytes in length */
898 fstat(fd, &statbuf);
899 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
900 SLOGE("footer file %s is not the expected size!\n", fname);
901 goto errout;
902 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700903
Paul Crowley14c8c072018-09-18 13:30:21 -0700904 /* Seek to the start of the crypt footer */
905 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
906 SLOGE("Cannot seek to real block device footer\n");
907 goto errout;
908 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700909
Paul Crowley14c8c072018-09-18 13:30:21 -0700910 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
911 SLOGE("Cannot read real block device footer\n");
912 goto errout;
913 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800914
Paul Crowley14c8c072018-09-18 13:30:21 -0700915 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
916 SLOGE("Bad magic for real block device %s\n", fname);
917 goto errout;
918 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800919
Paul Crowley14c8c072018-09-18 13:30:21 -0700920 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
921 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
922 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
923 goto errout;
924 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800925
Paul Crowley14c8c072018-09-18 13:30:21 -0700926 // We risk buffer overflows with oversized keys, so we just reject them.
927 // 0-sized keys are problematic (essentially by-passing encryption), and
928 // AES-CBC key wrapping only works for multiples of 16 bytes.
929 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
930 (crypt_ftr->keysize > MAX_KEY_LEN)) {
931 SLOGE(
932 "Invalid keysize (%u) for block device %s; Must be non-zero, "
933 "divisible by 16, and <= %d\n",
934 crypt_ftr->keysize, fname, MAX_KEY_LEN);
935 goto errout;
936 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937
Paul Crowley14c8c072018-09-18 13:30:21 -0700938 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
939 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
940 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
941 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800942
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
944 * copy on disk before returning.
945 */
946 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
947 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
948 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949
Paul Crowley14c8c072018-09-18 13:30:21 -0700950 /* Success! */
951 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952
953errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700954 close(fd);
955 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800956}
957
Paul Crowley14c8c072018-09-18 13:30:21 -0700958static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700959 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
960 crypt_ftr->persist_data_offset[1]) {
961 SLOGE("Crypt_ftr persist data regions overlap");
962 return -1;
963 }
964
965 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
966 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
967 return -1;
968 }
969
970 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700971 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700972 CRYPT_FOOTER_OFFSET) {
973 SLOGE("Persistent data extends past crypto footer");
974 return -1;
975 }
976
977 return 0;
978}
979
Paul Crowley14c8c072018-09-18 13:30:21 -0700980static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700981 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700982 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700983 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700984 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700985 int found = 0;
986 int fd;
987 int ret;
988 int i;
989
990 if (persist_data) {
991 /* Nothing to do, we've already loaded or initialized it */
992 return 0;
993 }
994
Ken Sumrall160b4d62013-04-22 12:15:39 -0700995 /* If not encrypted, just allocate an empty table and initialize it */
996 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700997 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800998 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700999 if (pdata) {
1000 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1001 persist_data = pdata;
1002 return 0;
1003 }
1004 return -1;
1005 }
1006
Paul Crowley14c8c072018-09-18 13:30:21 -07001007 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001008 return -1;
1009 }
1010
Paul Crowley14c8c072018-09-18 13:30:21 -07001011 if ((crypt_ftr.major_version < 1) ||
1012 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001013 SLOGE("Crypt_ftr version doesn't support persistent data");
1014 return -1;
1015 }
1016
1017 if (get_crypt_ftr_info(&fname, NULL)) {
1018 return -1;
1019 }
1020
1021 ret = validate_persistent_data_storage(&crypt_ftr);
1022 if (ret) {
1023 return -1;
1024 }
1025
Paul Crowley14c8c072018-09-18 13:30:21 -07001026 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001027 if (fd < 0) {
1028 SLOGE("Cannot open %s metadata file", fname);
1029 return -1;
1030 }
1031
Wei Wang4375f1b2017-02-24 17:43:01 -08001032 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -08001033 if (pdata == NULL) {
1034 SLOGE("Cannot allocate memory for persistent data");
1035 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001036 }
1037
1038 for (i = 0; i < 2; i++) {
1039 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
1040 SLOGE("Cannot seek to read persistent data on %s", fname);
1041 goto err2;
1042 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001043 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001044 SLOGE("Error reading persistent data on iteration %d", i);
1045 goto err2;
1046 }
1047 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1048 found = 1;
1049 break;
1050 }
1051 }
1052
1053 if (!found) {
1054 SLOGI("Could not find valid persistent data, creating");
1055 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
1056 }
1057
1058 /* Success */
1059 persist_data = pdata;
1060 close(fd);
1061 return 0;
1062
1063err2:
1064 free(pdata);
1065
1066err:
1067 close(fd);
1068 return -1;
1069}
1070
Paul Crowley14c8c072018-09-18 13:30:21 -07001071static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001072 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001073 struct crypt_persist_data* pdata;
1074 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001075 off64_t write_offset;
1076 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001077 int fd;
1078 int ret;
1079
1080 if (persist_data == NULL) {
1081 SLOGE("No persistent data to save");
1082 return -1;
1083 }
1084
Paul Crowley14c8c072018-09-18 13:30:21 -07001085 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001086 return -1;
1087 }
1088
Paul Crowley14c8c072018-09-18 13:30:21 -07001089 if ((crypt_ftr.major_version < 1) ||
1090 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001091 SLOGE("Crypt_ftr version doesn't support persistent data");
1092 return -1;
1093 }
1094
1095 ret = validate_persistent_data_storage(&crypt_ftr);
1096 if (ret) {
1097 return -1;
1098 }
1099
1100 if (get_crypt_ftr_info(&fname, NULL)) {
1101 return -1;
1102 }
1103
Paul Crowley14c8c072018-09-18 13:30:21 -07001104 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001105 if (fd < 0) {
1106 SLOGE("Cannot open %s metadata file", fname);
1107 return -1;
1108 }
1109
Wei Wang4375f1b2017-02-24 17:43:01 -08001110 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001111 if (pdata == NULL) {
1112 SLOGE("Cannot allocate persistant data");
1113 goto err;
1114 }
1115
1116 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1117 SLOGE("Cannot seek to read persistent data on %s", fname);
1118 goto err2;
1119 }
1120
1121 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001122 SLOGE("Error reading persistent data before save");
1123 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001124 }
1125
1126 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1127 /* The first copy is the curent valid copy, so write to
1128 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001129 write_offset = crypt_ftr.persist_data_offset[1];
1130 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001131 } else {
1132 /* The second copy must be the valid copy, so write to
1133 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001134 write_offset = crypt_ftr.persist_data_offset[0];
1135 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001136 }
1137
1138 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001139 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001140 SLOGE("Cannot seek to write persistent data");
1141 goto err2;
1142 }
1143 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001144 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001145 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001146 SLOGE("Cannot seek to erase previous persistent data");
1147 goto err2;
1148 }
1149 fsync(fd);
1150 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001151 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001152 SLOGE("Cannot write to erase previous persistent data");
1153 goto err2;
1154 }
1155 fsync(fd);
1156 } else {
1157 SLOGE("Cannot write to save persistent data");
1158 goto err2;
1159 }
1160
1161 /* Success */
1162 free(pdata);
1163 close(fd);
1164 return 0;
1165
1166err2:
1167 free(pdata);
1168err:
1169 close(fd);
1170 return -1;
1171}
1172
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001173/* Convert a binary key of specified length into an ascii hex string equivalent,
1174 * without the leading 0x and with null termination
1175 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001176static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1177 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001178 unsigned int i, a;
1179 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180
Paul Crowley14c8c072018-09-18 13:30:21 -07001181 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001182 /* For each byte, write out two ascii hex digits */
1183 nibble = (master_key[i] >> 4) & 0xf;
1184 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001185
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001186 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001187 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001188 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001189
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001190 /* Add the null termination */
1191 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001192}
1193
Eric Biggersed45ec32019-01-25 10:47:55 -08001194/*
1195 * If the ro.crypto.fde_sector_size system property is set, append the
1196 * parameters to make dm-crypt use the specified crypto sector size and round
1197 * the crypto device size down to a crypto sector boundary.
1198 */
David Andersonb9224732019-05-13 13:02:54 -07001199static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001200 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001201 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001202
Eric Biggersed45ec32019-01-25 10:47:55 -08001203 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1204 unsigned int sector_size;
1205
1206 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1207 (sector_size & (sector_size - 1)) != 0) {
1208 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1209 DM_CRYPT_SECTOR_SIZE, value);
1210 return -1;
1211 }
1212
David Andersonb9224732019-05-13 13:02:54 -07001213 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001214
1215 // With this option, IVs will match the sector numbering, instead
1216 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001217 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001218
1219 // Round the crypto device size down to a crypto sector boundary.
1220 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001221 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001222 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001223}
1224
Neeraj Soni73b46952019-09-12 16:47:27 +05301225#if defined(CONFIG_HW_DISK_ENCRYPTION) && !defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1226#define DM_CRYPT_BUF_SIZE 4096
1227
1228static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
1229 memset(io, 0, dataSize);
1230 io->data_size = dataSize;
1231 io->data_start = sizeof(struct dm_ioctl);
1232 io->version[0] = 4;
1233 io->version[1] = 0;
1234 io->version[2] = 0;
1235 io->flags = flags;
1236 if (name) {
1237 strlcpy(io->name, name, sizeof(io->name));
1238 }
1239}
1240
1241static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1242 const unsigned char* master_key, const char* real_blk_name,
1243 const char* name, int fd, const char* extra_params) {
1244 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1245 struct dm_ioctl* io;
1246 struct dm_target_spec* tgt;
1247 char* crypt_params;
1248 // We need two ASCII characters to represent each byte, and need space for
1249 // the '\0' terminator.
1250 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1251 size_t buff_offset;
1252 int i;
1253
1254 io = (struct dm_ioctl*)buffer;
1255
1256 /* Load the mapping table for this device */
1257 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
1258
1259 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1260 io->target_count = 1;
1261 tgt->status = 0;
1262 tgt->sector_start = 0;
1263 tgt->length = crypt_ftr->fs_size;
1264 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1265 buff_offset = crypt_params - buffer;
1266 SLOGI(
1267 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1268 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1269 extra_params);
1270 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1271 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1272 if (is_ice_enabled())
1273 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1274 else
1275 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1276 }
1277 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1278 crypt_ftr->crypto_type_name, master_key_ascii,
1279 real_blk_name, extra_params);
1280
1281 SLOGI("target_type = %s", tgt->target_type);
1282 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1283
1284 crypt_params += strlen(crypt_params) + 1;
1285 crypt_params =
1286 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1287 tgt->next = crypt_params - buffer;
1288
1289 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1290 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1291 break;
1292 }
1293 usleep(500000);
1294 }
1295
1296 if (i == TABLE_LOAD_RETRIES) {
1297 /* We failed to load the table, return an error */
1298 return -1;
1299 } else {
1300 return i + 1;
1301 }
1302}
1303
1304static int create_crypto_blk_dev_hw(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05301305 const char* real_blk_name, std::string* crypto_blk_name,
1306 const char* name, uint32_t flags) {
Neeraj Soni73b46952019-09-12 16:47:27 +05301307 char buffer[DM_CRYPT_BUF_SIZE];
1308 struct dm_ioctl* io;
1309 unsigned int minor;
1310 int fd = 0;
1311 int err;
1312 int retval = -1;
1313 int version[3];
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05301314 int load_count = 0;
Neeraj Soni73b46952019-09-12 16:47:27 +05301315 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1316 char progress[PROPERTY_VALUE_MAX] = {0};
1317 const char *extra_params;
1318
1319 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1320 SLOGE("Cannot open device-mapper\n");
1321 goto errout;
1322 }
1323
1324 io = (struct dm_ioctl*)buffer;
1325
1326 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1327 err = ioctl(fd, DM_DEV_CREATE, io);
1328 if (err) {
1329 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1330 goto errout;
1331 }
1332
1333 /* Get the device status, in particular, the name of it's device file */
1334 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1335 if (ioctl(fd, DM_DEV_STATUS, io)) {
1336 SLOGE("Cannot retrieve dm-crypt device status\n");
1337 goto errout;
1338 }
1339 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05301340 snprintf(crypto_blk_name->data(), MAXPATHLEN, "/dev/block/dm-%u", minor);
Neeraj Soni73b46952019-09-12 16:47:27 +05301341
1342 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1343 /* Set fde_enabled if either FDE completed or in-progress */
1344 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1345 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1346 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1347 if (is_ice_enabled()) {
1348 extra_params = "fde_enabled ice allow_encrypt_override";
1349 } else {
1350 extra_params = "fde_enabled allow_encrypt_override";
1351 }
1352 } else {
1353 extra_params = "fde_enabled allow_encrypt_override";
1354 }
1355 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1356 extra_params);
1357 }
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08001358
Neeraj Soni73b46952019-09-12 16:47:27 +05301359 if (load_count < 0) {
1360 SLOGE("Cannot load dm-crypt mapping table.\n");
1361 goto errout;
1362 } else if (load_count > 1) {
1363 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1364 }
1365
1366 /* Resume this device to activate it */
1367 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1368
1369 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1370 SLOGE("Cannot resume the dm-crypt device\n");
1371 goto errout;
1372 }
1373
1374 /* Ensure the dm device has been created before returning. */
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05301375 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Neeraj Soni73b46952019-09-12 16:47:27 +05301376 // WaitForFile generates a suitable log message
1377 goto errout;
1378 }
1379
1380 /* We made it here with no errors. Woot! */
1381 retval = 0;
1382
1383errout:
1384 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1385
1386 return retval;
1387}
1388#endif
1389
Paul Crowley5afbc622017-11-27 09:42:17 -08001390static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001391 const char* real_blk_name, std::string* crypto_blk_name,
1392 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001393 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001394
David Andersonb9224732019-05-13 13:02:54 -07001395 // We need two ASCII characters to represent each byte, and need space for
1396 // the '\0' terminator.
1397 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1398 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001399
David Andersonb9224732019-05-13 13:02:54 -07001400 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1401 (const char*)crypt_ftr->crypto_type_name,
1402 master_key_ascii, 0, real_blk_name, 0);
1403 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001404
Paul Crowley5afbc622017-11-27 09:42:17 -08001405 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001406 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001407 }
David Andersonb9224732019-05-13 13:02:54 -07001408 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001409 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001410 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001411 }
David Andersonb9224732019-05-13 13:02:54 -07001412
1413 DmTable table;
1414 table.AddTarget(std::move(target));
1415
1416 int load_count = 1;
1417 while (load_count < TABLE_LOAD_RETRIES) {
1418 if (dm.CreateDevice(name, table)) {
1419 break;
1420 }
1421 load_count++;
1422 }
1423
1424 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001425 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001426 return -1;
1427 }
1428 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001429 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1430 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431
Paul Crowley81796e92020-02-07 11:27:49 -08001432 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001433 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1434 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001435 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001436
Paul Crowley298fa322018-10-30 15:59:24 -07001437 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001438 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowley298fa322018-10-30 15:59:24 -07001439 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001440 return -1;
Paul Crowley298fa322018-10-30 15:59:24 -07001441 }
David Andersonb9224732019-05-13 13:02:54 -07001442 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001443}
1444
David Andersonb9224732019-05-13 13:02:54 -07001445static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001446 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001447 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001448 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1449 // to delete the device fails with EBUSY; for now, work around this by retrying.
1450 int tries = 5;
1451 while (tries-- > 0) {
1452 ret = dm.DeleteDevice(name);
1453 if (ret || errno != EBUSY) {
1454 break;
1455 }
1456 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1457 strerror(errno));
1458 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1459 }
1460 if (!ret) {
1461 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001462 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001463 }
David Andersonb9224732019-05-13 13:02:54 -07001464 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001465}
1466
Paul Crowley14c8c072018-09-18 13:30:21 -07001467static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1468 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001469 SLOGI("Using pbkdf2 for cryptfs KDF");
1470
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001471 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001472 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1473 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001474}
1475
Paul Crowley14c8c072018-09-18 13:30:21 -07001476static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001477 SLOGI("Using scrypt for cryptfs KDF");
1478
Paul Crowley14c8c072018-09-18 13:30:21 -07001479 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001480
1481 int N = 1 << ftr->N_factor;
1482 int r = 1 << ftr->r_factor;
1483 int p = 1 << ftr->p_factor;
1484
1485 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001486 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001487 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001488
Paul Crowley14c8c072018-09-18 13:30:21 -07001489 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001490}
1491
Paul Crowley14c8c072018-09-18 13:30:21 -07001492static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1493 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001494 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1495
1496 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001497 size_t signature_size;
1498 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001499 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001500
1501 int N = 1 << ftr->N_factor;
1502 int r = 1 << ftr->r_factor;
1503 int p = 1 << ftr->p_factor;
1504
Paul Crowley14c8c072018-09-18 13:30:21 -07001505 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001506 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001507
1508 if (rc) {
1509 SLOGE("scrypt failed");
1510 return -1;
1511 }
1512
Paul Crowley14c8c072018-09-18 13:30:21 -07001513 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001514 SLOGE("Signing failed");
1515 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001516 }
1517
Paul Crowley14c8c072018-09-18 13:30:21 -07001518 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1519 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001520 free(signature);
1521
1522 if (rc) {
1523 SLOGE("scrypt failed");
1524 return -1;
1525 }
1526
1527 return 0;
1528}
1529
Paul Crowley14c8c072018-09-18 13:30:21 -07001530static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1531 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001532 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1533 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001534 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001535 EVP_CIPHER_CTX e_ctx;
1536 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001537 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001538
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001539 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001540 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001541
1542 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001543 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001544 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001545 SLOGE("keymaster_create_key failed");
1546 return -1;
1547 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001548
Paul Crowley14c8c072018-09-18 13:30:21 -07001549 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1550 SLOGE("scrypt failed");
1551 return -1;
1552 }
1553 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001554
Paul Crowley14c8c072018-09-18 13:30:21 -07001555 case KDF_SCRYPT:
1556 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1557 SLOGE("scrypt failed");
1558 return -1;
1559 }
1560 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001561
Paul Crowley14c8c072018-09-18 13:30:21 -07001562 default:
1563 SLOGE("Invalid kdf_type");
1564 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001565 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001566
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001568 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001569 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1570 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571 SLOGE("EVP_EncryptInit failed\n");
1572 return -1;
1573 }
1574 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001575
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001576 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001577 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1578 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001579 SLOGE("EVP_EncryptUpdate failed\n");
1580 return -1;
1581 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001582 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583 SLOGE("EVP_EncryptFinal failed\n");
1584 return -1;
1585 }
1586
Greg Kaiser59ad0182018-02-16 13:01:36 -08001587 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001588 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1589 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001590 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001591
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001592 /* Store the scrypt of the intermediate key, so we can validate if it's a
1593 password error or mount error when things go wrong.
1594 Note there's no need to check for errors, since if this is incorrect, we
1595 simply won't wipe userdata, which is the correct default behavior
1596 */
1597 int N = 1 << crypt_ftr->N_factor;
1598 int r = 1 << crypt_ftr->r_factor;
1599 int p = 1 << crypt_ftr->p_factor;
1600
Paul Crowley14c8c072018-09-18 13:30:21 -07001601 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1602 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001603 sizeof(crypt_ftr->scrypted_intermediate_key));
1604
1605 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001606 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001607 }
1608
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001609 EVP_CIPHER_CTX_cleanup(&e_ctx);
1610
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001611 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001612}
1613
Paul Crowley14c8c072018-09-18 13:30:21 -07001614static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1615 const unsigned char* encrypted_master_key, size_t keysize,
1616 unsigned char* decrypted_master_key, kdf_func kdf,
1617 void* kdf_params, unsigned char** intermediate_key,
1618 size_t* intermediate_key_size) {
1619 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1620 EVP_CIPHER_CTX d_ctx;
1621 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001622
Paul Crowley14c8c072018-09-18 13:30:21 -07001623 /* Turn the password into an intermediate key and IV that can decrypt the
1624 master key */
1625 if (kdf(passwd, salt, ikey, kdf_params)) {
1626 SLOGE("kdf failed");
1627 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001628 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001629
Paul Crowley14c8c072018-09-18 13:30:21 -07001630 /* Initialize the decryption engine */
1631 EVP_CIPHER_CTX_init(&d_ctx);
1632 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1633 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1634 return -1;
1635 }
1636 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1637 /* Decrypt the master key */
1638 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1639 keysize)) {
1640 return -1;
1641 }
1642 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1643 return -1;
1644 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001645
Paul Crowley14c8c072018-09-18 13:30:21 -07001646 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1647 return -1;
1648 }
1649
1650 /* Copy intermediate key if needed by params */
1651 if (intermediate_key && intermediate_key_size) {
1652 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1653 if (*intermediate_key) {
1654 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1655 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1656 }
1657 }
1658
1659 EVP_CIPHER_CTX_cleanup(&d_ctx);
1660
1661 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001662}
1663
Paul Crowley14c8c072018-09-18 13:30:21 -07001664static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001665 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001666 *kdf = scrypt_keymaster;
1667 *kdf_params = ftr;
1668 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001669 *kdf = scrypt;
1670 *kdf_params = ftr;
1671 } else {
1672 *kdf = pbkdf2;
1673 *kdf_params = NULL;
1674 }
1675}
1676
Paul Crowley14c8c072018-09-18 13:30:21 -07001677static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1678 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1679 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001680 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001681 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001682 int ret;
1683
1684 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001685 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1686 decrypted_master_key, kdf, kdf_params, intermediate_key,
1687 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001688 if (ret != 0) {
1689 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001690 }
1691
1692 return ret;
1693}
1694
Paul Crowley14c8c072018-09-18 13:30:21 -07001695static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1696 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001697 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001698
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001699 /* Get some random bits for a key and salt */
1700 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1701 return -1;
1702 }
1703 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1704 return -1;
1705 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001706
1707 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301708 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001709}
1710
Hyangseok Chae79b03ff2020-02-27 18:21:50 +09001711static void ensure_subdirectory_unmounted(const char *prefix) {
1712 std::vector<std::string> umount_points;
1713 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1714 if (!mnts) {
1715 SLOGW("could not read mount files");
1716 return;
1717 }
1718
1719 //Find sudirectory mount point
1720 mntent* mentry;
1721 std::string top_directory(prefix);
1722 if (!android::base::EndsWith(prefix, "/")) {
1723 top_directory = top_directory + "/";
1724 }
1725 while ((mentry = getmntent(mnts.get())) != nullptr) {
1726 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1727 continue;
1728 }
1729
1730 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1731 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1732 umount_points.push_back(mentry->mnt_dir);
1733 }
1734 }
1735
1736 //Sort by path length to umount longest path first
1737 std::sort(std::begin(umount_points), std::end(umount_points),
1738 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1739
1740 for (std::string& mount_point : umount_points) {
1741 umount(mount_point.c_str());
1742 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1743 }
1744}
1745
Paul Crowley73be12d2020-02-03 12:22:03 -08001746static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001747 int i, err, rc;
Hyangseok Chae79b03ff2020-02-27 18:21:50 +09001748
1749 // Subdirectory mount will cause a failure of umount.
1750 ensure_subdirectory_unmounted(mountpoint);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301751#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001752
1753 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001754 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001755 if (umount(mountpoint) == 0) {
1756 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001757 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001758
1759 if (errno == EINVAL) {
1760 /* EINVAL is returned if the directory is not a mountpoint,
1761 * i.e. there is no filesystem mounted there. So just get out.
1762 */
1763 break;
1764 }
1765
1766 err = errno;
1767
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301768 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001769 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301770 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001771 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001772 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301773 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001774 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001775 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001776 }
1777 }
1778
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301779 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001780 }
1781
1782 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001783 SLOGD("unmounting %s succeeded\n", mountpoint);
1784 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001785 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001786 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1787 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1788 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001789 }
1790
1791 return rc;
1792}
1793
Paul Crowley14c8c072018-09-18 13:30:21 -07001794static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001795 // NOTE: post_fs_data results in init calling back around to vold, so all
1796 // callers to this method must be async
1797
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001798 /* Do the prep of the /data filesystem */
1799 property_set("vold.post_fs_data_done", "0");
1800 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001801 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001802
Ken Sumrallc5872692013-05-14 15:26:31 -07001803 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001804 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001805 /* We timed out to prep /data in time. Continue wait. */
1806 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001807 }
Wei Wang42e38102017-06-07 10:46:12 -07001808 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001809}
1810
Paul Crowley14c8c072018-09-18 13:30:21 -07001811static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001812 // Mark the footer as bad
1813 struct crypt_mnt_ftr crypt_ftr;
1814 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1815 SLOGE("Failed to get crypto footer - panic");
1816 return;
1817 }
1818
1819 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1820 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1821 SLOGE("Failed to set crypto footer - panic");
1822 return;
1823 }
1824}
1825
Paul Crowley14c8c072018-09-18 13:30:21 -07001826static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001827 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001828 SLOGE("Failed to mount tmpfs on data - panic");
1829 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001830 }
1831
1832 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1833 SLOGE("Failed to trigger post fs data - panic");
1834 return;
1835 }
1836
1837 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1838 SLOGE("Failed to trigger restart min framework - panic");
1839 return;
1840 }
1841}
1842
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001843/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001844static int cryptfs_restart_internal(int restart_main) {
Yifan Hong804afe12019-02-07 12:56:47 -08001845 std::string crypto_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301846#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001847 std::string blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301848#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001849 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001850 static int restart_successful = 0;
1851
1852 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001853 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001854 SLOGE("Encrypted filesystem not validated, aborting");
1855 return -1;
1856 }
1857
1858 if (restart_successful) {
1859 SLOGE("System already restarted with encrypted disk, aborting");
1860 return -1;
1861 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001862
Paul Lawrencef4faa572014-01-29 13:31:03 -08001863 if (restart_main) {
1864 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001865 * start all services in one of these classes: core, early_hal, hal,
1866 * main and late_start. To get to the minimal UI for PIN entry, we
1867 * need to start core, early_hal, hal and main. When we want to
1868 * shutdown the framework again, we need to stop most of the services in
1869 * these classes, but only those services that were started after
1870 * /data was mounted. This excludes critical services like vold and
1871 * ueventd, which need to keep running. We could possible stop
1872 * even fewer services, but because we want services to pick up APEX
1873 * libraries from the real /data, restarting is better, as it makes
1874 * these devices consistent with FBE devices and lets them use the
1875 * most recent code.
1876 *
1877 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001878 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001879 * We then restart the class core, hal, main, and also the class
1880 * late_start.
1881 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001882 * At the moment, I've only put a few things in late_start that I know
1883 * are not needed to bring up the framework, and that also cause problems
1884 * with unmounting the tmpfs /data, but I hope to add add more services
1885 * to the late_start class as we optimize this to decrease the delay
1886 * till the user is asked for the password to the filesystem.
1887 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001888
Martijn Coenenf629b002019-04-24 10:41:11 +02001889 /* The init files are setup to stop the right set of services when
1890 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001891 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001892 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001893 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001894
Paul Lawrencef4faa572014-01-29 13:31:03 -08001895 /* Ugh, shutting down the framework is not synchronous, so until it
1896 * can be fixed, this horrible hack will wait a moment for it all to
1897 * shut down before proceeding. Without it, some devices cannot
1898 * restart the graphics services.
1899 */
1900 sleep(2);
1901 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001902
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903 /* Now that the framework is shutdown, we should be able to umount()
1904 * the tmpfs filesystem, and mount the real one.
1905 */
1906
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301907#if defined(CONFIG_HW_DISK_ENCRYPTION)
1908#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1909 if (is_ice_enabled()) {
Yifan Hong804afe12019-02-07 12:56:47 -08001910 get_crypt_info(nullptr, &blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301911 if (set_ice_param(START_ENCDEC)) {
1912 SLOGE("Failed to set ICE data");
1913 return -1;
1914 }
1915 }
1916#else
Yifan Hong804afe12019-02-07 12:56:47 -08001917 blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1918 if (blkdev.empty()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301919 SLOGE("fs_crypto_blkdev not set\n");
1920 return -1;
1921 }
1922 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1923#endif
1924#else
Yifan Hong804afe12019-02-07 12:56:47 -08001925 crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1926 if (crypto_blkdev.empty()) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001927 SLOGE("fs_crypto_blkdev not set\n");
1928 return -1;
1929 }
1930
Paul Crowley14c8c072018-09-18 13:30:21 -07001931 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301932#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001933 /* If ro.crypto.readonly is set to 1, mount the decrypted
1934 * filesystem readonly. This is used when /data is mounted by
1935 * recovery mode.
1936 */
1937 char ro_prop[PROPERTY_VALUE_MAX];
1938 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001939 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001940 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1941 if (entry != nullptr) {
1942 entry->flags |= MS_RDONLY;
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001943 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001944 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001945
Ken Sumralle5032c42012-04-01 23:58:44 -07001946 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001947 int retries = RETRY_MOUNT_ATTEMPTS;
1948 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001949
1950 /*
1951 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1952 * partitions in the fsck domain.
1953 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001954 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001955 SLOGE("Failed to setexeccon");
1956 return -1;
1957 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001958 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301959#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001960 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev.data(), 0,
Paul Lawrence67f90442020-06-12 08:12:48 -07001961 needs_cp, false)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301962#else
Yifan Hong804afe12019-02-07 12:56:47 -08001963 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev.data(), 0,
Steven Laver60b2b8d2020-06-19 08:37:05 -07001964 needs_cp, false)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301965#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001966 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1967 /* TODO: invoke something similar to
1968 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1969 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301970#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001971 SLOGI("Failed to mount %s because it is busy - waiting", blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301972#else
Yifan Hong804afe12019-02-07 12:56:47 -08001973 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301974#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001975 if (--retries) {
1976 sleep(RETRY_MOUNT_DELAY_SECONDS);
1977 } else {
1978 /* Let's hope that a reboot clears away whatever is keeping
1979 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001980 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001981 }
1982 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301983#ifdef CONFIG_HW_DISK_ENCRYPTION
1984 if (--retries) {
1985 sleep(RETRY_MOUNT_DELAY_SECONDS);
1986 } else {
1987 SLOGE("Failed to mount decrypted data");
1988 cryptfs_set_corrupt();
1989 cryptfs_trigger_restart_min_framework();
1990 SLOGI("Started framework to offer wipe");
1991 return -1;
1992 }
1993#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001994 SLOGE("Failed to mount decrypted data");
1995 cryptfs_set_corrupt();
1996 cryptfs_trigger_restart_min_framework();
1997 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001998 if (setexeccon(NULL)) {
1999 SLOGE("Failed to setexeccon");
2000 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002001 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302002#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002003 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002004 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002005 if (setexeccon(NULL)) {
2006 SLOGE("Failed to setexeccon");
2007 return -1;
2008 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002009
Ken Sumralle5032c42012-04-01 23:58:44 -07002010 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002011 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09002012 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07002013
2014 /* startup service classes main and late_start */
2015 property_set("vold.decrypt", "trigger_restart_framework");
2016 SLOGD("Just triggered restart_framework\n");
2017
2018 /* Give it a few moments to get started */
2019 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302020#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002021 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302022#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002023
Ken Sumrall0cc16632011-01-18 20:32:26 -08002024 if (rc == 0) {
2025 restart_successful = 1;
2026 }
2027
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002028 return rc;
2029}
2030
Paul Crowley14c8c072018-09-18 13:30:21 -07002031int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002032 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07002033 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002034 SLOGE("cryptfs_restart not valid for file encryption:");
2035 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002036 }
2037
Paul Lawrencef4faa572014-01-29 13:31:03 -08002038 /* Call internal implementation forcing a restart of main service group */
2039 return cryptfs_restart_internal(1);
2040}
2041
Paul Crowley14c8c072018-09-18 13:30:21 -07002042static int do_crypto_complete(const char* mount_point) {
2043 struct crypt_mnt_ftr crypt_ftr;
2044 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002045
Paul Crowley14c8c072018-09-18 13:30:21 -07002046 property_get("ro.crypto.state", encrypted_state, "");
2047 if (strcmp(encrypted_state, "encrypted")) {
2048 SLOGE("not running with encryption, aborting");
2049 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08002050 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002051
Paul Crowley14c8c072018-09-18 13:30:21 -07002052 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07002053 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002054 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2055 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002056
Paul Crowley14c8c072018-09-18 13:30:21 -07002057 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002058 std::string key_loc;
2059 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002060
Paul Crowley14c8c072018-09-18 13:30:21 -07002061 /*
2062 * Only report this error if key_loc is a file and it exists.
2063 * If the device was never encrypted, and /data is not mountable for
2064 * some reason, returning 1 should prevent the UI from presenting the
2065 * a "enter password" screen, or worse, a "press button to wipe the
2066 * device" screen.
2067 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002068 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002069 SLOGE("master key file does not exist, aborting");
2070 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2071 } else {
2072 SLOGE("Error getting crypt footer and key\n");
2073 return CRYPTO_COMPLETE_BAD_METADATA;
2074 }
2075 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002076
Paul Crowley14c8c072018-09-18 13:30:21 -07002077 // Test for possible error flags
2078 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2079 SLOGE("Encryption process is partway completed\n");
2080 return CRYPTO_COMPLETE_PARTIAL;
2081 }
2082
2083 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2084 SLOGE("Encryption process was interrupted but cannot continue\n");
2085 return CRYPTO_COMPLETE_INCONSISTENT;
2086 }
2087
2088 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
2089 SLOGE("Encryption is successful but data is corrupt\n");
2090 return CRYPTO_COMPLETE_CORRUPT;
2091 }
2092
2093 /* We passed the test! We shall diminish, and return to the west */
2094 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002095}
2096
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302097#ifdef CONFIG_HW_DISK_ENCRYPTION
2098static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2099 const char *passwd, const char *mount_point, const char *label)
2100{
Bill Peckham0db11972018-10-10 10:25:42 -07002101 /* Allocate enough space for a 256 bit key, but we may use less */
2102 unsigned char decrypted_master_key[32];
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05302103 std::string crypto_blkdev_hw;
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002104 std::string crypto_blkdev;
Yifan Hong804afe12019-02-07 12:56:47 -08002105 std::string real_blkdev;
Bill Peckham0db11972018-10-10 10:25:42 -07002106 unsigned int orig_failed_decrypt_count;
2107 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302108
Bill Peckham0db11972018-10-10 10:25:42 -07002109 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2110 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302111
Yifan Hong804afe12019-02-07 12:56:47 -08002112 get_crypt_info(nullptr, &real_blkdev);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302113
Bill Peckham0db11972018-10-10 10:25:42 -07002114 int key_index = 0;
2115 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2116 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2117 if (key_index < 0) {
2118 rc = crypt_ftr->failed_decrypt_count;
2119 goto errout;
2120 }
2121 else {
2122 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302123#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Neeraj Soni73b46952019-09-12 16:47:27 +05302124 if (create_crypto_blk_dev_hw(crypt_ftr, (unsigned char*)&key_index,
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05302125 real_blkdev.c_str(), &crypto_blkdev_hw, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002126 SLOGE("Error creating decrypted block device");
2127 rc = -1;
2128 goto errout;
2129 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302130#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002131 } else {
2132 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002133 real_blkdev.c_str(), &crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002134 SLOGE("Error creating decrypted block device");
2135 rc = -1;
2136 goto errout;
2137 }
2138 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302139 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302140 }
2141
Bill Peckham0db11972018-10-10 10:25:42 -07002142 if (rc == 0) {
2143 crypt_ftr->failed_decrypt_count = 0;
2144 if (orig_failed_decrypt_count != 0) {
2145 put_crypt_ftr_and_key(crypt_ftr);
2146 }
2147
2148 /* Save the name of the crypto block device
2149 * so we can mount it when restarting the framework. */
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05302150 if (is_ice_enabled()) {
2151#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
2152 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev_hw.c_str());
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002153#endif
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05302154 } else {
2155 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
2156 }
Bill Peckham0db11972018-10-10 10:25:42 -07002157 master_key_saved = 1;
2158 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302159
Bill Peckham0db11972018-10-10 10:25:42 -07002160 errout:
2161 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302162}
2163#endif
2164
Paul Crowley14c8c072018-09-18 13:30:21 -07002165static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2166 const char* mount_point, const char* label) {
2167 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08002168 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002169 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002170 char tmp_mount_point[64];
2171 unsigned int orig_failed_decrypt_count;
2172 int rc;
Paul Crowley14c8c072018-09-18 13:30:21 -07002173 int upgrade = 0;
2174 unsigned char* intermediate_key = 0;
2175 size_t intermediate_key_size = 0;
2176 int N = 1 << crypt_ftr->N_factor;
2177 int r = 1 << crypt_ftr->r_factor;
2178 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302179
Paul Crowley14c8c072018-09-18 13:30:21 -07002180 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2181 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002182
Paul Crowley14c8c072018-09-18 13:30:21 -07002183 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2184 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2185 &intermediate_key_size)) {
2186 SLOGE("Failed to decrypt master key\n");
2187 rc = -1;
2188 goto errout;
2189 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002190 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002191
Tom Cherry4c5bde22019-01-29 14:34:01 -08002192 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002193
Paul Crowley14c8c072018-09-18 13:30:21 -07002194 // Create crypto block device - all (non fatal) code paths
2195 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08002196 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08002197 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002198 SLOGE("Error creating decrypted block device\n");
2199 rc = -1;
2200 goto errout;
2201 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002202
Paul Crowley14c8c072018-09-18 13:30:21 -07002203 /* Work out if the problem is the password or the data */
2204 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002205
Paul Crowley14c8c072018-09-18 13:30:21 -07002206 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2207 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2208 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002209
Paul Crowley14c8c072018-09-18 13:30:21 -07002210 // Does the key match the crypto footer?
2211 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2212 sizeof(scrypted_intermediate_key)) == 0) {
2213 SLOGI("Password matches");
2214 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002215 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002216 /* Try mounting the file system anyway, just in case the problem's with
2217 * the footer, not the key. */
2218 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2219 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08002220 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
2221 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002222 SLOGE("Error temp mounting decrypted block device\n");
2223 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002224
Paul Crowley14c8c072018-09-18 13:30:21 -07002225 rc = ++crypt_ftr->failed_decrypt_count;
2226 put_crypt_ftr_and_key(crypt_ftr);
2227 } else {
2228 /* Success! */
2229 SLOGI("Password did not match but decrypted drive mounted - continue");
2230 umount(tmp_mount_point);
2231 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002232 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002233 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002234
Paul Crowley14c8c072018-09-18 13:30:21 -07002235 if (rc == 0) {
2236 crypt_ftr->failed_decrypt_count = 0;
2237 if (orig_failed_decrypt_count != 0) {
2238 put_crypt_ftr_and_key(crypt_ftr);
2239 }
2240
2241 /* Save the name of the crypto block device
2242 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08002243 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07002244
2245 /* Also save a the master key so we can reencrypted the key
2246 * the key when we want to change the password on it. */
2247 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2248 saved_mount_point = strdup(mount_point);
2249 master_key_saved = 1;
2250 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2251 rc = 0;
2252
2253 // Upgrade if we're not using the latest KDF.
Satya Tangirala23452c12021-03-22 23:29:15 -07002254 if (crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002255 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2256 upgrade = 1;
Paul Crowley14c8c072018-09-18 13:30:21 -07002257 }
2258
2259 if (upgrade) {
2260 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002261 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002262 if (!rc) {
2263 rc = put_crypt_ftr_and_key(crypt_ftr);
2264 }
2265 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2266
2267 // Do not fail even if upgrade failed - machine is bootable
2268 // Note that if this code is ever hit, there is a *serious* problem
2269 // since KDFs should never fail. You *must* fix the kdf before
2270 // proceeding!
2271 if (rc) {
2272 SLOGW(
2273 "Upgrade failed with error %d,"
2274 " but continuing with previous state",
2275 rc);
2276 rc = 0;
2277 }
2278 }
2279 }
2280
2281errout:
2282 if (intermediate_key) {
2283 memset(intermediate_key, 0, intermediate_key_size);
2284 free(intermediate_key);
2285 }
2286 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002287}
2288
Ken Sumrall29d8da82011-05-18 17:20:07 -07002289/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002290 * Called by vold when it's asked to mount an encrypted external
2291 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002292 * as any metadata is been stored in a separate, small partition. We
2293 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002294 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002295int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08002296 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08002297 auto crypto_type = get_crypto_type();
2298 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08002299 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08002300 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002301 return -1;
2302 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002303 uint64_t nr_sec = 0;
2304 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002305 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002306 return -1;
2307 }
2308
Jeff Sharkey9c484982015-03-31 10:35:33 -07002309 struct crypt_mnt_ftr ext_crypt_ftr;
2310 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2311 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08002312 ext_crypt_ftr.keysize = crypto_type.get_keysize();
2313 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002314 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002315 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002316 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002317 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2318 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002319
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002320 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
2321 real_blkdev, out_crypto_blkdev, label, flags);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002322}
2323
Paul Crowley14c8c072018-09-18 13:30:21 -07002324int cryptfs_crypto_complete(void) {
2325 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002326}
2327
Paul Crowley14c8c072018-09-18 13:30:21 -07002328int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002329 char encrypted_state[PROPERTY_VALUE_MAX];
2330 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002331 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2332 SLOGE(
2333 "encrypted fs already validated or not running with encryption,"
2334 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002335 return -1;
2336 }
2337
2338 if (get_crypt_ftr_and_key(crypt_ftr)) {
2339 SLOGE("Error getting crypt footer and key");
2340 return -1;
2341 }
2342
2343 return 0;
2344}
2345
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302346#ifdef CONFIG_HW_DISK_ENCRYPTION
2347int cryptfs_check_passwd_hw(const char* passwd)
2348{
2349 struct crypt_mnt_ftr crypt_ftr;
2350 int rc;
2351 unsigned char master_key[KEY_LEN_BYTES];
2352
2353 /* get key */
2354 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2355 SLOGE("Error getting crypt footer and key");
2356 return -1;
2357 }
2358
2359 /*
2360 * in case of manual encryption (from GUI), the encryption is done with
2361 * default password
2362 */
2363 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2364 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2365 * which was created with actual password before reboot.
2366 */
2367 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2368 if (rc) {
2369 SLOGE("password doesn't match");
2370 rc = ++crypt_ftr.failed_decrypt_count;
2371 put_crypt_ftr_and_key(&crypt_ftr);
2372 return rc;
2373 }
2374
2375 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2376 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2377
2378 if (rc) {
2379 SLOGE("Default password did not match on reboot encryption");
2380 return rc;
2381 }
2382
2383 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2384 put_crypt_ftr_and_key(&crypt_ftr);
2385 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2386 if (rc) {
2387 SLOGE("Could not change password on reboot encryption");
2388 return rc;
2389 }
2390 } else
2391 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2392 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2393
2394 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2395 cryptfs_clear_password();
2396 password = strdup(passwd);
2397 struct timespec now;
2398 clock_gettime(CLOCK_BOOTTIME, &now);
2399 password_expiry_time = now.tv_sec + password_max_age_seconds;
2400 }
2401
2402 return rc;
2403}
2404#endif
2405
Paul Crowley14c8c072018-09-18 13:30:21 -07002406int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002407 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002408 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002409 SLOGE("cryptfs_check_passwd not valid for file encryption");
2410 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002411 }
2412
Paul Lawrencef4faa572014-01-29 13:31:03 -08002413 struct crypt_mnt_ftr crypt_ftr;
2414 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002415
Paul Lawrencef4faa572014-01-29 13:31:03 -08002416 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002417 if (rc) {
2418 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002419 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002420 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002421
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302422#ifdef CONFIG_HW_DISK_ENCRYPTION
2423 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2424 return cryptfs_check_passwd_hw(passwd);
2425#endif
2426
Paul Crowley14c8c072018-09-18 13:30:21 -07002427 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002428 if (rc) {
2429 SLOGE("Password did not match");
2430 return rc;
2431 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002432
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002433 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2434 // Here we have a default actual password but a real password
2435 // we must test against the scrypted value
2436 // First, we must delete the crypto block device that
2437 // test_mount_encrypted_fs leaves behind as a side effect
2438 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002439 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2440 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002441 if (rc) {
2442 SLOGE("Default password did not match on reboot encryption");
2443 return rc;
2444 }
2445
2446 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2447 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302448 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002449 if (rc) {
2450 SLOGE("Could not change password on reboot encryption");
2451 return rc;
2452 }
2453 }
2454
2455 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002456 cryptfs_clear_password();
2457 password = strdup(passwd);
2458 struct timespec now;
2459 clock_gettime(CLOCK_BOOTTIME, &now);
2460 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002461 }
2462
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002463 return rc;
2464}
2465
Paul Crowley14c8c072018-09-18 13:30:21 -07002466int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002467 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002468 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002469 char encrypted_state[PROPERTY_VALUE_MAX];
2470 int rc;
2471
2472 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002473 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002474 SLOGE("device not encrypted, aborting");
2475 return -2;
2476 }
2477
2478 if (!master_key_saved) {
2479 SLOGE("encrypted fs not yet mounted, aborting");
2480 return -1;
2481 }
2482
2483 if (!saved_mount_point) {
2484 SLOGE("encrypted fs failed to save mount point, aborting");
2485 return -1;
2486 }
2487
Ken Sumrall160b4d62013-04-22 12:15:39 -07002488 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002489 SLOGE("Error getting crypt footer and key\n");
2490 return -1;
2491 }
2492
2493 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2494 /* If the device has no password, then just say the password is valid */
2495 rc = 0;
2496 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302497#ifdef CONFIG_HW_DISK_ENCRYPTION
2498 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2499 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2500 rc = 0;
2501 else
2502 rc = -1;
2503 } else {
2504 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2505 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2506 /* They match, the password is correct */
2507 rc = 0;
2508 } else {
2509 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2510 sleep(1);
2511 rc = 1;
2512 }
2513 }
2514#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002515 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002516 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2517 /* They match, the password is correct */
2518 rc = 0;
2519 } else {
2520 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2521 sleep(1);
2522 rc = 1;
2523 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302524#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002525 }
2526
2527 return rc;
2528}
2529
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002530/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002531 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002532 * Presumably, at a minimum, the caller will update the
2533 * filesystem size and crypto_type_name after calling this function.
2534 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002535static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002536 off64_t off;
2537
2538 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002539 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002540 ftr->major_version = CURRENT_MAJOR_VERSION;
2541 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002542 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002543 ftr->keysize = get_crypto_type().get_keysize();
Satya Tangirala23452c12021-03-22 23:29:15 -07002544 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002545
Kenny Rootc4c70f12013-06-14 12:11:38 -07002546 get_device_scrypt_params(ftr);
2547
Ken Sumrall160b4d62013-04-22 12:15:39 -07002548 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2549 if (get_crypt_ftr_info(NULL, &off) == 0) {
2550 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002551 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002552 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002553
2554 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002555}
2556
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002557#define FRAMEWORK_BOOT_WAIT 60
2558
Paul Crowleyb64933a2017-10-31 08:25:55 -07002559static int vold_unmountAll(void) {
2560 VolumeManager* vm = VolumeManager::Instance();
2561 return vm->unmountAll();
2562}
2563
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002564int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002565 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002566 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002567 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002568 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002569 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002570 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002571 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002572 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002573 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002574 int num_vols;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002575 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002576 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302577#ifdef CONFIG_HW_DISK_ENCRYPTION
2578 unsigned char newpw[32];
2579 int key_index = 0;
2580#endif
2581 int index = 0;
Kalesh Singh98062dc2021-02-22 15:10:45 -05002582
2583 /* Get a wakelock as this may take a while, and we don't want the
2584 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2585 * wants to keep the screen on, it can grab a full wakelock.
2586 */
2587 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
2588 auto wl = android::wakelock::WakeLock::tryGet(lockid);
2589 if (!wl.has_value()) {
2590 return android::UNEXPECTED_NULL;
2591 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302592
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002593 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Eric Biggersc01995e2020-11-03 14:11:00 -08002594 if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002595 if (!check_ftr_sha(&crypt_ftr)) {
2596 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2597 put_crypt_ftr_and_key(&crypt_ftr);
2598 goto error_unencrypted;
2599 }
2600
2601 /* Doing a reboot-encryption*/
2602 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2603 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2604 rebootEncryption = true;
2605 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002606 } else {
2607 // We don't want to accidentally reference invalid data.
2608 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002609 }
2610
2611 property_get("ro.crypto.state", encrypted_state, "");
Eric Biggersc01995e2020-11-03 14:11:00 -08002612 if (!strcmp(encrypted_state, "encrypted")) {
Paul Lawrence87999172014-02-20 12:21:31 -08002613 SLOGE("Device is already running encrypted, aborting");
2614 goto error_unencrypted;
2615 }
2616
Tom Cherry4c5bde22019-01-29 14:34:01 -08002617 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002618
Ken Sumrall3ed82362011-01-28 23:31:16 -08002619 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002620 uint64_t nr_sec;
2621 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002622 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002623 goto error_unencrypted;
2624 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002625
2626 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002627 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002628 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002629 fs_size_sec = get_fs_size(real_blkdev.c_str());
2630 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002631
Paul Lawrence87999172014-02-20 12:21:31 -08002632 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002633
2634 if (fs_size_sec > max_fs_size_sec) {
2635 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2636 goto error_unencrypted;
2637 }
2638 }
2639
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002640 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002641 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002642 */
2643 property_set("vold.decrypt", "trigger_shutdown_framework");
2644 SLOGD("Just asked init to shut down class main\n");
2645
Jeff Sharkey9c484982015-03-31 10:35:33 -07002646 /* Ask vold to unmount all devices that it manages */
2647 if (vold_unmountAll()) {
2648 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002649 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002650
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002651 /* no_ui means we are being called from init, not settings.
2652 Now we always reboot from settings, so !no_ui means reboot
2653 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002654 if (!no_ui) {
2655 /* Try fallback, which is to reboot and try there */
2656 onlyCreateHeader = true;
2657 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2658 if (breadcrumb == 0) {
2659 SLOGE("Failed to create breadcrumb file");
2660 goto error_shutting_down;
2661 }
2662 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002663 }
2664
2665 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002666 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002667 /* Now that /data is unmounted, we need to mount a tmpfs
2668 * /data, set a property saying we're doing inplace encryption,
2669 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002670 */
xzj7e38a3a2018-10-12 10:17:11 +08002671 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002672 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002673 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002674 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002675 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002676 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002677
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002678 /* restart the framework. */
2679 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002680 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002681
Ken Sumrall92736ef2012-10-17 20:57:14 -07002682 /* Ugh, shutting down the framework is not synchronous, so until it
2683 * can be fixed, this horrible hack will wait a moment for it all to
2684 * shut down before proceeding. Without it, some devices cannot
2685 * restart the graphics services.
2686 */
2687 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002688 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002689
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002690 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002691 /* Initialize a crypt_mnt_ftr for the partition */
Eric Biggersc01995e2020-11-03 14:11:00 -08002692 if (!rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002693 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2694 goto error_shutting_down;
2695 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002696
Tom Cherry4c5bde22019-01-29 14:34:01 -08002697 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002698 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002699 } else {
2700 crypt_ftr.fs_size = nr_sec;
2701 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002702 /* At this point, we are in an inconsistent state. Until we successfully
2703 complete encryption, a reboot will leave us broken. So mark the
2704 encryption failed in case that happens.
2705 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002706 if (onlyCreateHeader) {
2707 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2708 } else {
2709 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2710 }
Paul Lawrence87999172014-02-20 12:21:31 -08002711 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302712#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002713 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2714 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302715#else
Paul Crowley220567c2020-02-07 12:45:20 -08002716 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002717 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302718#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002719
Paul Lawrence87999172014-02-20 12:21:31 -08002720 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002721 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2722 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002723 SLOGE("Cannot create encrypted master key\n");
2724 goto error_shutting_down;
2725 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002726
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002727 /* Replace scrypted intermediate key if we are preparing for a reboot */
2728 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002729 unsigned char fake_master_key[MAX_KEY_LEN];
2730 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002731 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002732 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002733 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002734 }
2735
Paul Lawrence87999172014-02-20 12:21:31 -08002736 /* Write the key to the end of the partition */
2737 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002738
Paul Lawrence87999172014-02-20 12:21:31 -08002739 /* If any persistent data has been remembered, save it.
2740 * If none, create a valid empty table and save that.
2741 */
2742 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002743 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2744 if (pdata) {
2745 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2746 persist_data = pdata;
2747 }
Paul Lawrence87999172014-02-20 12:21:31 -08002748 }
2749 if (persist_data) {
2750 save_persistent_data();
2751 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002752 }
2753
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302754 /* When encryption triggered from settings, encryption starts after reboot.
2755 So set the encryption key when the actual encryption starts.
2756 */
2757#ifdef CONFIG_HW_DISK_ENCRYPTION
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002758 if (!rebootEncryption)
2759 clear_hw_device_encryption_key();
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302760
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002761 if (get_keymaster_hw_fde_passwd(
2762 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2763 newpw, crypt_ftr.salt, &crypt_ftr))
2764 key_index = set_hw_device_encryption_key(
2765 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2766 (char*)crypt_ftr.crypto_type_name);
2767 else
2768 key_index = set_hw_device_encryption_key((const char*)newpw,
2769 (char*) crypt_ftr.crypto_type_name);
2770 if (key_index < 0)
2771 goto error_shutting_down;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302772
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002773 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2774 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302775#endif
2776
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002777 if (onlyCreateHeader) {
2778 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002779 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302780 } else {
2781 /* Do extra work for a better UX when doing the long inplace encryption */
2782 /* Now that /data is unmounted, we need to mount a tmpfs
2783 * /data, set a property saying we're doing inplace encryption,
2784 * and restart the framework.
2785 */
2786 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2787 goto error_shutting_down;
2788 }
2789 /* Tells the framework that inplace encryption is starting */
2790 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002791
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302792 /* restart the framework. */
2793 /* Create necessary paths on /data */
2794 prep_data_fs();
2795
2796 /* Ugh, shutting down the framework is not synchronous, so until it
2797 * can be fixed, this horrible hack will wait a moment for it all to
2798 * shut down before proceeding. Without it, some devices cannot
2799 * restart the graphics services.
2800 */
2801 sleep(2);
2802
Ajay Dudani87701e22014-09-17 21:02:52 -07002803 /* startup service classes main and late_start */
2804 property_set("vold.decrypt", "trigger_restart_min_framework");
2805 SLOGD("Just triggered restart_min_framework\n");
2806
2807 /* OK, the framework is restarted and will soon be showing a
2808 * progress bar. Time to setup an encrypted mapping, and
2809 * either write a new filesystem, or encrypt in place updating
2810 * the progress bar as we work.
2811 */
2812 }
2813
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002814 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302815#ifdef CONFIG_HW_DISK_ENCRYPTION
2816 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302817#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002818 crypto_blkdev = real_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302819#else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002820 create_crypto_blk_dev_hw(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302821 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302822#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302823 else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002824 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302825 CRYPTO_BLOCK_DEVICE, 0);
2826#else
Paul Crowley81796e92020-02-07 11:27:49 -08002827 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002828 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302829#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002830
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302831#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2832 if (set_ice_param(START_ENC)) {
2833 SLOGE("Failed to set ICE data");
2834 goto error_shutting_down;
2835 }
2836#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002837 if (!rc) {
Eric Biggersf038c5f2020-11-03 14:11:02 -08002838 if (encrypt_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size, true)) {
2839 crypt_ftr.encrypted_upto = crypt_ftr.fs_size;
2840 rc = 0;
2841 } else {
Paul Lawrence87999172014-02-20 12:21:31 -08002842 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002843 }
Eric Biggers88f993b2020-11-03 14:11:00 -08002844 /* Undo the dm-crypt mapping whether we succeed or not */
2845 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002846 }
2847
Paul Crowley14c8c072018-09-18 13:30:21 -07002848 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002849 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002850 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002851
Paul Lawrence6bfed202014-07-28 12:47:22 -07002852 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002853
Eric Biggersc01995e2020-11-03 14:11:00 -08002854 char value[PROPERTY_VALUE_MAX];
2855 property_get("ro.crypto.state", value, "");
2856 if (!strcmp(value, "")) {
2857 /* default encryption - continue first boot sequence */
2858 property_set("ro.crypto.state", "encrypted");
2859 property_set("ro.crypto.type", "block");
Kalesh Singh98062dc2021-02-22 15:10:45 -05002860 wl.reset();
Eric Biggersc01995e2020-11-03 14:11:00 -08002861 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2862 // Bring up cryptkeeper that will check the password and set it
2863 property_set("vold.decrypt", "trigger_shutdown_framework");
2864 sleep(2);
2865 property_set("vold.encrypt_progress", "");
2866 cryptfs_trigger_restart_min_framework();
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002867 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002868 cryptfs_check_passwd(DEFAULT_PASSWORD);
2869 cryptfs_restart_internal(1);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002870 }
Eric Biggersc01995e2020-11-03 14:11:00 -08002871 return 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002872 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002873 sleep(2); /* Give the UI a chance to show 100% progress */
2874 cryptfs_reboot(RebootType::reboot);
Paul Lawrence87999172014-02-20 12:21:31 -08002875 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002876 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002877 char value[PROPERTY_VALUE_MAX];
2878
Ken Sumrall319369a2012-06-27 16:30:18 -07002879 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002880 if (!strcmp(value, "1")) {
2881 /* wipe data if encryption failed */
2882 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002883 std::string err;
2884 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002885 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002886 if (!write_bootloader_message(options, &err)) {
2887 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002888 }
Josh Gaofec44372017-08-28 13:22:55 -07002889 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002890 } else {
2891 /* set property to trigger dialog */
2892 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002893 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002894 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002895 }
2896
Ken Sumrall3ed82362011-01-28 23:31:16 -08002897 /* hrm, the encrypt step claims success, but the reboot failed.
2898 * This should not happen.
2899 * Set the property and return. Hope the framework can deal with it.
2900 */
2901 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002902 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002903
2904error_unencrypted:
2905 property_set("vold.encrypt_progress", "error_not_encrypted");
2906 return -1;
2907
2908error_shutting_down:
2909 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2910 * but the framework is stopped and not restarted to show the error, so it's up to
2911 * vold to restart the system.
2912 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002913 SLOGE(
2914 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2915 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002916 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002917
2918 /* shouldn't get here */
2919 property_set("vold.encrypt_progress", "error_shutting_down");
2920 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002921}
2922
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002923int cryptfs_enable(int type, const char* passwd, int no_ui) {
2924 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002925}
2926
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002927int cryptfs_enable_default(int no_ui) {
2928 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002929}
2930
Bill Peckham0db11972018-10-10 10:25:42 -07002931int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002932 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002933 SLOGE("cryptfs_changepw not valid for file encryption");
2934 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002935 }
2936
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002937 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002938 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002939
2940 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002941 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002942 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002943 return -1;
2944 }
2945
Paul Lawrencef4faa572014-01-29 13:31:03 -08002946 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2947 SLOGE("Invalid crypt_type %d", crypt_type);
2948 return -1;
2949 }
2950
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002951 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002952 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002953 SLOGE("Error getting crypt footer and key");
2954 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002955 }
2956
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302957#ifdef CONFIG_HW_DISK_ENCRYPTION
2958 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2959 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
2960 else {
2961 crypt_ftr.crypt_type = crypt_type;
2962
2963 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
2964 DEFAULT_PASSWORD : newpw,
2965 crypt_ftr.salt,
2966 saved_master_key,
2967 crypt_ftr.master_key,
2968 &crypt_ftr, false);
2969 if (rc) {
2970 SLOGE("Encrypt master key failed: %d", rc);
2971 return -1;
2972 }
2973 /* save the key */
2974 put_crypt_ftr_and_key(&crypt_ftr);
2975
2976 return 0;
2977 }
2978#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08002979 crypt_ftr.crypt_type = crypt_type;
2980
Paul Crowley14c8c072018-09-18 13:30:21 -07002981 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07002982 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
2983 false);
JP Abgrall933216c2015-02-11 13:44:32 -08002984 if (rc) {
2985 SLOGE("Encrypt master key failed: %d", rc);
2986 return -1;
2987 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002988 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002989 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002990
2991 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302992#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002993}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002994
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302995#ifdef CONFIG_HW_DISK_ENCRYPTION
2996int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
2997{
2998 struct crypt_mnt_ftr crypt_ftr;
2999 int rc;
3000 int previous_type;
3001
3002 /* get key */
3003 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3004 SLOGE("Error getting crypt footer and key");
3005 return -1;
3006 }
3007
3008 previous_type = crypt_ftr.crypt_type;
3009 int rc1;
3010 unsigned char tmp_curpw[32] = {0};
3011 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3012 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3013 crypt_ftr.salt, &crypt_ftr);
3014
3015 crypt_ftr.crypt_type = crypt_type;
3016
3017 int ret, rc2;
3018 unsigned char tmp_newpw[32] = {0};
3019
3020 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3021 DEFAULT_PASSWORD : newpw , tmp_newpw,
3022 crypt_ftr.salt, &crypt_ftr);
3023
3024 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3025 ret = update_hw_device_encryption_key(
3026 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3027 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3028 (char*)crypt_ftr.crypto_type_name);
3029 if (ret) {
3030 SLOGE("Error updating device encryption hardware key ret %d", ret);
3031 return -1;
3032 } else {
3033 SLOGI("Encryption hardware key updated");
3034 }
3035 }
3036
3037 /* save the key */
3038 put_crypt_ftr_and_key(&crypt_ftr);
3039 return 0;
3040}
3041#endif
3042
Rubin Xu85c01f92014-10-13 12:49:54 +01003043static unsigned int persist_get_max_entries(int encrypted) {
3044 struct crypt_mnt_ftr crypt_ftr;
3045 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003046
3047 /* If encrypted, use the values from the crypt_ftr, otherwise
3048 * use the values for the current spec.
3049 */
3050 if (encrypted) {
3051 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003052 /* Something is wrong, assume no space for entries */
3053 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003054 }
3055 dsize = crypt_ftr.persist_data_size;
3056 } else {
3057 dsize = CRYPT_PERSIST_DATA_SIZE;
3058 }
3059
Rubin Xud78181b2018-10-09 16:13:38 +01003060 if (dsize > sizeof(struct crypt_persist_data)) {
3061 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3062 } else {
3063 return 0;
3064 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003065}
3066
Paul Crowley14c8c072018-09-18 13:30:21 -07003067static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003068 unsigned int i;
3069
3070 if (persist_data == NULL) {
3071 return -1;
3072 }
3073 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3074 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3075 /* We found it! */
3076 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3077 return 0;
3078 }
3079 }
3080
3081 return -1;
3082}
3083
Paul Crowley14c8c072018-09-18 13:30:21 -07003084static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003085 unsigned int i;
3086 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003087 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003088
3089 if (persist_data == NULL) {
3090 return -1;
3091 }
3092
Rubin Xu85c01f92014-10-13 12:49:54 +01003093 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003094
3095 num = persist_data->persist_valid_entries;
3096
3097 for (i = 0; i < num; i++) {
3098 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3099 /* We found an existing entry, update it! */
3100 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3101 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3102 return 0;
3103 }
3104 }
3105
3106 /* We didn't find it, add it to the end, if there is room */
3107 if (persist_data->persist_valid_entries < max_persistent_entries) {
3108 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3109 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3110 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3111 persist_data->persist_valid_entries++;
3112 return 0;
3113 }
3114
3115 return -1;
3116}
3117
Rubin Xu85c01f92014-10-13 12:49:54 +01003118/**
3119 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3120 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3121 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003122int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003123 std::string key_ = key;
3124 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003125
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003126 std::string parsed_field;
3127 unsigned parsed_index;
3128
3129 std::string::size_type split = key_.find_last_of('_');
3130 if (split == std::string::npos) {
3131 parsed_field = key_;
3132 parsed_index = 0;
3133 } else {
3134 parsed_field = key_.substr(0, split);
3135 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003136 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003137
3138 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003139}
3140
3141/*
3142 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3143 * remaining entries starting from index will be deleted.
3144 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3145 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3146 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3147 *
3148 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003149static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003150 unsigned int i;
3151 unsigned int j;
3152 unsigned int num;
3153
3154 if (persist_data == NULL) {
3155 return PERSIST_DEL_KEY_ERROR_OTHER;
3156 }
3157
3158 num = persist_data->persist_valid_entries;
3159
Paul Crowley14c8c072018-09-18 13:30:21 -07003160 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003161 // Filter out to-be-deleted entries in place.
3162 for (i = 0; i < num; i++) {
3163 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3164 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3165 j++;
3166 }
3167 }
3168
3169 if (j < num) {
3170 persist_data->persist_valid_entries = j;
3171 // Zeroise the remaining entries
3172 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3173 return PERSIST_DEL_KEY_OK;
3174 } else {
3175 // Did not find an entry matching the given fieldname
3176 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3177 }
3178}
3179
Paul Crowley14c8c072018-09-18 13:30:21 -07003180static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003181 unsigned int i;
3182 unsigned int count;
3183
3184 if (persist_data == NULL) {
3185 return -1;
3186 }
3187
3188 count = 0;
3189 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3190 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3191 count++;
3192 }
3193 }
3194
3195 return count;
3196}
3197
Ken Sumrall160b4d62013-04-22 12:15:39 -07003198/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003199int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003200 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003201 SLOGE("Cannot get field when file encrypted");
3202 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003203 }
3204
Ken Sumrall160b4d62013-04-22 12:15:39 -07003205 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003206 /* CRYPTO_GETFIELD_OK is success,
3207 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3208 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3209 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003210 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003211 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3212 int i;
3213 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003214
3215 if (persist_data == NULL) {
3216 load_persistent_data();
3217 if (persist_data == NULL) {
3218 SLOGE("Getfield error, cannot load persistent data");
3219 goto out;
3220 }
3221 }
3222
Rubin Xu85c01f92014-10-13 12:49:54 +01003223 // Read value from persistent entries. If the original value is split into multiple entries,
3224 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003225 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003226 // 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 -07003227 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003228 // value too small
3229 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3230 goto out;
3231 }
3232 rc = CRYPTO_GETFIELD_OK;
3233
3234 for (i = 1; /* break explicitly */; i++) {
3235 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003236 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003237 // If the fieldname is very long, we stop as soon as it begins to overflow the
3238 // maximum field length. At this point we have in fact fully read out the original
3239 // value because cryptfs_setfield would not allow fields with longer names to be
3240 // written in the first place.
3241 break;
3242 }
3243 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003244 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3245 // value too small.
3246 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3247 goto out;
3248 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003249 } else {
3250 // Exhaust all entries.
3251 break;
3252 }
3253 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003254 } else {
3255 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003256 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003257 }
3258
3259out:
3260 return rc;
3261}
3262
3263/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003264int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003265 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003266 SLOGE("Cannot set field when file encrypted");
3267 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003268 }
3269
Ken Sumrall160b4d62013-04-22 12:15:39 -07003270 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003271 /* 0 is success, negative values are error */
3272 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003273 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003274 unsigned int field_id;
3275 char temp_field[PROPERTY_KEY_MAX];
3276 unsigned int num_entries;
3277 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003278
3279 if (persist_data == NULL) {
3280 load_persistent_data();
3281 if (persist_data == NULL) {
3282 SLOGE("Setfield error, cannot load persistent data");
3283 goto out;
3284 }
3285 }
3286
3287 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003288 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003289 encrypted = 1;
3290 }
3291
Rubin Xu85c01f92014-10-13 12:49:54 +01003292 // Compute the number of entries required to store value, each entry can store up to
3293 // (PROPERTY_VALUE_MAX - 1) chars
3294 if (strlen(value) == 0) {
3295 // Empty value also needs one entry to store.
3296 num_entries = 1;
3297 } else {
3298 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3299 }
3300
3301 max_keylen = strlen(fieldname);
3302 if (num_entries > 1) {
3303 // Need an extra "_%d" suffix.
3304 max_keylen += 1 + log10(num_entries);
3305 }
3306 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3307 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003308 goto out;
3309 }
3310
Rubin Xu85c01f92014-10-13 12:49:54 +01003311 // Make sure we have enough space to write the new value
3312 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3313 persist_get_max_entries(encrypted)) {
3314 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3315 goto out;
3316 }
3317
3318 // Now that we know persist_data has enough space for value, let's delete the old field first
3319 // to make up space.
3320 persist_del_keys(fieldname, 0);
3321
3322 if (persist_set_key(fieldname, value, encrypted)) {
3323 // fail to set key, should not happen as we have already checked the available space
3324 SLOGE("persist_set_key() error during setfield()");
3325 goto out;
3326 }
3327
3328 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003329 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003330
3331 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3332 // fail to set key, should not happen as we have already checked the available space.
3333 SLOGE("persist_set_key() error during setfield()");
3334 goto out;
3335 }
3336 }
3337
Ken Sumrall160b4d62013-04-22 12:15:39 -07003338 /* If we are running encrypted, save the persistent data now */
3339 if (encrypted) {
3340 if (save_persistent_data()) {
3341 SLOGE("Setfield error, cannot save persistent data");
3342 goto out;
3343 }
3344 }
3345
Rubin Xu85c01f92014-10-13 12:49:54 +01003346 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003347
3348out:
3349 return rc;
3350}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003351
3352/* Checks userdata. Attempt to mount the volume if default-
3353 * encrypted.
3354 * On success trigger next init phase and return 0.
3355 * Currently do not handle failure - see TODO below.
3356 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003357int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003358 int crypt_type = cryptfs_get_password_type();
3359 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3360 SLOGE("Bad crypt type - error");
3361 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003362 SLOGD(
3363 "Password is not default - "
3364 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003365 property_set("vold.decrypt", "trigger_restart_min_framework");
3366 return 0;
3367 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3368 SLOGD("Password is default - restarting filesystem");
3369 cryptfs_restart_internal(0);
3370 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003371 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003372 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003373 }
3374
Paul Lawrence6bfed202014-07-28 12:47:22 -07003375 /** Corrupt. Allow us to boot into framework, which will detect bad
3376 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003377 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003378 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003379 return 0;
3380}
3381
3382/* Returns type of the password, default, pattern, pin or password.
3383 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003384int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003385 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003386 SLOGE("cryptfs_get_password_type not valid for file encryption");
3387 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003388 }
3389
Paul Lawrencef4faa572014-01-29 13:31:03 -08003390 struct crypt_mnt_ftr crypt_ftr;
3391
3392 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3393 SLOGE("Error getting crypt footer and key\n");
3394 return -1;
3395 }
3396
Paul Lawrence6bfed202014-07-28 12:47:22 -07003397 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3398 return -1;
3399 }
3400
Paul Lawrencef4faa572014-01-29 13:31:03 -08003401 return crypt_ftr.crypt_type;
3402}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003403
Paul Crowley14c8c072018-09-18 13:30:21 -07003404const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003405 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003406 SLOGE("cryptfs_get_password not valid for file encryption");
3407 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003408 }
3409
Paul Lawrence399317e2014-03-10 13:20:50 -07003410 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003411 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003412 if (now.tv_sec < password_expiry_time) {
3413 return password;
3414 } else {
3415 cryptfs_clear_password();
3416 return 0;
3417 }
3418}
3419
Paul Crowley14c8c072018-09-18 13:30:21 -07003420void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003421 if (password) {
3422 size_t len = strlen(password);
3423 memset(password, 0, len);
3424 free(password);
3425 password = 0;
3426 password_expiry_time = 0;
3427 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003428}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003429
Paul Crowley14c8c072018-09-18 13:30:21 -07003430int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003431 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3432 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003433}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303434
3435int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3436{
3437 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3438 SLOGE("Failed to initialize crypt_ftr");
3439 return -1;
3440 }
3441
3442 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3443 crypt_ftr->salt, crypt_ftr)) {
3444 SLOGE("Cannot create encrypted master key\n");
3445 return -1;
3446 }
3447
3448 //crypt_ftr->keysize = key_length / 8;
3449 return 0;
3450}
3451
3452int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3453 unsigned char* master_key)
3454{
3455 int rc;
3456
3457 unsigned char* intermediate_key = 0;
3458 size_t intermediate_key_size = 0;
3459
3460 if (password == 0 || *password == 0) {
3461 password = DEFAULT_PASSWORD;
3462 }
3463
3464 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3465 &intermediate_key_size);
3466
3467 if (rc) {
3468 SLOGE("Can't calculate intermediate key");
3469 return rc;
3470 }
3471
3472 int N = 1 << ftr->N_factor;
3473 int r = 1 << ftr->r_factor;
3474 int p = 1 << ftr->p_factor;
3475
3476 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3477
3478 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3479 ftr->salt, sizeof(ftr->salt), N, r, p,
3480 scrypted_intermediate_key,
3481 sizeof(scrypted_intermediate_key));
3482
3483 free(intermediate_key);
3484
3485 if (rc) {
3486 SLOGE("Can't scrypt intermediate key");
3487 return rc;
3488 }
3489
3490 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3491 intermediate_key_size);
3492}