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