blob: 95c146122a36fbc26c3e706fcb6cf47728082316 [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
Daniel Normanbe0137a2021-04-28 12:37:42 -070032#include <android-base/logging.h>
Eric Biggersed45ec32019-01-25 10:47:55 -080033#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080034#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080035#include <android-base/stringprintf.h>
Hyangseok Chae79b03ff2020-02-27 18:21:50 +090036#include <android-base/strings.h>
Logan Chiend557d762018-05-02 11:36:45 +080037#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070040#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070043#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070044#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080045#include <log/log.h>
Ken Sumralle550f782013-08-20 13:48:23 -070046#include <logwrap/logwrap.h>
Logan Chiend557d762018-05-02 11:36:45 +080047#include <openssl/evp.h>
48#include <openssl/sha.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080049#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070050#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080051
52#include <ctype.h>
53#include <errno.h>
54#include <fcntl.h>
55#include <inttypes.h>
56#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080057#include <linux/kdev_t.h>
58#include <math.h>
Hyangseok Chae79b03ff2020-02-27 18:21:50 +090059#include <mntent.h>
Logan Chiend557d762018-05-02 11:36:45 +080060#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080063#include <sys/mount.h>
64#include <sys/param.h>
65#include <sys/stat.h>
66#include <sys/types.h>
67#include <sys/wait.h>
68#include <time.h>
69#include <unistd.h>
70
Martijn Coenen26ad7b32020-02-13 16:20:52 +010071#include <chrono>
72#include <thread>
73
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053074#ifdef CONFIG_HW_DISK_ENCRYPTION
Neeraj Soni73b46952019-09-12 16:47:27 +053075#include <linux/dm-ioctl.h>
76#include <sys/ioctl.h>
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053077#include <cryptfs_hw.h>
78#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080079extern "C" {
80#include <crypto_scrypt.h>
81}
Mark Salyzyn3e971272014-01-21 13:27:04 -080082
Eric Biggersed45ec32019-01-25 10:47:55 -080083using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080084using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080085using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080086using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080087using android::vold::KeyBuffer;
Paul Crowleyb3d018a2020-02-12 11:04:05 -080088using android::vold::KeyGeneration;
Daniel Normanbe0137a2021-04-28 12:37:42 -070089using namespace android::vold;
David Andersonb9224732019-05-13 13:02:54 -070090using namespace android::dm;
Paul Crowley298fa322018-10-30 15:59:24 -070091using namespace std::chrono_literals;
92
Paul Crowley73be12d2020-02-03 12:22:03 -080093/* The current cryptfs version */
94#define CURRENT_MAJOR_VERSION 1
95#define CURRENT_MINOR_VERSION 3
96
97#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
98#define CRYPT_PERSIST_DATA_SIZE 0x1000
99
Eric Biggersf038c5f2020-11-03 14:11:02 -0800100#define CRYPT_SECTOR_SIZE 512
101
Paul Crowley73be12d2020-02-03 12:22:03 -0800102#define MAX_CRYPTO_TYPE_NAME_LEN 64
103
104#define MAX_KEY_LEN 48
105#define SALT_LEN 16
106#define SCRYPT_LEN 32
107
108/* definitions of flags in the structure below */
109#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
Eric Biggersc01995e2020-11-03 14:11:00 -0800110#define CRYPT_ENCRYPTION_IN_PROGRESS 0x2 /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800111#define CRYPT_INCONSISTENT_STATE \
112 0x4 /* Set when starting encryption, clear when \
113 exit cleanly, either through success or \
114 correctly marked partial encryption */
115#define CRYPT_DATA_CORRUPT \
116 0x8 /* Set when encryption is fine, but the \
117 underlying volume is corrupt */
118#define CRYPT_FORCE_ENCRYPTION \
119 0x10 /* Set when it is time to encrypt this \
120 volume on boot. Everything in this \
121 structure is set up correctly as \
122 though device is encrypted except \
123 that the master key is encrypted with the \
124 default password. */
125#define CRYPT_FORCE_COMPLETE \
126 0x20 /* Set when the above encryption cycle is \
127 complete. On next cryptkeeper entry, match \
128 the password. If it matches fix the master \
129 key and remove this flag. */
130
131/* Allowed values for type in the structure below */
132#define CRYPT_TYPE_PASSWORD \
133 0 /* master_key is encrypted with a password \
134 * Must be zero to be compatible with pre-L \
135 * devices where type is always password.*/
136#define CRYPT_TYPE_DEFAULT \
137 1 /* master_key is encrypted with default \
138 * password */
139#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
140#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
141#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
142
143#define CRYPT_MNT_MAGIC 0xD0B5B1C4
144#define PERSIST_DATA_MAGIC 0xE950CD44
145
146/* Key Derivation Function algorithms */
147#define KDF_PBKDF2 1
148#define KDF_SCRYPT 2
149/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
150#define KDF_SCRYPT_KEYMASTER 5
151
152/* Maximum allowed keymaster blob size. */
153#define KEYMASTER_BLOB_SIZE 2048
154
155/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
156#define __le8 unsigned char
157
158#if !defined(SHA256_DIGEST_LENGTH)
159#define SHA256_DIGEST_LENGTH 32
160#endif
161
162/* This structure starts 16,384 bytes before the end of a hardware
163 * partition that is encrypted, or in a separate partition. It's location
164 * is specified by a property set in init.<device>.rc.
165 * The structure allocates 48 bytes for a key, but the real key size is
166 * specified in the struct. Currently, the code is hardcoded to use 128
167 * bit keys.
168 * The fields after salt are only valid in rev 1.1 and later stuctures.
169 * Obviously, the filesystem does not include the last 16 kbytes
170 * of the partition if the crypt_mnt_ftr lives at the end of the
171 * partition.
172 */
173
174struct crypt_mnt_ftr {
175 __le32 magic; /* See above */
176 __le16 major_version;
177 __le16 minor_version;
178 __le32 ftr_size; /* in bytes, not including key following */
179 __le32 flags; /* See above */
180 __le32 keysize; /* in bytes */
181 __le32 crypt_type; /* how master_key is encrypted. Must be a
182 * CRYPT_TYPE_XXX value */
183 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
184 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
185 mount, set to 0 on successful mount */
186 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
187 needed to decrypt this
188 partition, null terminated */
189 __le32 spare2; /* ignored */
190 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
191 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
192 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
193 * on device with that info, either the footer of the
194 * real_blkdevice or the metadata partition. */
195
196 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
197 * persistent data table*/
198
199 __le8 kdf_type; /* The key derivation function used. */
200
201 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
202 __le8 N_factor; /* (1 << N) */
203 __le8 r_factor; /* (1 << r) */
204 __le8 p_factor; /* (1 << p) */
Eric Biggersc01995e2020-11-03 14:11:00 -0800205 __le64 encrypted_upto; /* no longer used */
206 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800207
208 /* key_master key, used to sign the derived key which is then used to generate
209 * the intermediate key
210 * This key should be used for no other purposes! We use this key to sign unpadded
211 * data, which is acceptable but only if the key is not reused elsewhere. */
212 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
213 __le32 keymaster_blob_size;
214
215 /* Store scrypt of salted intermediate key. When decryption fails, we can
216 check if this matches, and if it does, we know that the problem is with the
217 drive, and there is no point in asking the user for more passwords.
218
219 Note that if any part of this structure is corrupt, this will not match and
220 we will continue to believe the user entered the wrong password. In that
221 case the only solution is for the user to enter a password enough times to
222 force a wipe.
223
224 Note also that there is no need to worry about migration. If this data is
225 wrong, we simply won't recognise a right password, and will continue to
226 prompt. On the first password change, this value will be populated and
227 then we will be OK.
228 */
229 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
230
231 /* sha of this structure with this element set to zero
232 Used when encrypting on reboot to validate structure before doing something
233 fatal
234 */
235 unsigned char sha256[SHA256_DIGEST_LENGTH];
236};
237
238/* Persistant data that should be available before decryption.
239 * Things like airplane mode, locale and timezone are kept
240 * here and can be retrieved by the CryptKeeper UI to properly
241 * configure the phone before asking for the password
242 * This is only valid if the major and minor version above
243 * is set to 1.1 or higher.
244 *
245 * This is a 4K structure. There are 2 copies, and the code alternates
246 * writing one and then clearing the previous one. The reading
247 * code reads the first valid copy it finds, based on the magic number.
248 * The absolute offset to the first of the two copies is kept in rev 1.1
249 * and higher crypt_mnt_ftr structures.
250 */
251struct crypt_persist_entry {
252 char key[PROPERTY_KEY_MAX];
253 char val[PROPERTY_VALUE_MAX];
254};
255
256/* Should be exactly 4K in size */
257struct crypt_persist_data {
258 __le32 persist_magic;
259 __le32 persist_valid_entries;
260 __le32 persist_spare[30];
261 struct crypt_persist_entry persist_entry[0];
262};
263
264static int wait_and_unmount(const char* mountpoint, bool kill);
265
266typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
267 void* params);
268
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800269#define UNUSED __attribute__((unused))
270
Jason parks70a4b3f2011-01-28 10:10:47 -0600271#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800272
273constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
274constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700275constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800276
277// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700278static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600279
Paul Crowley14c8c072018-09-18 13:30:21 -0700280#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700281
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530282#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700283#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800284
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800285#define CRYPTO_BLOCK_DEVICE "userdata"
286
287#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
288
Ken Sumrall29d8da82011-05-18 17:20:07 -0700289#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700290#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700291
Ken Sumralle919efe2012-09-29 17:07:41 -0700292#define TABLE_LOAD_RETRIES 10
293
Shawn Willden47ba10d2014-09-03 17:07:06 -0600294#define RSA_KEY_SIZE 2048
295#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
296#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600297#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530298#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700299
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700300#define RETRY_MOUNT_ATTEMPTS 10
301#define RETRY_MOUNT_DELAY_SECONDS 1
302
Paul Crowley5afbc622017-11-27 09:42:17 -0800303#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
304
Paul Crowley73473332017-11-21 15:43:51 -0800305static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
306
Greg Kaiser59ad0182018-02-16 13:01:36 -0800307static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700308static char* saved_mount_point;
309static int master_key_saved = 0;
310static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800311
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530312static int previous_type;
313
314#ifdef CONFIG_HW_DISK_ENCRYPTION
315static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
316 unsigned char *ikey, void *params);
317static void convert_key_to_hex_ascii(const unsigned char *master_key,
318 unsigned int keysize, char *master_key_ascii);
319static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
320static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
321 const char *passwd, const char *mount_point, const char *label);
322int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
323 const char *newpw);
324int cryptfs_check_passwd_hw(char *passwd);
325int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
326 unsigned char* master_key);
327
328static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
329 unsigned int keysize, char *master_key_ascii)
330{
331 unsigned int i, a;
332 unsigned char nibble;
333
334 for (i = 0, a = 0; i < keysize; i++, a += 2) {
335 /* For each byte, write out two ascii hex digits */
336 nibble = (master_key[i] >> 4) & 0xf;
337 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
338
339 nibble = master_key[i] & 0xf;
340 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
341 }
342
343 /* Add the null termination */
344 master_key_ascii[a] = '\0';
345}
346
347static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
348 unsigned char* salt,
349 const struct crypt_mnt_ftr *ftr)
350{
351 /* if newpw updated, return 0
352 * if newpw not updated return -1
353 */
354 int rc = -1;
355
356 if (should_use_keymaster()) {
357 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
358 SLOGE("scrypt failed");
359 } else {
360 rc = 0;
361 }
362 }
363
364 return rc;
365}
366
367static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
368{
369 unsigned char newpw[32] = {0};
370 int key_index;
371 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
372 key_index = set_hw_device_encryption_key(passwd,
373 (char*) crypt_ftr->crypto_type_name);
374 else
375 key_index = set_hw_device_encryption_key((const char*)newpw,
376 (char*) crypt_ftr->crypto_type_name);
377 return key_index;
378}
379
380static int verify_and_update_hw_fde_passwd(const char *passwd,
381 struct crypt_mnt_ftr* crypt_ftr)
382{
383 char* new_passwd = NULL;
384 unsigned char newpw[32] = {0};
385 int key_index = -1;
386 int passwd_updated = -1;
387 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
388
389 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
390 if (key_index < 0) {
391 ++crypt_ftr->failed_decrypt_count;
392
393 if (ascii_passwd_updated) {
394 SLOGI("Ascii password was updated");
395 } else {
396 /* Code in else part would execute only once:
397 * When device is upgraded from L->M release.
398 * Once upgraded, code flow should never come here.
399 * L release passed actual password in hex, so try with hex
400 * Each nible of passwd was encoded as a byte, so allocate memory
401 * twice of password len plus one more byte for null termination
402 */
403 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
404 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
405 if (new_passwd == NULL) {
406 SLOGE("System out of memory. Password verification incomplete");
407 goto out;
408 }
409 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
410 } else {
411 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
412 if (new_passwd == NULL) {
413 SLOGE("System out of memory. Password verification incomplete");
414 goto out;
415 }
416 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
417 strlen(passwd), new_passwd);
418 }
419 key_index = set_hw_device_encryption_key((const char*)new_passwd,
420 (char*) crypt_ftr->crypto_type_name);
421 if (key_index >=0) {
422 crypt_ftr->failed_decrypt_count = 0;
423 SLOGI("Hex password verified...will try to update with Ascii value");
424 /* Before updating password, tie that with keymaster to tie with ROT */
425
426 if (get_keymaster_hw_fde_passwd(passwd, newpw,
427 crypt_ftr->salt, crypt_ftr)) {
428 passwd_updated = update_hw_device_encryption_key(new_passwd,
429 passwd, (char*)crypt_ftr->crypto_type_name);
430 } else {
431 passwd_updated = update_hw_device_encryption_key(new_passwd,
432 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
433 }
434
435 if (passwd_updated >= 0) {
436 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
437 SLOGI("Ascii password recorded and updated");
438 } else {
439 SLOGI("Passwd verified, could not update...Will try next time");
440 }
441 } else {
442 ++crypt_ftr->failed_decrypt_count;
443 }
444 free(new_passwd);
445 }
446 } else {
447 if (!ascii_passwd_updated)
448 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
449 }
450out:
451 // update footer before leaving
452 put_crypt_ftr_and_key(crypt_ftr);
453 return key_index;
454}
455#endif
456
Paul Crowley220567c2020-02-07 12:45:20 -0800457constexpr CryptoType aes_128_cbc = CryptoType()
458 .set_config_name("AES-128-CBC")
459 .set_kernel_name("aes-cbc-essiv:sha256")
460 .set_keysize(16);
461
462constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
463
464static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
465 array_length(supported_crypto_types)),
466 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
467 "incompletely constructed.");
468
469static const CryptoType& get_crypto_type() {
470 // We only want to parse this read-only property once. But we need to wait
471 // until the system is initialized before we can read it. So we use a static
472 // scoped within this function to get it only once.
473 static CryptoType crypto_type =
474 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
475 aes_128_cbc, "ro.crypto.fde_algorithm");
476 return crypto_type;
477}
478
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800479const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800480 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800481}
482
Daniel Normanbe0137a2021-04-28 12:37:42 -0700483static bool write_string_to_buf(const std::string& towrite, uint8_t* buffer, uint32_t buffer_size,
484 uint32_t* out_size) {
485 if (!buffer || !out_size) {
486 LOG(ERROR) << "Missing target pointers";
487 return false;
488 }
489 *out_size = towrite.size();
490 if (buffer_size < towrite.size()) {
491 LOG(ERROR) << "Buffer too small " << buffer_size << " < " << towrite.size();
492 return false;
493 }
494 memset(buffer, '\0', buffer_size);
495 std::copy(towrite.begin(), towrite.end(), buffer);
496 return true;
497}
498
499static int keymaster_create_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
500 uint32_t ratelimit, uint8_t* key_buffer,
501 uint32_t key_buffer_size,
502 uint32_t* key_out_size) {
503 if (key_out_size) {
504 *key_out_size = 0;
505 }
506 Keymaster dev;
507 if (!dev) {
508 LOG(ERROR) << "Failed to initiate keymaster session";
509 return -1;
510 }
511 auto keyParams = km::AuthorizationSetBuilder()
512 .RsaSigningKey(rsa_key_size, rsa_exponent)
513 .NoDigestOrPadding()
514 .Authorization(km::TAG_NO_AUTH_REQUIRED)
515 .Authorization(km::TAG_MIN_SECONDS_BETWEEN_OPS, ratelimit);
516 std::string key;
517 if (!dev.generateKey(keyParams, &key)) return -1;
518 if (!write_string_to_buf(key, key_buffer, key_buffer_size, key_out_size)) return -1;
519 return 0;
520}
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700521
522/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700523static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800524 if (ftr->keymaster_blob_size) {
525 SLOGI("Already have key");
526 return 0;
527 }
528
Paul Crowley14c8c072018-09-18 13:30:21 -0700529 int rc = keymaster_create_key_for_cryptfs_scrypt(
530 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
531 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000532 if (rc) {
533 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800534 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000535 ftr->keymaster_blob_size = 0;
536 }
537 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700538 return -1;
539 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000540 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700541}
542
Daniel Normanbe0137a2021-04-28 12:37:42 -0700543static int keymaster_sign_object_for_cryptfs_scrypt(struct crypt_mnt_ftr* ftr, uint32_t ratelimit,
544 const uint8_t* object, const size_t object_size,
545 uint8_t** signature_buffer,
546 size_t* signature_buffer_size) {
547 if (!object || !signature_buffer || !signature_buffer_size) {
548 LOG(ERROR) << __FILE__ << ":" << __LINE__ << ":Invalid argument";
549 return -1;
550 }
551
552 Keymaster dev;
553 if (!dev) {
554 LOG(ERROR) << "Failed to initiate keymaster session";
555 return -1;
556 }
557
558 km::AuthorizationSet outParams;
559 std::string key(reinterpret_cast<const char*>(ftr->keymaster_blob), ftr->keymaster_blob_size);
560 std::string input(reinterpret_cast<const char*>(object), object_size);
561 std::string output;
562 KeymasterOperation op;
563
564 auto paramBuilder = km::AuthorizationSetBuilder().NoDigestOrPadding().Authorization(
565 km::TAG_PURPOSE, km::KeyPurpose::SIGN);
566 while (true) {
567 op = dev.begin(key, paramBuilder, &outParams);
568 if (op.getErrorCode() == km::ErrorCode::KEY_RATE_LIMIT_EXCEEDED) {
569 sleep(ratelimit);
570 continue;
571 } else
572 break;
573 }
574
575 if (!op) {
576 LOG(ERROR) << "Error starting keymaster signature transaction: "
577 << int32_t(op.getErrorCode());
578 return -1;
579 }
580
581 if (op.getUpgradedBlob()) {
582 write_string_to_buf(*op.getUpgradedBlob(), ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
583 &ftr->keymaster_blob_size);
584
585 SLOGD("Upgrading key");
586 if (put_crypt_ftr_and_key(ftr) != 0) {
587 SLOGE("Failed to write upgraded key to disk");
588 return -1;
589 }
590 SLOGD("Key upgraded successfully");
591 }
592
593 if (!op.updateCompletely(input, &output)) {
594 LOG(ERROR) << "Error sending data to keymaster signature transaction: "
595 << int32_t(op.getErrorCode());
596 return -1;
597 }
598
599 if (!op.finish(&output)) {
600 LOG(ERROR) << "Error finalizing keymaster signature transaction: "
601 << int32_t(op.getErrorCode());
602 return -1;
603 }
604
605 *signature_buffer = reinterpret_cast<uint8_t*>(malloc(output.size()));
606 if (*signature_buffer == nullptr) {
607 LOG(ERROR) << "Error allocation buffer for keymaster signature";
608 return -1;
609 }
610 *signature_buffer_size = output.size();
611 std::copy(output.data(), output.data() + output.size(), *signature_buffer);
612
613 return 0;
614}
615
Shawn Willdene17a9c42014-09-08 13:04:08 -0600616/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700617static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
618 const size_t object_size, unsigned char** signature,
619 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600620 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600621 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600622 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600623
Shawn Willdene17a9c42014-09-08 13:04:08 -0600624 // To sign a message with RSA, the message must satisfy two
625 // constraints:
626 //
627 // 1. The message, when interpreted as a big-endian numeric value, must
628 // be strictly less than the public modulus of the RSA key. Note
629 // that because the most significant bit of the public modulus is
630 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
631 // key), an n-bit message with most significant bit 0 always
632 // satisfies this requirement.
633 //
634 // 2. The message must have the same length in bits as the public
635 // modulus of the RSA key. This requirement isn't mathematically
636 // necessary, but is necessary to ensure consistency in
637 // implementations.
638 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600639 case KDF_SCRYPT_KEYMASTER:
640 // This ensures the most significant byte of the signed message
641 // is zero. We could have zero-padded to the left instead, but
642 // this approach is slightly more robust against changes in
643 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600644 // so) because we really should be using a proper deterministic
645 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800646 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600647 SLOGI("Signing safely-padded object");
648 break;
649 default:
650 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000651 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600652 }
Daniel Normanbe0137a2021-04-28 12:37:42 -0700653 return keymaster_sign_object_for_cryptfs_scrypt(ftr, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
654 to_sign_size, signature, signature_size);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600655}
656
Paul Lawrence399317e2014-03-10 13:20:50 -0700657/* Store password when userdata is successfully decrypted and mounted.
658 * Cleared by cryptfs_clear_password
659 *
660 * To avoid a double prompt at boot, we need to store the CryptKeeper
661 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
662 * Since the entire framework is torn down and rebuilt after encryption,
663 * we have to use a daemon or similar to store the password. Since vold
664 * is secured against IPC except from system processes, it seems a reasonable
665 * place to store this.
666 *
667 * password should be cleared once it has been used.
668 *
669 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800670 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700671static char* password = 0;
672static int password_expiry_time = 0;
673static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800674
Paul Crowley14c8c072018-09-18 13:30:21 -0700675enum class RebootType { reboot, recovery, shutdown };
676static void cryptfs_reboot(RebootType rt) {
677 switch (rt) {
678 case RebootType::reboot:
679 property_set(ANDROID_RB_PROPERTY, "reboot");
680 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800681
Paul Crowley14c8c072018-09-18 13:30:21 -0700682 case RebootType::recovery:
683 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
684 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800685
Paul Crowley14c8c072018-09-18 13:30:21 -0700686 case RebootType::shutdown:
687 property_set(ANDROID_RB_PROPERTY, "shutdown");
688 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700689 }
Paul Lawrence87999172014-02-20 12:21:31 -0800690
Ken Sumralladfba362013-06-04 16:37:52 -0700691 sleep(20);
692
693 /* Shouldn't get here, reboot should happen before sleep times out */
694 return;
695}
696
Kenny Rootc4c70f12013-06-14 12:11:38 -0700697/**
698 * Gets the default device scrypt parameters for key derivation time tuning.
699 * The parameters should lead to about one second derivation time for the
700 * given device.
701 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700702static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700703 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000704 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700705
Paul Crowley63c18d32016-02-10 14:02:47 +0000706 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
707 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
708 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
709 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700710 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000711 ftr->N_factor = Nf;
712 ftr->r_factor = rf;
713 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700714}
715
Tom Cherry4c5bde22019-01-29 14:34:01 -0800716static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800717 int fd, block_size;
718 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200719 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800720
Paul Crowley14c8c072018-09-18 13:30:21 -0700721 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800722 SLOGE("Cannot open device to get filesystem size ");
723 return 0;
724 }
725
726 if (lseek64(fd, 1024, SEEK_SET) < 0) {
727 SLOGE("Cannot seek to superblock");
728 return 0;
729 }
730
731 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
732 SLOGE("Cannot read superblock");
733 return 0;
734 }
735
736 close(fd);
737
Daniel Rosenberge82df162014-08-15 22:19:23 +0000738 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
739 SLOGE("Not a valid ext4 superblock");
740 return 0;
741 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800742 block_size = 1024 << sb.s_log_block_size;
743 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200744 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800745
746 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200747 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800748}
749
Tom Cherry4c5bde22019-01-29 14:34:01 -0800750static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
751 for (const auto& entry : fstab_default) {
752 if (!entry.fs_mgr_flags.vold_managed &&
753 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
754 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
755 if (key_loc != nullptr) {
756 *key_loc = entry.key_loc;
757 }
758 if (real_blk_device != nullptr) {
759 *real_blk_device = entry.blk_device;
760 }
761 return;
762 }
763 }
764}
765
Paul Crowley14c8c072018-09-18 13:30:21 -0700766static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
767 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200768 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700769 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700770 char key_loc[PROPERTY_VALUE_MAX];
771 char real_blkdev[PROPERTY_VALUE_MAX];
772 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700773
Paul Crowley14c8c072018-09-18 13:30:21 -0700774 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800775 std::string key_loc;
776 std::string real_blkdev;
777 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700778
Tom Cherry4c5bde22019-01-29 14:34:01 -0800779 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200780 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700781 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
782 * encryption info footer and key, and plenty of bytes to spare for future
783 * growth.
784 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800785 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200786 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700787 cached_data = 1;
788 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800789 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700790 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700791 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800792 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700793 cached_off = 0;
794 cached_data = 1;
795 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700796 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700797
Paul Crowley14c8c072018-09-18 13:30:21 -0700798 if (cached_data) {
799 if (metadata_fname) {
800 *metadata_fname = cached_metadata_fname;
801 }
802 if (off) {
803 *off = cached_off;
804 }
805 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700806 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700807
Paul Crowley14c8c072018-09-18 13:30:21 -0700808 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700809}
810
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800811/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700812static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800813 SHA256_CTX c;
814 SHA256_Init(&c);
815 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
816 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
817 SHA256_Final(crypt_ftr->sha256, &c);
818}
819
Ken Sumralle8744072011-01-18 22:01:55 -0800820/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800821 * update the failed mount count but not change the key.
822 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700823static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
824 int fd;
825 unsigned int cnt;
826 /* starting_off is set to the SEEK_SET offset
827 * where the crypto structure starts
828 */
829 off64_t starting_off;
830 int rc = -1;
831 char* fname = NULL;
832 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800833
Paul Crowley14c8c072018-09-18 13:30:21 -0700834 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800835
Paul Crowley14c8c072018-09-18 13:30:21 -0700836 if (get_crypt_ftr_info(&fname, &starting_off)) {
837 SLOGE("Unable to get crypt_ftr_info\n");
838 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800839 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700840 if (fname[0] != '/') {
841 SLOGE("Unexpected value for crypto key location\n");
842 return -1;
843 }
844 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
845 SLOGE("Cannot open footer file %s for put\n", fname);
846 return -1;
847 }
Ken Sumralle8744072011-01-18 22:01:55 -0800848
Paul Crowley14c8c072018-09-18 13:30:21 -0700849 /* Seek to the start of the crypt footer */
850 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
851 SLOGE("Cannot seek to real block device footer\n");
852 goto errout;
853 }
854
855 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
856 SLOGE("Cannot write real block device footer\n");
857 goto errout;
858 }
859
860 fstat(fd, &statbuf);
861 /* If the keys are kept on a raw block device, do not try to truncate it. */
862 if (S_ISREG(statbuf.st_mode)) {
863 if (ftruncate(fd, 0x4000)) {
864 SLOGE("Cannot set footer file size\n");
865 goto errout;
866 }
867 }
868
869 /* Success! */
870 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800871
872errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700873 close(fd);
874 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800875}
876
Paul Crowley14c8c072018-09-18 13:30:21 -0700877static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800878 struct crypt_mnt_ftr copy;
879 memcpy(&copy, crypt_ftr, sizeof(copy));
880 set_ftr_sha(&copy);
881 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
882}
883
Paul Crowley14c8c072018-09-18 13:30:21 -0700884static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700885 return TEMP_FAILURE_RETRY(read(fd, buff, len));
886}
887
Paul Crowley14c8c072018-09-18 13:30:21 -0700888static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700889 return TEMP_FAILURE_RETRY(write(fd, buff, len));
890}
891
Paul Crowley14c8c072018-09-18 13:30:21 -0700892static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700893 memset(pdata, 0, len);
894 pdata->persist_magic = PERSIST_DATA_MAGIC;
895 pdata->persist_valid_entries = 0;
896}
897
898/* A routine to update the passed in crypt_ftr to the lastest version.
899 * fd is open read/write on the device that holds the crypto footer and persistent
900 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
901 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
902 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700903static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700904 int orig_major = crypt_ftr->major_version;
905 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700906
Kenny Root7434b312013-06-14 11:29:53 -0700907 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700908 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700909 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700910
Kenny Rootc4c70f12013-06-14 12:11:38 -0700911 SLOGW("upgrading crypto footer to 1.1");
912
Paul Crowley14c8c072018-09-18 13:30:21 -0700913 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700914 if (pdata == NULL) {
915 SLOGE("Cannot allocate persisent data\n");
916 return;
917 }
918 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
919
920 /* Need to initialize the persistent data area */
921 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
922 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100923 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700924 return;
925 }
926 /* Write all zeros to the first copy, making it invalid */
927 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
928
929 /* Write a valid but empty structure to the second copy */
930 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
931 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
932
933 /* Update the footer */
934 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
935 crypt_ftr->persist_data_offset[0] = pdata_offset;
936 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
937 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100938 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700939 }
940
Paul Lawrencef4faa572014-01-29 13:31:03 -0800941 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700942 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800943 /* But keep the old kdf_type.
944 * It will get updated later to KDF_SCRYPT after the password has been verified.
945 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700946 crypt_ftr->kdf_type = KDF_PBKDF2;
947 get_device_scrypt_params(crypt_ftr);
948 crypt_ftr->minor_version = 2;
949 }
950
Paul Lawrencef4faa572014-01-29 13:31:03 -0800951 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
952 SLOGW("upgrading crypto footer to 1.3");
953 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
954 crypt_ftr->minor_version = 3;
955 }
956
Kenny Root7434b312013-06-14 11:29:53 -0700957 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
958 if (lseek64(fd, offset, SEEK_SET) == -1) {
959 SLOGE("Cannot seek to crypt footer\n");
960 return;
961 }
962 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700963 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700964}
965
Paul Crowley14c8c072018-09-18 13:30:21 -0700966static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
967 int fd;
968 unsigned int cnt;
969 off64_t starting_off;
970 int rc = -1;
971 char* fname = NULL;
972 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700973
Paul Crowley14c8c072018-09-18 13:30:21 -0700974 if (get_crypt_ftr_info(&fname, &starting_off)) {
975 SLOGE("Unable to get crypt_ftr_info\n");
976 return -1;
977 }
978 if (fname[0] != '/') {
979 SLOGE("Unexpected value for crypto key location\n");
980 return -1;
981 }
982 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
983 SLOGE("Cannot open footer file %s for get\n", fname);
984 return -1;
985 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800986
Paul Crowley14c8c072018-09-18 13:30:21 -0700987 /* Make sure it's 16 Kbytes in length */
988 fstat(fd, &statbuf);
989 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
990 SLOGE("footer file %s is not the expected size!\n", fname);
991 goto errout;
992 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700993
Paul Crowley14c8c072018-09-18 13:30:21 -0700994 /* Seek to the start of the crypt footer */
995 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
996 SLOGE("Cannot seek to real block device footer\n");
997 goto errout;
998 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700999
Paul Crowley14c8c072018-09-18 13:30:21 -07001000 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
1001 SLOGE("Cannot read real block device footer\n");
1002 goto errout;
1003 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001004
Paul Crowley14c8c072018-09-18 13:30:21 -07001005 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
1006 SLOGE("Bad magic for real block device %s\n", fname);
1007 goto errout;
1008 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001009
Paul Crowley14c8c072018-09-18 13:30:21 -07001010 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
1011 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
1012 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
1013 goto errout;
1014 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001015
Paul Crowley14c8c072018-09-18 13:30:21 -07001016 // We risk buffer overflows with oversized keys, so we just reject them.
1017 // 0-sized keys are problematic (essentially by-passing encryption), and
1018 // AES-CBC key wrapping only works for multiples of 16 bytes.
1019 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
1020 (crypt_ftr->keysize > MAX_KEY_LEN)) {
1021 SLOGE(
1022 "Invalid keysize (%u) for block device %s; Must be non-zero, "
1023 "divisible by 16, and <= %d\n",
1024 crypt_ftr->keysize, fname, MAX_KEY_LEN);
1025 goto errout;
1026 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001027
Paul Crowley14c8c072018-09-18 13:30:21 -07001028 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
1029 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
1030 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
1031 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08001032
Paul Crowley14c8c072018-09-18 13:30:21 -07001033 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
1034 * copy on disk before returning.
1035 */
1036 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
1037 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
1038 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001039
Paul Crowley14c8c072018-09-18 13:30:21 -07001040 /* Success! */
1041 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001042
1043errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001044 close(fd);
1045 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001046}
1047
Paul Crowley14c8c072018-09-18 13:30:21 -07001048static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001049 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
1050 crypt_ftr->persist_data_offset[1]) {
1051 SLOGE("Crypt_ftr persist data regions overlap");
1052 return -1;
1053 }
1054
1055 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
1056 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
1057 return -1;
1058 }
1059
1060 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -07001061 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -07001062 CRYPT_FOOTER_OFFSET) {
1063 SLOGE("Persistent data extends past crypto footer");
1064 return -1;
1065 }
1066
1067 return 0;
1068}
1069
Paul Crowley14c8c072018-09-18 13:30:21 -07001070static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001071 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001072 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001073 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07001074 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001075 int found = 0;
1076 int fd;
1077 int ret;
1078 int i;
1079
1080 if (persist_data) {
1081 /* Nothing to do, we've already loaded or initialized it */
1082 return 0;
1083 }
1084
Ken Sumrall160b4d62013-04-22 12:15:39 -07001085 /* If not encrypted, just allocate an empty table and initialize it */
1086 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001087 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -08001088 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001089 if (pdata) {
1090 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1091 persist_data = pdata;
1092 return 0;
1093 }
1094 return -1;
1095 }
1096
Paul Crowley14c8c072018-09-18 13:30:21 -07001097 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001098 return -1;
1099 }
1100
Paul Crowley14c8c072018-09-18 13:30:21 -07001101 if ((crypt_ftr.major_version < 1) ||
1102 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001103 SLOGE("Crypt_ftr version doesn't support persistent data");
1104 return -1;
1105 }
1106
1107 if (get_crypt_ftr_info(&fname, NULL)) {
1108 return -1;
1109 }
1110
1111 ret = validate_persistent_data_storage(&crypt_ftr);
1112 if (ret) {
1113 return -1;
1114 }
1115
Paul Crowley14c8c072018-09-18 13:30:21 -07001116 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001117 if (fd < 0) {
1118 SLOGE("Cannot open %s metadata file", fname);
1119 return -1;
1120 }
1121
Wei Wang4375f1b2017-02-24 17:43:01 -08001122 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -08001123 if (pdata == NULL) {
1124 SLOGE("Cannot allocate memory for persistent data");
1125 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001126 }
1127
1128 for (i = 0; i < 2; i++) {
1129 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
1130 SLOGE("Cannot seek to read persistent data on %s", fname);
1131 goto err2;
1132 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001133 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001134 SLOGE("Error reading persistent data on iteration %d", i);
1135 goto err2;
1136 }
1137 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1138 found = 1;
1139 break;
1140 }
1141 }
1142
1143 if (!found) {
1144 SLOGI("Could not find valid persistent data, creating");
1145 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
1146 }
1147
1148 /* Success */
1149 persist_data = pdata;
1150 close(fd);
1151 return 0;
1152
1153err2:
1154 free(pdata);
1155
1156err:
1157 close(fd);
1158 return -1;
1159}
1160
Paul Crowley14c8c072018-09-18 13:30:21 -07001161static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001162 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001163 struct crypt_persist_data* pdata;
1164 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001165 off64_t write_offset;
1166 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001167 int fd;
1168 int ret;
1169
1170 if (persist_data == NULL) {
1171 SLOGE("No persistent data to save");
1172 return -1;
1173 }
1174
Paul Crowley14c8c072018-09-18 13:30:21 -07001175 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001176 return -1;
1177 }
1178
Paul Crowley14c8c072018-09-18 13:30:21 -07001179 if ((crypt_ftr.major_version < 1) ||
1180 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001181 SLOGE("Crypt_ftr version doesn't support persistent data");
1182 return -1;
1183 }
1184
1185 ret = validate_persistent_data_storage(&crypt_ftr);
1186 if (ret) {
1187 return -1;
1188 }
1189
1190 if (get_crypt_ftr_info(&fname, NULL)) {
1191 return -1;
1192 }
1193
Paul Crowley14c8c072018-09-18 13:30:21 -07001194 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001195 if (fd < 0) {
1196 SLOGE("Cannot open %s metadata file", fname);
1197 return -1;
1198 }
1199
Wei Wang4375f1b2017-02-24 17:43:01 -08001200 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001201 if (pdata == NULL) {
1202 SLOGE("Cannot allocate persistant data");
1203 goto err;
1204 }
1205
1206 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1207 SLOGE("Cannot seek to read persistent data on %s", fname);
1208 goto err2;
1209 }
1210
1211 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001212 SLOGE("Error reading persistent data before save");
1213 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001214 }
1215
1216 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1217 /* The first copy is the curent valid copy, so write to
1218 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001219 write_offset = crypt_ftr.persist_data_offset[1];
1220 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001221 } else {
1222 /* The second copy must be the valid copy, so write to
1223 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001224 write_offset = crypt_ftr.persist_data_offset[0];
1225 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001226 }
1227
1228 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001229 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001230 SLOGE("Cannot seek to write persistent data");
1231 goto err2;
1232 }
1233 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001234 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001235 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001236 SLOGE("Cannot seek to erase previous persistent data");
1237 goto err2;
1238 }
1239 fsync(fd);
1240 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001241 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001242 SLOGE("Cannot write to erase previous persistent data");
1243 goto err2;
1244 }
1245 fsync(fd);
1246 } else {
1247 SLOGE("Cannot write to save persistent data");
1248 goto err2;
1249 }
1250
1251 /* Success */
1252 free(pdata);
1253 close(fd);
1254 return 0;
1255
1256err2:
1257 free(pdata);
1258err:
1259 close(fd);
1260 return -1;
1261}
1262
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263/* Convert a binary key of specified length into an ascii hex string equivalent,
1264 * without the leading 0x and with null termination
1265 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001266static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1267 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001268 unsigned int i, a;
1269 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001270
Paul Crowley14c8c072018-09-18 13:30:21 -07001271 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001272 /* For each byte, write out two ascii hex digits */
1273 nibble = (master_key[i] >> 4) & 0xf;
1274 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001275
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001276 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001277 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001278 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001279
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001280 /* Add the null termination */
1281 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001282}
1283
Eric Biggersed45ec32019-01-25 10:47:55 -08001284/*
1285 * If the ro.crypto.fde_sector_size system property is set, append the
1286 * parameters to make dm-crypt use the specified crypto sector size and round
1287 * the crypto device size down to a crypto sector boundary.
1288 */
David Andersonb9224732019-05-13 13:02:54 -07001289static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001290 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001291 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001292
Eric Biggersed45ec32019-01-25 10:47:55 -08001293 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1294 unsigned int sector_size;
1295
1296 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1297 (sector_size & (sector_size - 1)) != 0) {
1298 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1299 DM_CRYPT_SECTOR_SIZE, value);
1300 return -1;
1301 }
1302
David Andersonb9224732019-05-13 13:02:54 -07001303 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001304
1305 // With this option, IVs will match the sector numbering, instead
1306 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001307 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001308
1309 // Round the crypto device size down to a crypto sector boundary.
1310 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001311 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001312 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001313}
1314
Neeraj Soni73b46952019-09-12 16:47:27 +05301315#if defined(CONFIG_HW_DISK_ENCRYPTION) && !defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1316#define DM_CRYPT_BUF_SIZE 4096
1317
1318static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
1319 memset(io, 0, dataSize);
1320 io->data_size = dataSize;
1321 io->data_start = sizeof(struct dm_ioctl);
1322 io->version[0] = 4;
1323 io->version[1] = 0;
1324 io->version[2] = 0;
1325 io->flags = flags;
1326 if (name) {
1327 strlcpy(io->name, name, sizeof(io->name));
1328 }
1329}
1330
1331static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1332 const unsigned char* master_key, const char* real_blk_name,
1333 const char* name, int fd, const char* extra_params) {
1334 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1335 struct dm_ioctl* io;
1336 struct dm_target_spec* tgt;
1337 char* crypt_params;
1338 // We need two ASCII characters to represent each byte, and need space for
1339 // the '\0' terminator.
1340 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1341 size_t buff_offset;
1342 int i;
1343
1344 io = (struct dm_ioctl*)buffer;
1345
1346 /* Load the mapping table for this device */
1347 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
1348
1349 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1350 io->target_count = 1;
1351 tgt->status = 0;
1352 tgt->sector_start = 0;
1353 tgt->length = crypt_ftr->fs_size;
1354 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1355 buff_offset = crypt_params - buffer;
1356 SLOGI(
1357 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1358 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1359 extra_params);
1360 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1361 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1362 if (is_ice_enabled())
1363 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1364 else
1365 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1366 }
1367 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1368 crypt_ftr->crypto_type_name, master_key_ascii,
1369 real_blk_name, extra_params);
1370
1371 SLOGI("target_type = %s", tgt->target_type);
1372 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1373
1374 crypt_params += strlen(crypt_params) + 1;
1375 crypt_params =
1376 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1377 tgt->next = crypt_params - buffer;
1378
1379 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1380 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1381 break;
1382 }
1383 usleep(500000);
1384 }
1385
1386 if (i == TABLE_LOAD_RETRIES) {
1387 /* We failed to load the table, return an error */
1388 return -1;
1389 } else {
1390 return i + 1;
1391 }
1392}
1393
1394static 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 +05301395 const char* real_blk_name, std::string* crypto_blk_name,
1396 const char* name, uint32_t flags) {
Neeraj Soni73b46952019-09-12 16:47:27 +05301397 char buffer[DM_CRYPT_BUF_SIZE];
1398 struct dm_ioctl* io;
1399 unsigned int minor;
1400 int fd = 0;
1401 int err;
1402 int retval = -1;
1403 int version[3];
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05301404 int load_count = 0;
Neeraj Soni73b46952019-09-12 16:47:27 +05301405 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1406 char progress[PROPERTY_VALUE_MAX] = {0};
1407 const char *extra_params;
1408
1409 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1410 SLOGE("Cannot open device-mapper\n");
1411 goto errout;
1412 }
1413
1414 io = (struct dm_ioctl*)buffer;
1415
1416 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1417 err = ioctl(fd, DM_DEV_CREATE, io);
1418 if (err) {
1419 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1420 goto errout;
1421 }
1422
1423 /* Get the device status, in particular, the name of it's device file */
1424 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1425 if (ioctl(fd, DM_DEV_STATUS, io)) {
1426 SLOGE("Cannot retrieve dm-crypt device status\n");
1427 goto errout;
1428 }
1429 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05301430 snprintf(crypto_blk_name->data(), MAXPATHLEN, "/dev/block/dm-%u", minor);
Neeraj Soni73b46952019-09-12 16:47:27 +05301431
1432 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1433 /* Set fde_enabled if either FDE completed or in-progress */
1434 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1435 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1436 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1437 if (is_ice_enabled()) {
1438 extra_params = "fde_enabled ice allow_encrypt_override";
1439 } else {
1440 extra_params = "fde_enabled allow_encrypt_override";
1441 }
1442 } else {
1443 extra_params = "fde_enabled allow_encrypt_override";
1444 }
1445 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1446 extra_params);
1447 }
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08001448
Neeraj Soni73b46952019-09-12 16:47:27 +05301449 if (load_count < 0) {
1450 SLOGE("Cannot load dm-crypt mapping table.\n");
1451 goto errout;
1452 } else if (load_count > 1) {
1453 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1454 }
1455
1456 /* Resume this device to activate it */
1457 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1458
1459 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1460 SLOGE("Cannot resume the dm-crypt device\n");
1461 goto errout;
1462 }
1463
1464 /* Ensure the dm device has been created before returning. */
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05301465 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Neeraj Soni73b46952019-09-12 16:47:27 +05301466 // WaitForFile generates a suitable log message
1467 goto errout;
1468 }
1469
1470 /* We made it here with no errors. Woot! */
1471 retval = 0;
1472
1473errout:
1474 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1475
1476 return retval;
1477}
1478#endif
1479
Paul Crowley5afbc622017-11-27 09:42:17 -08001480static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001481 const char* real_blk_name, std::string* crypto_blk_name,
1482 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001483 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001484
David Andersonb9224732019-05-13 13:02:54 -07001485 // We need two ASCII characters to represent each byte, and need space for
1486 // the '\0' terminator.
1487 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1488 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001489
David Andersonb9224732019-05-13 13:02:54 -07001490 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1491 (const char*)crypt_ftr->crypto_type_name,
1492 master_key_ascii, 0, real_blk_name, 0);
1493 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001494
Paul Crowley5afbc622017-11-27 09:42:17 -08001495 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001496 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001497 }
David Andersonb9224732019-05-13 13:02:54 -07001498 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001499 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001500 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001501 }
David Andersonb9224732019-05-13 13:02:54 -07001502
1503 DmTable table;
1504 table.AddTarget(std::move(target));
1505
1506 int load_count = 1;
1507 while (load_count < TABLE_LOAD_RETRIES) {
1508 if (dm.CreateDevice(name, table)) {
1509 break;
1510 }
1511 load_count++;
1512 }
1513
1514 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001515 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001516 return -1;
1517 }
1518 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001519 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1520 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521
Paul Crowley81796e92020-02-07 11:27:49 -08001522 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001523 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1524 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001525 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001526
Paul Crowley298fa322018-10-30 15:59:24 -07001527 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001528 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowley298fa322018-10-30 15:59:24 -07001529 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001530 return -1;
Paul Crowley298fa322018-10-30 15:59:24 -07001531 }
David Andersonb9224732019-05-13 13:02:54 -07001532 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001533}
1534
David Andersonb9224732019-05-13 13:02:54 -07001535static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001536 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001537 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001538 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1539 // to delete the device fails with EBUSY; for now, work around this by retrying.
1540 int tries = 5;
1541 while (tries-- > 0) {
1542 ret = dm.DeleteDevice(name);
1543 if (ret || errno != EBUSY) {
1544 break;
1545 }
1546 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1547 strerror(errno));
1548 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1549 }
1550 if (!ret) {
1551 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001552 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001553 }
David Andersonb9224732019-05-13 13:02:54 -07001554 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001555}
1556
Paul Crowley14c8c072018-09-18 13:30:21 -07001557static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1558 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001559 SLOGI("Using pbkdf2 for cryptfs KDF");
1560
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001562 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1563 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001564}
1565
Paul Crowley14c8c072018-09-18 13:30:21 -07001566static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001567 SLOGI("Using scrypt for cryptfs KDF");
1568
Paul Crowley14c8c072018-09-18 13:30:21 -07001569 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001570
1571 int N = 1 << ftr->N_factor;
1572 int r = 1 << ftr->r_factor;
1573 int p = 1 << ftr->p_factor;
1574
1575 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001576 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001577 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001578
Paul Crowley14c8c072018-09-18 13:30:21 -07001579 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001580}
1581
Paul Crowley14c8c072018-09-18 13:30:21 -07001582static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1583 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001584 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1585
1586 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001587 size_t signature_size;
1588 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001589 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001590
1591 int N = 1 << ftr->N_factor;
1592 int r = 1 << ftr->r_factor;
1593 int p = 1 << ftr->p_factor;
1594
Paul Crowley14c8c072018-09-18 13:30:21 -07001595 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001596 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001597
1598 if (rc) {
1599 SLOGE("scrypt failed");
1600 return -1;
1601 }
1602
Paul Crowley14c8c072018-09-18 13:30:21 -07001603 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001604 SLOGE("Signing failed");
1605 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001606 }
1607
Paul Crowley14c8c072018-09-18 13:30:21 -07001608 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1609 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001610 free(signature);
1611
1612 if (rc) {
1613 SLOGE("scrypt failed");
1614 return -1;
1615 }
1616
1617 return 0;
1618}
1619
Paul Crowley14c8c072018-09-18 13:30:21 -07001620static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1621 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001622 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1623 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001624 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001625 EVP_CIPHER_CTX e_ctx;
1626 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001627 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001628
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001629 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001630 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001631
1632 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001633 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001634 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001635 SLOGE("keymaster_create_key failed");
1636 return -1;
1637 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001638
Paul Crowley14c8c072018-09-18 13:30:21 -07001639 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1640 SLOGE("scrypt failed");
1641 return -1;
1642 }
1643 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001644
Paul Crowley14c8c072018-09-18 13:30:21 -07001645 case KDF_SCRYPT:
1646 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1647 SLOGE("scrypt failed");
1648 return -1;
1649 }
1650 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001651
Paul Crowley14c8c072018-09-18 13:30:21 -07001652 default:
1653 SLOGE("Invalid kdf_type");
1654 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001655 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001656
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001657 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001658 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001659 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1660 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001661 SLOGE("EVP_EncryptInit failed\n");
1662 return -1;
1663 }
1664 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001665
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001666 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001667 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1668 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001669 SLOGE("EVP_EncryptUpdate failed\n");
1670 return -1;
1671 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001672 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001673 SLOGE("EVP_EncryptFinal failed\n");
1674 return -1;
1675 }
1676
Greg Kaiser59ad0182018-02-16 13:01:36 -08001677 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001678 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1679 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001680 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001681
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001682 /* Store the scrypt of the intermediate key, so we can validate if it's a
1683 password error or mount error when things go wrong.
1684 Note there's no need to check for errors, since if this is incorrect, we
1685 simply won't wipe userdata, which is the correct default behavior
1686 */
1687 int N = 1 << crypt_ftr->N_factor;
1688 int r = 1 << crypt_ftr->r_factor;
1689 int p = 1 << crypt_ftr->p_factor;
1690
Paul Crowley14c8c072018-09-18 13:30:21 -07001691 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1692 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001693 sizeof(crypt_ftr->scrypted_intermediate_key));
1694
1695 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001696 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001697 }
1698
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001699 EVP_CIPHER_CTX_cleanup(&e_ctx);
1700
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001701 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001702}
1703
Paul Crowley14c8c072018-09-18 13:30:21 -07001704static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1705 const unsigned char* encrypted_master_key, size_t keysize,
1706 unsigned char* decrypted_master_key, kdf_func kdf,
1707 void* kdf_params, unsigned char** intermediate_key,
1708 size_t* intermediate_key_size) {
1709 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1710 EVP_CIPHER_CTX d_ctx;
1711 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001712
Paul Crowley14c8c072018-09-18 13:30:21 -07001713 /* Turn the password into an intermediate key and IV that can decrypt the
1714 master key */
1715 if (kdf(passwd, salt, ikey, kdf_params)) {
1716 SLOGE("kdf failed");
1717 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001718 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001719
Paul Crowley14c8c072018-09-18 13:30:21 -07001720 /* Initialize the decryption engine */
1721 EVP_CIPHER_CTX_init(&d_ctx);
1722 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1723 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1724 return -1;
1725 }
1726 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1727 /* Decrypt the master key */
1728 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1729 keysize)) {
1730 return -1;
1731 }
1732 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1733 return -1;
1734 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001735
Paul Crowley14c8c072018-09-18 13:30:21 -07001736 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1737 return -1;
1738 }
1739
1740 /* Copy intermediate key if needed by params */
1741 if (intermediate_key && intermediate_key_size) {
1742 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1743 if (*intermediate_key) {
1744 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1745 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1746 }
1747 }
1748
1749 EVP_CIPHER_CTX_cleanup(&d_ctx);
1750
1751 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001752}
1753
Paul Crowley14c8c072018-09-18 13:30:21 -07001754static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001755 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001756 *kdf = scrypt_keymaster;
1757 *kdf_params = ftr;
1758 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001759 *kdf = scrypt;
1760 *kdf_params = ftr;
1761 } else {
1762 *kdf = pbkdf2;
1763 *kdf_params = NULL;
1764 }
1765}
1766
Paul Crowley14c8c072018-09-18 13:30:21 -07001767static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1768 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1769 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001770 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001771 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001772 int ret;
1773
1774 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001775 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1776 decrypted_master_key, kdf, kdf_params, intermediate_key,
1777 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001778 if (ret != 0) {
1779 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001780 }
1781
1782 return ret;
1783}
1784
Paul Crowley14c8c072018-09-18 13:30:21 -07001785static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1786 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001787 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001788
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001789 /* Get some random bits for a key and salt */
1790 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1791 return -1;
1792 }
1793 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1794 return -1;
1795 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001796
1797 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301798 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001799}
1800
Hyangseok Chae79b03ff2020-02-27 18:21:50 +09001801static void ensure_subdirectory_unmounted(const char *prefix) {
1802 std::vector<std::string> umount_points;
1803 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1804 if (!mnts) {
1805 SLOGW("could not read mount files");
1806 return;
1807 }
1808
1809 //Find sudirectory mount point
1810 mntent* mentry;
1811 std::string top_directory(prefix);
1812 if (!android::base::EndsWith(prefix, "/")) {
1813 top_directory = top_directory + "/";
1814 }
1815 while ((mentry = getmntent(mnts.get())) != nullptr) {
1816 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1817 continue;
1818 }
1819
1820 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1821 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1822 umount_points.push_back(mentry->mnt_dir);
1823 }
1824 }
1825
1826 //Sort by path length to umount longest path first
1827 std::sort(std::begin(umount_points), std::end(umount_points),
1828 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1829
1830 for (std::string& mount_point : umount_points) {
1831 umount(mount_point.c_str());
1832 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1833 }
1834}
1835
Paul Crowley73be12d2020-02-03 12:22:03 -08001836static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001837 int i, err, rc;
Hyangseok Chae79b03ff2020-02-27 18:21:50 +09001838
1839 // Subdirectory mount will cause a failure of umount.
1840 ensure_subdirectory_unmounted(mountpoint);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301841#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001842
1843 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001844 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001845 if (umount(mountpoint) == 0) {
1846 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001847 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001848
1849 if (errno == EINVAL) {
1850 /* EINVAL is returned if the directory is not a mountpoint,
1851 * i.e. there is no filesystem mounted there. So just get out.
1852 */
1853 break;
1854 }
1855
1856 err = errno;
1857
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301858 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001859 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301860 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001861 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001862 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301863 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001864 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001865 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001866 }
1867 }
1868
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301869 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001870 }
1871
1872 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001873 SLOGD("unmounting %s succeeded\n", mountpoint);
1874 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001875 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001876 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1877 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1878 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001879 }
1880
1881 return rc;
1882}
1883
Paul Crowley14c8c072018-09-18 13:30:21 -07001884static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001885 // NOTE: post_fs_data results in init calling back around to vold, so all
1886 // callers to this method must be async
1887
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001888 /* Do the prep of the /data filesystem */
1889 property_set("vold.post_fs_data_done", "0");
1890 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001891 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001892
Ken Sumrallc5872692013-05-14 15:26:31 -07001893 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001894 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001895 /* We timed out to prep /data in time. Continue wait. */
1896 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001897 }
Wei Wang42e38102017-06-07 10:46:12 -07001898 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001899}
1900
Paul Crowley14c8c072018-09-18 13:30:21 -07001901static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001902 // Mark the footer as bad
1903 struct crypt_mnt_ftr crypt_ftr;
1904 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1905 SLOGE("Failed to get crypto footer - panic");
1906 return;
1907 }
1908
1909 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1910 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1911 SLOGE("Failed to set crypto footer - panic");
1912 return;
1913 }
1914}
1915
Paul Crowley14c8c072018-09-18 13:30:21 -07001916static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001917 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001918 SLOGE("Failed to mount tmpfs on data - panic");
1919 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001920 }
1921
1922 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1923 SLOGE("Failed to trigger post fs data - panic");
1924 return;
1925 }
1926
1927 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1928 SLOGE("Failed to trigger restart min framework - panic");
1929 return;
1930 }
1931}
1932
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001933/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001934static int cryptfs_restart_internal(int restart_main) {
Yifan Hong804afe12019-02-07 12:56:47 -08001935 std::string crypto_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301936#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001937 std::string blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301938#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001939 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001940 static int restart_successful = 0;
1941
1942 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001943 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001944 SLOGE("Encrypted filesystem not validated, aborting");
1945 return -1;
1946 }
1947
1948 if (restart_successful) {
1949 SLOGE("System already restarted with encrypted disk, aborting");
1950 return -1;
1951 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001952
Paul Lawrencef4faa572014-01-29 13:31:03 -08001953 if (restart_main) {
1954 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001955 * start all services in one of these classes: core, early_hal, hal,
1956 * main and late_start. To get to the minimal UI for PIN entry, we
1957 * need to start core, early_hal, hal and main. When we want to
1958 * shutdown the framework again, we need to stop most of the services in
1959 * these classes, but only those services that were started after
1960 * /data was mounted. This excludes critical services like vold and
1961 * ueventd, which need to keep running. We could possible stop
1962 * even fewer services, but because we want services to pick up APEX
1963 * libraries from the real /data, restarting is better, as it makes
1964 * these devices consistent with FBE devices and lets them use the
1965 * most recent code.
1966 *
1967 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001968 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001969 * We then restart the class core, hal, main, and also the class
1970 * late_start.
1971 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001972 * At the moment, I've only put a few things in late_start that I know
1973 * are not needed to bring up the framework, and that also cause problems
1974 * with unmounting the tmpfs /data, but I hope to add add more services
1975 * to the late_start class as we optimize this to decrease the delay
1976 * till the user is asked for the password to the filesystem.
1977 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001978
Martijn Coenenf629b002019-04-24 10:41:11 +02001979 /* The init files are setup to stop the right set of services when
1980 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001981 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001982 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001983 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001984
Paul Lawrencef4faa572014-01-29 13:31:03 -08001985 /* Ugh, shutting down the framework is not synchronous, so until it
1986 * can be fixed, this horrible hack will wait a moment for it all to
1987 * shut down before proceeding. Without it, some devices cannot
1988 * restart the graphics services.
1989 */
1990 sleep(2);
1991 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001992
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001993 /* Now that the framework is shutdown, we should be able to umount()
1994 * the tmpfs filesystem, and mount the real one.
1995 */
1996
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301997#if defined(CONFIG_HW_DISK_ENCRYPTION)
1998#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1999 if (is_ice_enabled()) {
Yifan Hong804afe12019-02-07 12:56:47 -08002000 get_crypt_info(nullptr, &blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302001 if (set_ice_param(START_ENCDEC)) {
2002 SLOGE("Failed to set ICE data");
2003 return -1;
2004 }
2005 }
2006#else
Yifan Hong804afe12019-02-07 12:56:47 -08002007 blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
2008 if (blkdev.empty()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302009 SLOGE("fs_crypto_blkdev not set\n");
2010 return -1;
2011 }
2012 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
2013#endif
2014#else
Yifan Hong804afe12019-02-07 12:56:47 -08002015 crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
2016 if (crypto_blkdev.empty()) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08002017 SLOGE("fs_crypto_blkdev not set\n");
2018 return -1;
2019 }
2020
Paul Crowley14c8c072018-09-18 13:30:21 -07002021 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302022#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08002023 /* If ro.crypto.readonly is set to 1, mount the decrypted
2024 * filesystem readonly. This is used when /data is mounted by
2025 * recovery mode.
2026 */
2027 char ro_prop[PROPERTY_VALUE_MAX];
2028 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002029 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002030 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2031 if (entry != nullptr) {
2032 entry->flags |= MS_RDONLY;
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07002033 }
Doug Zongker6fd57712013-12-17 09:43:23 -08002034 }
JP Abgrall62c7af32014-06-16 13:01:23 -07002035
Ken Sumralle5032c42012-04-01 23:58:44 -07002036 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002037 int retries = RETRY_MOUNT_ATTEMPTS;
2038 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002039
2040 /*
2041 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
2042 * partitions in the fsck domain.
2043 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08002044 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002045 SLOGE("Failed to setexeccon");
2046 return -1;
2047 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07002048 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302049#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08002050 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev.data(), 0,
Paul Lawrence67f90442020-06-12 08:12:48 -07002051 needs_cp, false)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302052#else
Yifan Hong804afe12019-02-07 12:56:47 -08002053 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev.data(), 0,
Steven Laver60b2b8d2020-06-19 08:37:05 -07002054 needs_cp, false)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302055#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002056 if (mount_rc == FS_MGR_DOMNT_BUSY) {
2057 /* TODO: invoke something similar to
2058 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
2059 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302060#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08002061 SLOGI("Failed to mount %s because it is busy - waiting", blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302062#else
Yifan Hong804afe12019-02-07 12:56:47 -08002063 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302064#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002065 if (--retries) {
2066 sleep(RETRY_MOUNT_DELAY_SECONDS);
2067 } else {
2068 /* Let's hope that a reboot clears away whatever is keeping
2069 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07002070 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002071 }
2072 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302073#ifdef CONFIG_HW_DISK_ENCRYPTION
2074 if (--retries) {
2075 sleep(RETRY_MOUNT_DELAY_SECONDS);
2076 } else {
2077 SLOGE("Failed to mount decrypted data");
2078 cryptfs_set_corrupt();
2079 cryptfs_trigger_restart_min_framework();
2080 SLOGI("Started framework to offer wipe");
2081 return -1;
2082 }
2083#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002084 SLOGE("Failed to mount decrypted data");
2085 cryptfs_set_corrupt();
2086 cryptfs_trigger_restart_min_framework();
2087 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002088 if (setexeccon(NULL)) {
2089 SLOGE("Failed to setexeccon");
2090 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002091 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302092#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002093 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002094 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002095 if (setexeccon(NULL)) {
2096 SLOGE("Failed to setexeccon");
2097 return -1;
2098 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002099
Ken Sumralle5032c42012-04-01 23:58:44 -07002100 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002101 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09002102 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07002103
2104 /* startup service classes main and late_start */
2105 property_set("vold.decrypt", "trigger_restart_framework");
2106 SLOGD("Just triggered restart_framework\n");
2107
2108 /* Give it a few moments to get started */
2109 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302110#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002111 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302112#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002113
Ken Sumrall0cc16632011-01-18 20:32:26 -08002114 if (rc == 0) {
2115 restart_successful = 1;
2116 }
2117
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002118 return rc;
2119}
2120
Paul Crowley14c8c072018-09-18 13:30:21 -07002121int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002122 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07002123 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002124 SLOGE("cryptfs_restart not valid for file encryption:");
2125 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002126 }
2127
Paul Lawrencef4faa572014-01-29 13:31:03 -08002128 /* Call internal implementation forcing a restart of main service group */
2129 return cryptfs_restart_internal(1);
2130}
2131
Paul Crowley14c8c072018-09-18 13:30:21 -07002132static int do_crypto_complete(const char* mount_point) {
2133 struct crypt_mnt_ftr crypt_ftr;
2134 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002135
Paul Crowley14c8c072018-09-18 13:30:21 -07002136 property_get("ro.crypto.state", encrypted_state, "");
2137 if (strcmp(encrypted_state, "encrypted")) {
2138 SLOGE("not running with encryption, aborting");
2139 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08002140 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002141
Paul Crowley14c8c072018-09-18 13:30:21 -07002142 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07002143 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002144 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2145 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002146
Paul Crowley14c8c072018-09-18 13:30:21 -07002147 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002148 std::string key_loc;
2149 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002150
Paul Crowley14c8c072018-09-18 13:30:21 -07002151 /*
2152 * Only report this error if key_loc is a file and it exists.
2153 * If the device was never encrypted, and /data is not mountable for
2154 * some reason, returning 1 should prevent the UI from presenting the
2155 * a "enter password" screen, or worse, a "press button to wipe the
2156 * device" screen.
2157 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002158 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002159 SLOGE("master key file does not exist, aborting");
2160 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2161 } else {
2162 SLOGE("Error getting crypt footer and key\n");
2163 return CRYPTO_COMPLETE_BAD_METADATA;
2164 }
2165 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002166
Paul Crowley14c8c072018-09-18 13:30:21 -07002167 // Test for possible error flags
2168 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2169 SLOGE("Encryption process is partway completed\n");
2170 return CRYPTO_COMPLETE_PARTIAL;
2171 }
2172
2173 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2174 SLOGE("Encryption process was interrupted but cannot continue\n");
2175 return CRYPTO_COMPLETE_INCONSISTENT;
2176 }
2177
2178 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
2179 SLOGE("Encryption is successful but data is corrupt\n");
2180 return CRYPTO_COMPLETE_CORRUPT;
2181 }
2182
2183 /* We passed the test! We shall diminish, and return to the west */
2184 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002185}
2186
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302187#ifdef CONFIG_HW_DISK_ENCRYPTION
2188static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2189 const char *passwd, const char *mount_point, const char *label)
2190{
Bill Peckham0db11972018-10-10 10:25:42 -07002191 /* Allocate enough space for a 256 bit key, but we may use less */
2192 unsigned char decrypted_master_key[32];
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05302193 std::string crypto_blkdev_hw;
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002194 std::string crypto_blkdev;
Yifan Hong804afe12019-02-07 12:56:47 -08002195 std::string real_blkdev;
Bill Peckham0db11972018-10-10 10:25:42 -07002196 unsigned int orig_failed_decrypt_count;
2197 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302198
Bill Peckham0db11972018-10-10 10:25:42 -07002199 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2200 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302201
Yifan Hong804afe12019-02-07 12:56:47 -08002202 get_crypt_info(nullptr, &real_blkdev);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302203
Bill Peckham0db11972018-10-10 10:25:42 -07002204 int key_index = 0;
2205 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2206 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2207 if (key_index < 0) {
2208 rc = crypt_ftr->failed_decrypt_count;
2209 goto errout;
2210 }
2211 else {
2212 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302213#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Neeraj Soni73b46952019-09-12 16:47:27 +05302214 if (create_crypto_blk_dev_hw(crypt_ftr, (unsigned char*)&key_index,
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05302215 real_blkdev.c_str(), &crypto_blkdev_hw, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002216 SLOGE("Error creating decrypted block device");
2217 rc = -1;
2218 goto errout;
2219 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302220#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002221 } else {
2222 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002223 real_blkdev.c_str(), &crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002224 SLOGE("Error creating decrypted block device");
2225 rc = -1;
2226 goto errout;
2227 }
2228 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302229 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302230 }
2231
Bill Peckham0db11972018-10-10 10:25:42 -07002232 if (rc == 0) {
2233 crypt_ftr->failed_decrypt_count = 0;
2234 if (orig_failed_decrypt_count != 0) {
2235 put_crypt_ftr_and_key(crypt_ftr);
2236 }
2237
2238 /* Save the name of the crypto block device
2239 * so we can mount it when restarting the framework. */
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05302240 if (is_ice_enabled()) {
2241#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
2242 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev_hw.c_str());
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002243#endif
Phanindra Babu Pabba4c4b58e2020-12-07 16:29:26 +05302244 } else {
2245 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
2246 }
Bill Peckham0db11972018-10-10 10:25:42 -07002247 master_key_saved = 1;
2248 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302249
Bill Peckham0db11972018-10-10 10:25:42 -07002250 errout:
2251 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302252}
2253#endif
2254
Paul Crowley14c8c072018-09-18 13:30:21 -07002255static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2256 const char* mount_point, const char* label) {
2257 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08002258 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002259 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002260 char tmp_mount_point[64];
2261 unsigned int orig_failed_decrypt_count;
2262 int rc;
Paul Crowley14c8c072018-09-18 13:30:21 -07002263 int upgrade = 0;
2264 unsigned char* intermediate_key = 0;
2265 size_t intermediate_key_size = 0;
2266 int N = 1 << crypt_ftr->N_factor;
2267 int r = 1 << crypt_ftr->r_factor;
2268 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302269
Paul Crowley14c8c072018-09-18 13:30:21 -07002270 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2271 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002272
Paul Crowley14c8c072018-09-18 13:30:21 -07002273 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2274 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2275 &intermediate_key_size)) {
2276 SLOGE("Failed to decrypt master key\n");
2277 rc = -1;
2278 goto errout;
2279 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002280 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002281
Tom Cherry4c5bde22019-01-29 14:34:01 -08002282 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002283
Paul Crowley14c8c072018-09-18 13:30:21 -07002284 // Create crypto block device - all (non fatal) code paths
2285 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08002286 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08002287 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002288 SLOGE("Error creating decrypted block device\n");
2289 rc = -1;
2290 goto errout;
2291 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002292
Paul Crowley14c8c072018-09-18 13:30:21 -07002293 /* Work out if the problem is the password or the data */
2294 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002295
Paul Crowley14c8c072018-09-18 13:30:21 -07002296 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2297 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2298 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002299
Paul Crowley14c8c072018-09-18 13:30:21 -07002300 // Does the key match the crypto footer?
2301 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2302 sizeof(scrypted_intermediate_key)) == 0) {
2303 SLOGI("Password matches");
2304 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002305 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002306 /* Try mounting the file system anyway, just in case the problem's with
2307 * the footer, not the key. */
2308 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2309 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08002310 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
2311 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002312 SLOGE("Error temp mounting decrypted block device\n");
2313 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002314
Paul Crowley14c8c072018-09-18 13:30:21 -07002315 rc = ++crypt_ftr->failed_decrypt_count;
2316 put_crypt_ftr_and_key(crypt_ftr);
2317 } else {
2318 /* Success! */
2319 SLOGI("Password did not match but decrypted drive mounted - continue");
2320 umount(tmp_mount_point);
2321 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002322 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002323 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002324
Paul Crowley14c8c072018-09-18 13:30:21 -07002325 if (rc == 0) {
2326 crypt_ftr->failed_decrypt_count = 0;
2327 if (orig_failed_decrypt_count != 0) {
2328 put_crypt_ftr_and_key(crypt_ftr);
2329 }
2330
2331 /* Save the name of the crypto block device
2332 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08002333 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07002334
2335 /* Also save a the master key so we can reencrypted the key
2336 * the key when we want to change the password on it. */
2337 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2338 saved_mount_point = strdup(mount_point);
2339 master_key_saved = 1;
2340 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2341 rc = 0;
2342
2343 // Upgrade if we're not using the latest KDF.
Satya Tangirala23452c12021-03-22 23:29:15 -07002344 if (crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002345 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2346 upgrade = 1;
Paul Crowley14c8c072018-09-18 13:30:21 -07002347 }
2348
2349 if (upgrade) {
2350 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002351 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002352 if (!rc) {
2353 rc = put_crypt_ftr_and_key(crypt_ftr);
2354 }
2355 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2356
2357 // Do not fail even if upgrade failed - machine is bootable
2358 // Note that if this code is ever hit, there is a *serious* problem
2359 // since KDFs should never fail. You *must* fix the kdf before
2360 // proceeding!
2361 if (rc) {
2362 SLOGW(
2363 "Upgrade failed with error %d,"
2364 " but continuing with previous state",
2365 rc);
2366 rc = 0;
2367 }
2368 }
2369 }
2370
2371errout:
2372 if (intermediate_key) {
2373 memset(intermediate_key, 0, intermediate_key_size);
2374 free(intermediate_key);
2375 }
2376 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002377}
2378
Ken Sumrall29d8da82011-05-18 17:20:07 -07002379/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002380 * Called by vold when it's asked to mount an encrypted external
2381 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002382 * as any metadata is been stored in a separate, small partition. We
2383 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002384 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002385int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08002386 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08002387 auto crypto_type = get_crypto_type();
2388 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08002389 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08002390 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002391 return -1;
2392 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002393 uint64_t nr_sec = 0;
2394 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002395 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002396 return -1;
2397 }
2398
Jeff Sharkey9c484982015-03-31 10:35:33 -07002399 struct crypt_mnt_ftr ext_crypt_ftr;
2400 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2401 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08002402 ext_crypt_ftr.keysize = crypto_type.get_keysize();
2403 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002404 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002405 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002406 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002407 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2408 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002409
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002410 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
2411 real_blkdev, out_crypto_blkdev, label, flags);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002412}
2413
Paul Crowley14c8c072018-09-18 13:30:21 -07002414int cryptfs_crypto_complete(void) {
2415 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002416}
2417
Paul Crowley14c8c072018-09-18 13:30:21 -07002418int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002419 char encrypted_state[PROPERTY_VALUE_MAX];
2420 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002421 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2422 SLOGE(
2423 "encrypted fs already validated or not running with encryption,"
2424 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002425 return -1;
2426 }
2427
2428 if (get_crypt_ftr_and_key(crypt_ftr)) {
2429 SLOGE("Error getting crypt footer and key");
2430 return -1;
2431 }
2432
2433 return 0;
2434}
2435
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302436#ifdef CONFIG_HW_DISK_ENCRYPTION
2437int cryptfs_check_passwd_hw(const char* passwd)
2438{
2439 struct crypt_mnt_ftr crypt_ftr;
2440 int rc;
2441 unsigned char master_key[KEY_LEN_BYTES];
2442
2443 /* get key */
2444 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2445 SLOGE("Error getting crypt footer and key");
2446 return -1;
2447 }
2448
2449 /*
2450 * in case of manual encryption (from GUI), the encryption is done with
2451 * default password
2452 */
2453 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2454 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2455 * which was created with actual password before reboot.
2456 */
2457 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2458 if (rc) {
2459 SLOGE("password doesn't match");
2460 rc = ++crypt_ftr.failed_decrypt_count;
2461 put_crypt_ftr_and_key(&crypt_ftr);
2462 return rc;
2463 }
2464
2465 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2466 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2467
2468 if (rc) {
2469 SLOGE("Default password did not match on reboot encryption");
2470 return rc;
2471 }
2472
2473 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2474 put_crypt_ftr_and_key(&crypt_ftr);
2475 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2476 if (rc) {
2477 SLOGE("Could not change password on reboot encryption");
2478 return rc;
2479 }
2480 } else
2481 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2482 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2483
2484 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2485 cryptfs_clear_password();
2486 password = strdup(passwd);
2487 struct timespec now;
2488 clock_gettime(CLOCK_BOOTTIME, &now);
2489 password_expiry_time = now.tv_sec + password_max_age_seconds;
2490 }
2491
2492 return rc;
2493}
2494#endif
2495
Paul Crowley14c8c072018-09-18 13:30:21 -07002496int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002497 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002498 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002499 SLOGE("cryptfs_check_passwd not valid for file encryption");
2500 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002501 }
2502
Paul Lawrencef4faa572014-01-29 13:31:03 -08002503 struct crypt_mnt_ftr crypt_ftr;
2504 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002505
Paul Lawrencef4faa572014-01-29 13:31:03 -08002506 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002507 if (rc) {
2508 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002509 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002510 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002511
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 return cryptfs_check_passwd_hw(passwd);
2515#endif
2516
Paul Crowley14c8c072018-09-18 13:30:21 -07002517 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002518 if (rc) {
2519 SLOGE("Password did not match");
2520 return rc;
2521 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002522
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002523 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2524 // Here we have a default actual password but a real password
2525 // we must test against the scrypted value
2526 // First, we must delete the crypto block device that
2527 // test_mount_encrypted_fs leaves behind as a side effect
2528 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002529 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2530 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002531 if (rc) {
2532 SLOGE("Default password did not match on reboot encryption");
2533 return rc;
2534 }
2535
2536 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2537 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302538 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002539 if (rc) {
2540 SLOGE("Could not change password on reboot encryption");
2541 return rc;
2542 }
2543 }
2544
2545 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002546 cryptfs_clear_password();
2547 password = strdup(passwd);
2548 struct timespec now;
2549 clock_gettime(CLOCK_BOOTTIME, &now);
2550 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002551 }
2552
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002553 return rc;
2554}
2555
Paul Crowley14c8c072018-09-18 13:30:21 -07002556int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002557 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002558 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002559 char encrypted_state[PROPERTY_VALUE_MAX];
2560 int rc;
2561
2562 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002563 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002564 SLOGE("device not encrypted, aborting");
2565 return -2;
2566 }
2567
2568 if (!master_key_saved) {
2569 SLOGE("encrypted fs not yet mounted, aborting");
2570 return -1;
2571 }
2572
2573 if (!saved_mount_point) {
2574 SLOGE("encrypted fs failed to save mount point, aborting");
2575 return -1;
2576 }
2577
Ken Sumrall160b4d62013-04-22 12:15:39 -07002578 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002579 SLOGE("Error getting crypt footer and key\n");
2580 return -1;
2581 }
2582
2583 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2584 /* If the device has no password, then just say the password is valid */
2585 rc = 0;
2586 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302587#ifdef CONFIG_HW_DISK_ENCRYPTION
2588 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2589 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2590 rc = 0;
2591 else
2592 rc = -1;
2593 } else {
2594 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2595 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2596 /* They match, the password is correct */
2597 rc = 0;
2598 } else {
2599 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2600 sleep(1);
2601 rc = 1;
2602 }
2603 }
2604#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002605 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002606 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2607 /* They match, the password is correct */
2608 rc = 0;
2609 } else {
2610 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2611 sleep(1);
2612 rc = 1;
2613 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302614#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002615 }
2616
2617 return rc;
2618}
2619
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002620/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002621 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002622 * Presumably, at a minimum, the caller will update the
2623 * filesystem size and crypto_type_name after calling this function.
2624 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002625static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002626 off64_t off;
2627
2628 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002629 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002630 ftr->major_version = CURRENT_MAJOR_VERSION;
2631 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002632 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002633 ftr->keysize = get_crypto_type().get_keysize();
Satya Tangirala23452c12021-03-22 23:29:15 -07002634 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002635
Kenny Rootc4c70f12013-06-14 12:11:38 -07002636 get_device_scrypt_params(ftr);
2637
Ken Sumrall160b4d62013-04-22 12:15:39 -07002638 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2639 if (get_crypt_ftr_info(NULL, &off) == 0) {
2640 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002641 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002642 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002643
2644 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002645}
2646
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002647#define FRAMEWORK_BOOT_WAIT 60
2648
Paul Crowleyb64933a2017-10-31 08:25:55 -07002649static int vold_unmountAll(void) {
2650 VolumeManager* vm = VolumeManager::Instance();
2651 return vm->unmountAll();
2652}
2653
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002654int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002655 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002656 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002657 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002658 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002659 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002660 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002661 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002662 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002663 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002664 int num_vols;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002665 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002666 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302667#ifdef CONFIG_HW_DISK_ENCRYPTION
2668 unsigned char newpw[32];
2669 int key_index = 0;
2670#endif
2671 int index = 0;
Kalesh Singh98062dc2021-02-22 15:10:45 -05002672
2673 /* Get a wakelock as this may take a while, and we don't want the
2674 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2675 * wants to keep the screen on, it can grab a full wakelock.
2676 */
2677 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
2678 auto wl = android::wakelock::WakeLock::tryGet(lockid);
2679 if (!wl.has_value()) {
2680 return android::UNEXPECTED_NULL;
2681 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302682
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002683 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Eric Biggersc01995e2020-11-03 14:11:00 -08002684 if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002685 if (!check_ftr_sha(&crypt_ftr)) {
2686 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2687 put_crypt_ftr_and_key(&crypt_ftr);
2688 goto error_unencrypted;
2689 }
2690
2691 /* Doing a reboot-encryption*/
2692 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2693 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2694 rebootEncryption = true;
2695 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002696 } else {
2697 // We don't want to accidentally reference invalid data.
2698 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002699 }
2700
2701 property_get("ro.crypto.state", encrypted_state, "");
Eric Biggersc01995e2020-11-03 14:11:00 -08002702 if (!strcmp(encrypted_state, "encrypted")) {
Paul Lawrence87999172014-02-20 12:21:31 -08002703 SLOGE("Device is already running encrypted, aborting");
2704 goto error_unencrypted;
2705 }
2706
Tom Cherry4c5bde22019-01-29 14:34:01 -08002707 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002708
Ken Sumrall3ed82362011-01-28 23:31:16 -08002709 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002710 uint64_t nr_sec;
2711 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002712 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002713 goto error_unencrypted;
2714 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002715
2716 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002717 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002718 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002719 fs_size_sec = get_fs_size(real_blkdev.c_str());
2720 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002721
Paul Lawrence87999172014-02-20 12:21:31 -08002722 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002723
2724 if (fs_size_sec > max_fs_size_sec) {
2725 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2726 goto error_unencrypted;
2727 }
2728 }
2729
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002730 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002731 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002732 */
2733 property_set("vold.decrypt", "trigger_shutdown_framework");
2734 SLOGD("Just asked init to shut down class main\n");
2735
Jeff Sharkey9c484982015-03-31 10:35:33 -07002736 /* Ask vold to unmount all devices that it manages */
2737 if (vold_unmountAll()) {
2738 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002739 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002740
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002741 /* no_ui means we are being called from init, not settings.
2742 Now we always reboot from settings, so !no_ui means reboot
2743 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002744 if (!no_ui) {
2745 /* Try fallback, which is to reboot and try there */
2746 onlyCreateHeader = true;
2747 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2748 if (breadcrumb == 0) {
2749 SLOGE("Failed to create breadcrumb file");
2750 goto error_shutting_down;
2751 }
2752 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002753 }
2754
2755 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002756 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002757 /* Now that /data is unmounted, we need to mount a tmpfs
2758 * /data, set a property saying we're doing inplace encryption,
2759 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002760 */
xzj7e38a3a2018-10-12 10:17:11 +08002761 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002762 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002763 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002764 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002765 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002766 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002767
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002768 /* restart the framework. */
2769 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002770 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002771
Ken Sumrall92736ef2012-10-17 20:57:14 -07002772 /* Ugh, shutting down the framework is not synchronous, so until it
2773 * can be fixed, this horrible hack will wait a moment for it all to
2774 * shut down before proceeding. Without it, some devices cannot
2775 * restart the graphics services.
2776 */
2777 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002778 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002779
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002780 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002781 /* Initialize a crypt_mnt_ftr for the partition */
Eric Biggersc01995e2020-11-03 14:11:00 -08002782 if (!rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002783 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2784 goto error_shutting_down;
2785 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002786
Tom Cherry4c5bde22019-01-29 14:34:01 -08002787 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002788 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002789 } else {
2790 crypt_ftr.fs_size = nr_sec;
2791 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002792 /* At this point, we are in an inconsistent state. Until we successfully
2793 complete encryption, a reboot will leave us broken. So mark the
2794 encryption failed in case that happens.
2795 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002796 if (onlyCreateHeader) {
2797 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2798 } else {
2799 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2800 }
Paul Lawrence87999172014-02-20 12:21:31 -08002801 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302802#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002803 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2804 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302805#else
Paul Crowley220567c2020-02-07 12:45:20 -08002806 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002807 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302808#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002809
Paul Lawrence87999172014-02-20 12:21:31 -08002810 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002811 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2812 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002813 SLOGE("Cannot create encrypted master key\n");
2814 goto error_shutting_down;
2815 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002816
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002817 /* Replace scrypted intermediate key if we are preparing for a reboot */
2818 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002819 unsigned char fake_master_key[MAX_KEY_LEN];
2820 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002821 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002822 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002823 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002824 }
2825
Paul Lawrence87999172014-02-20 12:21:31 -08002826 /* Write the key to the end of the partition */
2827 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002828
Paul Lawrence87999172014-02-20 12:21:31 -08002829 /* If any persistent data has been remembered, save it.
2830 * If none, create a valid empty table and save that.
2831 */
2832 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002833 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2834 if (pdata) {
2835 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2836 persist_data = pdata;
2837 }
Paul Lawrence87999172014-02-20 12:21:31 -08002838 }
2839 if (persist_data) {
2840 save_persistent_data();
2841 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002842 }
2843
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302844 /* When encryption triggered from settings, encryption starts after reboot.
2845 So set the encryption key when the actual encryption starts.
2846 */
2847#ifdef CONFIG_HW_DISK_ENCRYPTION
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002848 if (!rebootEncryption)
2849 clear_hw_device_encryption_key();
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302850
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002851 if (get_keymaster_hw_fde_passwd(
2852 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2853 newpw, crypt_ftr.salt, &crypt_ftr))
2854 key_index = set_hw_device_encryption_key(
2855 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2856 (char*)crypt_ftr.crypto_type_name);
2857 else
2858 key_index = set_hw_device_encryption_key((const char*)newpw,
2859 (char*) crypt_ftr.crypto_type_name);
2860 if (key_index < 0)
2861 goto error_shutting_down;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302862
Scott Lobdell7e4cbd72020-11-05 18:29:14 -08002863 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2864 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302865#endif
2866
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002867 if (onlyCreateHeader) {
2868 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002869 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302870 } else {
2871 /* Do extra work for a better UX when doing the long inplace encryption */
2872 /* Now that /data is unmounted, we need to mount a tmpfs
2873 * /data, set a property saying we're doing inplace encryption,
2874 * and restart the framework.
2875 */
2876 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2877 goto error_shutting_down;
2878 }
2879 /* Tells the framework that inplace encryption is starting */
2880 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002881
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302882 /* restart the framework. */
2883 /* Create necessary paths on /data */
2884 prep_data_fs();
2885
2886 /* Ugh, shutting down the framework is not synchronous, so until it
2887 * can be fixed, this horrible hack will wait a moment for it all to
2888 * shut down before proceeding. Without it, some devices cannot
2889 * restart the graphics services.
2890 */
2891 sleep(2);
2892
Ajay Dudani87701e22014-09-17 21:02:52 -07002893 /* startup service classes main and late_start */
2894 property_set("vold.decrypt", "trigger_restart_min_framework");
2895 SLOGD("Just triggered restart_min_framework\n");
2896
2897 /* OK, the framework is restarted and will soon be showing a
2898 * progress bar. Time to setup an encrypted mapping, and
2899 * either write a new filesystem, or encrypt in place updating
2900 * the progress bar as we work.
2901 */
2902 }
2903
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002904 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302905#ifdef CONFIG_HW_DISK_ENCRYPTION
2906 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302907#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002908 crypto_blkdev = real_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302909#else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002910 create_crypto_blk_dev_hw(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302911 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302912#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302913 else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002914 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302915 CRYPTO_BLOCK_DEVICE, 0);
2916#else
Paul Crowley81796e92020-02-07 11:27:49 -08002917 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002918 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302919#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002920
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302921#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2922 if (set_ice_param(START_ENC)) {
2923 SLOGE("Failed to set ICE data");
2924 goto error_shutting_down;
2925 }
2926#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002927 if (!rc) {
Eric Biggersf038c5f2020-11-03 14:11:02 -08002928 if (encrypt_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size, true)) {
2929 crypt_ftr.encrypted_upto = crypt_ftr.fs_size;
2930 rc = 0;
2931 } else {
Paul Lawrence87999172014-02-20 12:21:31 -08002932 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002933 }
Eric Biggers88f993b2020-11-03 14:11:00 -08002934 /* Undo the dm-crypt mapping whether we succeed or not */
2935 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002936 }
2937
Paul Crowley14c8c072018-09-18 13:30:21 -07002938 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002939 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002940 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002941
Paul Lawrence6bfed202014-07-28 12:47:22 -07002942 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002943
Eric Biggersc01995e2020-11-03 14:11:00 -08002944 char value[PROPERTY_VALUE_MAX];
2945 property_get("ro.crypto.state", value, "");
2946 if (!strcmp(value, "")) {
2947 /* default encryption - continue first boot sequence */
2948 property_set("ro.crypto.state", "encrypted");
2949 property_set("ro.crypto.type", "block");
Kalesh Singh98062dc2021-02-22 15:10:45 -05002950 wl.reset();
Eric Biggersc01995e2020-11-03 14:11:00 -08002951 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2952 // Bring up cryptkeeper that will check the password and set it
2953 property_set("vold.decrypt", "trigger_shutdown_framework");
2954 sleep(2);
2955 property_set("vold.encrypt_progress", "");
2956 cryptfs_trigger_restart_min_framework();
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002957 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002958 cryptfs_check_passwd(DEFAULT_PASSWORD);
2959 cryptfs_restart_internal(1);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002960 }
Eric Biggersc01995e2020-11-03 14:11:00 -08002961 return 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002962 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002963 sleep(2); /* Give the UI a chance to show 100% progress */
2964 cryptfs_reboot(RebootType::reboot);
Paul Lawrence87999172014-02-20 12:21:31 -08002965 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002966 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002967 char value[PROPERTY_VALUE_MAX];
2968
Ken Sumrall319369a2012-06-27 16:30:18 -07002969 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002970 if (!strcmp(value, "1")) {
2971 /* wipe data if encryption failed */
2972 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002973 std::string err;
2974 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002975 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002976 if (!write_bootloader_message(options, &err)) {
2977 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002978 }
Josh Gaofec44372017-08-28 13:22:55 -07002979 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002980 } else {
2981 /* set property to trigger dialog */
2982 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002983 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002984 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002985 }
2986
Ken Sumrall3ed82362011-01-28 23:31:16 -08002987 /* hrm, the encrypt step claims success, but the reboot failed.
2988 * This should not happen.
2989 * Set the property and return. Hope the framework can deal with it.
2990 */
2991 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002992 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002993
2994error_unencrypted:
2995 property_set("vold.encrypt_progress", "error_not_encrypted");
2996 return -1;
2997
2998error_shutting_down:
2999 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3000 * but the framework is stopped and not restarted to show the error, so it's up to
3001 * vold to restart the system.
3002 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003003 SLOGE(
3004 "Error enabling encryption after framework is shutdown, no data changed, restarting "
3005 "system");
Josh Gaofec44372017-08-28 13:22:55 -07003006 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003007
3008 /* shouldn't get here */
3009 property_set("vold.encrypt_progress", "error_shutting_down");
3010 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003011}
3012
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003013int cryptfs_enable(int type, const char* passwd, int no_ui) {
3014 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003015}
3016
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003017int cryptfs_enable_default(int no_ui) {
3018 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003019}
3020
Bill Peckham0db11972018-10-10 10:25:42 -07003021int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07003022 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003023 SLOGE("cryptfs_changepw not valid for file encryption");
3024 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003025 }
3026
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003027 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003028 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003029
3030 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003031 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003032 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003033 return -1;
3034 }
3035
Paul Lawrencef4faa572014-01-29 13:31:03 -08003036 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3037 SLOGE("Invalid crypt_type %d", crypt_type);
3038 return -1;
3039 }
3040
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003041 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003042 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003043 SLOGE("Error getting crypt footer and key");
3044 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003045 }
3046
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303047#ifdef CONFIG_HW_DISK_ENCRYPTION
3048 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
3049 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
3050 else {
3051 crypt_ftr.crypt_type = crypt_type;
3052
3053 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
3054 DEFAULT_PASSWORD : newpw,
3055 crypt_ftr.salt,
3056 saved_master_key,
3057 crypt_ftr.master_key,
3058 &crypt_ftr, false);
3059 if (rc) {
3060 SLOGE("Encrypt master key failed: %d", rc);
3061 return -1;
3062 }
3063 /* save the key */
3064 put_crypt_ftr_and_key(&crypt_ftr);
3065
3066 return 0;
3067 }
3068#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003069 crypt_ftr.crypt_type = crypt_type;
3070
Paul Crowley14c8c072018-09-18 13:30:21 -07003071 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07003072 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
3073 false);
JP Abgrall933216c2015-02-11 13:44:32 -08003074 if (rc) {
3075 SLOGE("Encrypt master key failed: %d", rc);
3076 return -1;
3077 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003078 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003079 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003080
3081 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303082#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003083}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003084
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303085#ifdef CONFIG_HW_DISK_ENCRYPTION
3086int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3087{
3088 struct crypt_mnt_ftr crypt_ftr;
3089 int rc;
3090 int previous_type;
3091
3092 /* get key */
3093 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3094 SLOGE("Error getting crypt footer and key");
3095 return -1;
3096 }
3097
3098 previous_type = crypt_ftr.crypt_type;
3099 int rc1;
3100 unsigned char tmp_curpw[32] = {0};
3101 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3102 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3103 crypt_ftr.salt, &crypt_ftr);
3104
3105 crypt_ftr.crypt_type = crypt_type;
3106
3107 int ret, rc2;
3108 unsigned char tmp_newpw[32] = {0};
3109
3110 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3111 DEFAULT_PASSWORD : newpw , tmp_newpw,
3112 crypt_ftr.salt, &crypt_ftr);
3113
3114 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3115 ret = update_hw_device_encryption_key(
3116 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3117 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3118 (char*)crypt_ftr.crypto_type_name);
3119 if (ret) {
3120 SLOGE("Error updating device encryption hardware key ret %d", ret);
3121 return -1;
3122 } else {
3123 SLOGI("Encryption hardware key updated");
3124 }
3125 }
3126
3127 /* save the key */
3128 put_crypt_ftr_and_key(&crypt_ftr);
3129 return 0;
3130}
3131#endif
3132
Rubin Xu85c01f92014-10-13 12:49:54 +01003133static unsigned int persist_get_max_entries(int encrypted) {
3134 struct crypt_mnt_ftr crypt_ftr;
3135 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003136
3137 /* If encrypted, use the values from the crypt_ftr, otherwise
3138 * use the values for the current spec.
3139 */
3140 if (encrypted) {
3141 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003142 /* Something is wrong, assume no space for entries */
3143 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003144 }
3145 dsize = crypt_ftr.persist_data_size;
3146 } else {
3147 dsize = CRYPT_PERSIST_DATA_SIZE;
3148 }
3149
Rubin Xud78181b2018-10-09 16:13:38 +01003150 if (dsize > sizeof(struct crypt_persist_data)) {
3151 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3152 } else {
3153 return 0;
3154 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003155}
3156
Paul Crowley14c8c072018-09-18 13:30:21 -07003157static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003158 unsigned int i;
3159
3160 if (persist_data == NULL) {
3161 return -1;
3162 }
3163 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3164 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3165 /* We found it! */
3166 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3167 return 0;
3168 }
3169 }
3170
3171 return -1;
3172}
3173
Paul Crowley14c8c072018-09-18 13:30:21 -07003174static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003175 unsigned int i;
3176 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003177 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003178
3179 if (persist_data == NULL) {
3180 return -1;
3181 }
3182
Rubin Xu85c01f92014-10-13 12:49:54 +01003183 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003184
3185 num = persist_data->persist_valid_entries;
3186
3187 for (i = 0; i < num; i++) {
3188 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3189 /* We found an existing entry, update it! */
3190 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3191 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3192 return 0;
3193 }
3194 }
3195
3196 /* We didn't find it, add it to the end, if there is room */
3197 if (persist_data->persist_valid_entries < max_persistent_entries) {
3198 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3199 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3200 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3201 persist_data->persist_valid_entries++;
3202 return 0;
3203 }
3204
3205 return -1;
3206}
3207
Rubin Xu85c01f92014-10-13 12:49:54 +01003208/**
3209 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3210 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3211 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003212int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003213 std::string key_ = key;
3214 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003215
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003216 std::string parsed_field;
3217 unsigned parsed_index;
3218
3219 std::string::size_type split = key_.find_last_of('_');
3220 if (split == std::string::npos) {
3221 parsed_field = key_;
3222 parsed_index = 0;
3223 } else {
3224 parsed_field = key_.substr(0, split);
3225 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003226 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003227
3228 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003229}
3230
3231/*
3232 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3233 * remaining entries starting from index will be deleted.
3234 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3235 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3236 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3237 *
3238 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003239static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003240 unsigned int i;
3241 unsigned int j;
3242 unsigned int num;
3243
3244 if (persist_data == NULL) {
3245 return PERSIST_DEL_KEY_ERROR_OTHER;
3246 }
3247
3248 num = persist_data->persist_valid_entries;
3249
Paul Crowley14c8c072018-09-18 13:30:21 -07003250 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003251 // Filter out to-be-deleted entries in place.
3252 for (i = 0; i < num; i++) {
3253 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3254 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3255 j++;
3256 }
3257 }
3258
3259 if (j < num) {
3260 persist_data->persist_valid_entries = j;
3261 // Zeroise the remaining entries
3262 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3263 return PERSIST_DEL_KEY_OK;
3264 } else {
3265 // Did not find an entry matching the given fieldname
3266 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3267 }
3268}
3269
Paul Crowley14c8c072018-09-18 13:30:21 -07003270static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003271 unsigned int i;
3272 unsigned int count;
3273
3274 if (persist_data == NULL) {
3275 return -1;
3276 }
3277
3278 count = 0;
3279 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3280 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3281 count++;
3282 }
3283 }
3284
3285 return count;
3286}
3287
Ken Sumrall160b4d62013-04-22 12:15:39 -07003288/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003289int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003290 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003291 SLOGE("Cannot get field when file encrypted");
3292 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003293 }
3294
Ken Sumrall160b4d62013-04-22 12:15:39 -07003295 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003296 /* CRYPTO_GETFIELD_OK is success,
3297 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3298 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3299 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003300 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003301 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3302 int i;
3303 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003304
3305 if (persist_data == NULL) {
3306 load_persistent_data();
3307 if (persist_data == NULL) {
3308 SLOGE("Getfield error, cannot load persistent data");
3309 goto out;
3310 }
3311 }
3312
Rubin Xu85c01f92014-10-13 12:49:54 +01003313 // Read value from persistent entries. If the original value is split into multiple entries,
3314 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003315 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003316 // 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 -07003317 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003318 // value too small
3319 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3320 goto out;
3321 }
3322 rc = CRYPTO_GETFIELD_OK;
3323
3324 for (i = 1; /* break explicitly */; i++) {
3325 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003326 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003327 // If the fieldname is very long, we stop as soon as it begins to overflow the
3328 // maximum field length. At this point we have in fact fully read out the original
3329 // value because cryptfs_setfield would not allow fields with longer names to be
3330 // written in the first place.
3331 break;
3332 }
3333 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003334 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3335 // value too small.
3336 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3337 goto out;
3338 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003339 } else {
3340 // Exhaust all entries.
3341 break;
3342 }
3343 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003344 } else {
3345 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003346 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003347 }
3348
3349out:
3350 return rc;
3351}
3352
3353/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003354int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003355 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003356 SLOGE("Cannot set field when file encrypted");
3357 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003358 }
3359
Ken Sumrall160b4d62013-04-22 12:15:39 -07003360 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003361 /* 0 is success, negative values are error */
3362 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003363 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003364 unsigned int field_id;
3365 char temp_field[PROPERTY_KEY_MAX];
3366 unsigned int num_entries;
3367 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003368
3369 if (persist_data == NULL) {
3370 load_persistent_data();
3371 if (persist_data == NULL) {
3372 SLOGE("Setfield error, cannot load persistent data");
3373 goto out;
3374 }
3375 }
3376
3377 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003378 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003379 encrypted = 1;
3380 }
3381
Rubin Xu85c01f92014-10-13 12:49:54 +01003382 // Compute the number of entries required to store value, each entry can store up to
3383 // (PROPERTY_VALUE_MAX - 1) chars
3384 if (strlen(value) == 0) {
3385 // Empty value also needs one entry to store.
3386 num_entries = 1;
3387 } else {
3388 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3389 }
3390
3391 max_keylen = strlen(fieldname);
3392 if (num_entries > 1) {
3393 // Need an extra "_%d" suffix.
3394 max_keylen += 1 + log10(num_entries);
3395 }
3396 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3397 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003398 goto out;
3399 }
3400
Rubin Xu85c01f92014-10-13 12:49:54 +01003401 // Make sure we have enough space to write the new value
3402 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3403 persist_get_max_entries(encrypted)) {
3404 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3405 goto out;
3406 }
3407
3408 // Now that we know persist_data has enough space for value, let's delete the old field first
3409 // to make up space.
3410 persist_del_keys(fieldname, 0);
3411
3412 if (persist_set_key(fieldname, value, encrypted)) {
3413 // fail to set key, should not happen as we have already checked the available space
3414 SLOGE("persist_set_key() error during setfield()");
3415 goto out;
3416 }
3417
3418 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003419 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003420
3421 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3422 // fail to set key, should not happen as we have already checked the available space.
3423 SLOGE("persist_set_key() error during setfield()");
3424 goto out;
3425 }
3426 }
3427
Ken Sumrall160b4d62013-04-22 12:15:39 -07003428 /* If we are running encrypted, save the persistent data now */
3429 if (encrypted) {
3430 if (save_persistent_data()) {
3431 SLOGE("Setfield error, cannot save persistent data");
3432 goto out;
3433 }
3434 }
3435
Rubin Xu85c01f92014-10-13 12:49:54 +01003436 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003437
3438out:
3439 return rc;
3440}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003441
3442/* Checks userdata. Attempt to mount the volume if default-
3443 * encrypted.
3444 * On success trigger next init phase and return 0.
3445 * Currently do not handle failure - see TODO below.
3446 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003447int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003448 int crypt_type = cryptfs_get_password_type();
3449 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3450 SLOGE("Bad crypt type - error");
3451 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003452 SLOGD(
3453 "Password is not default - "
3454 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003455 property_set("vold.decrypt", "trigger_restart_min_framework");
3456 return 0;
3457 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3458 SLOGD("Password is default - restarting filesystem");
3459 cryptfs_restart_internal(0);
3460 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003461 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003462 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003463 }
3464
Paul Lawrence6bfed202014-07-28 12:47:22 -07003465 /** Corrupt. Allow us to boot into framework, which will detect bad
3466 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003467 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003468 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003469 return 0;
3470}
3471
3472/* Returns type of the password, default, pattern, pin or password.
3473 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003474int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003475 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003476 SLOGE("cryptfs_get_password_type not valid for file encryption");
3477 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003478 }
3479
Paul Lawrencef4faa572014-01-29 13:31:03 -08003480 struct crypt_mnt_ftr crypt_ftr;
3481
3482 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3483 SLOGE("Error getting crypt footer and key\n");
3484 return -1;
3485 }
3486
Paul Lawrence6bfed202014-07-28 12:47:22 -07003487 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3488 return -1;
3489 }
3490
Paul Lawrencef4faa572014-01-29 13:31:03 -08003491 return crypt_ftr.crypt_type;
3492}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003493
Paul Crowley14c8c072018-09-18 13:30:21 -07003494const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003495 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003496 SLOGE("cryptfs_get_password not valid for file encryption");
3497 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003498 }
3499
Paul Lawrence399317e2014-03-10 13:20:50 -07003500 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003501 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003502 if (now.tv_sec < password_expiry_time) {
3503 return password;
3504 } else {
3505 cryptfs_clear_password();
3506 return 0;
3507 }
3508}
3509
Paul Crowley14c8c072018-09-18 13:30:21 -07003510void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003511 if (password) {
3512 size_t len = strlen(password);
3513 memset(password, 0, len);
3514 free(password);
3515 password = 0;
3516 password_expiry_time = 0;
3517 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003518}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003519
Paul Crowley14c8c072018-09-18 13:30:21 -07003520int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003521 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3522 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003523}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303524
3525int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3526{
3527 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3528 SLOGE("Failed to initialize crypt_ftr");
3529 return -1;
3530 }
3531
3532 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3533 crypt_ftr->salt, crypt_ftr)) {
3534 SLOGE("Cannot create encrypted master key\n");
3535 return -1;
3536 }
3537
3538 //crypt_ftr->keysize = key_length / 8;
3539 return 0;
3540}
3541
3542int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3543 unsigned char* master_key)
3544{
3545 int rc;
3546
3547 unsigned char* intermediate_key = 0;
3548 size_t intermediate_key_size = 0;
3549
3550 if (password == 0 || *password == 0) {
3551 password = DEFAULT_PASSWORD;
3552 }
3553
3554 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3555 &intermediate_key_size);
3556
3557 if (rc) {
3558 SLOGE("Can't calculate intermediate key");
3559 return rc;
3560 }
3561
3562 int N = 1 << ftr->N_factor;
3563 int r = 1 << ftr->r_factor;
3564 int p = 1 << ftr->p_factor;
3565
3566 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3567
3568 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3569 ftr->salt, sizeof(ftr->salt), N, r, p,
3570 scrypted_intermediate_key,
3571 sizeof(scrypted_intermediate_key));
3572
3573 free(intermediate_key);
3574
3575 if (rc) {
3576 SLOGE("Can't scrypt intermediate key");
3577 return rc;
3578 }
3579
3580 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3581 intermediate_key_size);
3582}