blob: 9166016e2bf00c42193472642448ea836dfcfa89 [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"
Logan Chiend557d762018-05-02 11:36:45 +080022#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070023#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080024#include "Keymaster.h"
25#include "Process.h"
26#include "ScryptParameters.h"
Paul Crowley298fa322018-10-30 15:59:24 -070027#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "VoldUtil.h"
29#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080030
Eric Biggersed45ec32019-01-25 10:47:55 -080031#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080032#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080033#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080034#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080035#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080036#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070037#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070039#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070040#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070041#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080042#include <log/log.h>
Ken Sumralle550f782013-08-20 13:48:23 -070043#include <logwrap/logwrap.h>
Logan Chiend557d762018-05-02 11:36:45 +080044#include <openssl/evp.h>
45#include <openssl/sha.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080046#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070047#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080048
49#include <ctype.h>
50#include <errno.h>
51#include <fcntl.h>
52#include <inttypes.h>
53#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080054#include <linux/kdev_t.h>
55#include <math.h>
56#include <stdio.h>
57#include <stdlib.h>
58#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080059#include <sys/mount.h>
60#include <sys/param.h>
61#include <sys/stat.h>
62#include <sys/types.h>
63#include <sys/wait.h>
64#include <time.h>
65#include <unistd.h>
66
Martijn Coenen26ad7b32020-02-13 16:20:52 +010067#include <chrono>
68#include <thread>
69
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053070#ifdef CONFIG_HW_DISK_ENCRYPTION
Neeraj Soni73b46952019-09-12 16:47:27 +053071#include <linux/dm-ioctl.h>
72#include <sys/ioctl.h>
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053073#include <cryptfs_hw.h>
74#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080075extern "C" {
76#include <crypto_scrypt.h>
77}
Mark Salyzyn3e971272014-01-21 13:27:04 -080078
Eric Biggersed45ec32019-01-25 10:47:55 -080079using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080080using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080081using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080082using android::vold::KeyBuffer;
David Andersonb9224732019-05-13 13:02:54 -070083using namespace android::dm;
Paul Crowley298fa322018-10-30 15:59:24 -070084using namespace std::chrono_literals;
85
Paul Crowley73be12d2020-02-03 12:22:03 -080086/* The current cryptfs version */
87#define CURRENT_MAJOR_VERSION 1
88#define CURRENT_MINOR_VERSION 3
89
90#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
91#define CRYPT_PERSIST_DATA_SIZE 0x1000
92
93#define MAX_CRYPTO_TYPE_NAME_LEN 64
94
95#define MAX_KEY_LEN 48
96#define SALT_LEN 16
97#define SCRYPT_LEN 32
98
99/* definitions of flags in the structure below */
100#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
101#define CRYPT_ENCRYPTION_IN_PROGRESS \
102 0x2 /* Encryption partially completed, \
103 encrypted_upto valid*/
104#define CRYPT_INCONSISTENT_STATE \
105 0x4 /* Set when starting encryption, clear when \
106 exit cleanly, either through success or \
107 correctly marked partial encryption */
108#define CRYPT_DATA_CORRUPT \
109 0x8 /* Set when encryption is fine, but the \
110 underlying volume is corrupt */
111#define CRYPT_FORCE_ENCRYPTION \
112 0x10 /* Set when it is time to encrypt this \
113 volume on boot. Everything in this \
114 structure is set up correctly as \
115 though device is encrypted except \
116 that the master key is encrypted with the \
117 default password. */
118#define CRYPT_FORCE_COMPLETE \
119 0x20 /* Set when the above encryption cycle is \
120 complete. On next cryptkeeper entry, match \
121 the password. If it matches fix the master \
122 key and remove this flag. */
123
124/* Allowed values for type in the structure below */
125#define CRYPT_TYPE_PASSWORD \
126 0 /* master_key is encrypted with a password \
127 * Must be zero to be compatible with pre-L \
128 * devices where type is always password.*/
129#define CRYPT_TYPE_DEFAULT \
130 1 /* master_key is encrypted with default \
131 * password */
132#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
133#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
134#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
135
136#define CRYPT_MNT_MAGIC 0xD0B5B1C4
137#define PERSIST_DATA_MAGIC 0xE950CD44
138
139/* Key Derivation Function algorithms */
140#define KDF_PBKDF2 1
141#define KDF_SCRYPT 2
142/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
143#define KDF_SCRYPT_KEYMASTER 5
144
145/* Maximum allowed keymaster blob size. */
146#define KEYMASTER_BLOB_SIZE 2048
147
148/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
149#define __le8 unsigned char
150
151#if !defined(SHA256_DIGEST_LENGTH)
152#define SHA256_DIGEST_LENGTH 32
153#endif
154
155/* This structure starts 16,384 bytes before the end of a hardware
156 * partition that is encrypted, or in a separate partition. It's location
157 * is specified by a property set in init.<device>.rc.
158 * The structure allocates 48 bytes for a key, but the real key size is
159 * specified in the struct. Currently, the code is hardcoded to use 128
160 * bit keys.
161 * The fields after salt are only valid in rev 1.1 and later stuctures.
162 * Obviously, the filesystem does not include the last 16 kbytes
163 * of the partition if the crypt_mnt_ftr lives at the end of the
164 * partition.
165 */
166
167struct crypt_mnt_ftr {
168 __le32 magic; /* See above */
169 __le16 major_version;
170 __le16 minor_version;
171 __le32 ftr_size; /* in bytes, not including key following */
172 __le32 flags; /* See above */
173 __le32 keysize; /* in bytes */
174 __le32 crypt_type; /* how master_key is encrypted. Must be a
175 * CRYPT_TYPE_XXX value */
176 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
177 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
178 mount, set to 0 on successful mount */
179 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
180 needed to decrypt this
181 partition, null terminated */
182 __le32 spare2; /* ignored */
183 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
184 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
185 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
186 * on device with that info, either the footer of the
187 * real_blkdevice or the metadata partition. */
188
189 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
190 * persistent data table*/
191
192 __le8 kdf_type; /* The key derivation function used. */
193
194 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
195 __le8 N_factor; /* (1 << N) */
196 __le8 r_factor; /* (1 << r) */
197 __le8 p_factor; /* (1 << p) */
198 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
199 we have to stop (e.g. power low) this is the last
200 encrypted 512 byte sector.*/
201 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
202 set, hash of first block, used
203 to validate before continuing*/
204
205 /* key_master key, used to sign the derived key which is then used to generate
206 * the intermediate key
207 * This key should be used for no other purposes! We use this key to sign unpadded
208 * data, which is acceptable but only if the key is not reused elsewhere. */
209 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
210 __le32 keymaster_blob_size;
211
212 /* Store scrypt of salted intermediate key. When decryption fails, we can
213 check if this matches, and if it does, we know that the problem is with the
214 drive, and there is no point in asking the user for more passwords.
215
216 Note that if any part of this structure is corrupt, this will not match and
217 we will continue to believe the user entered the wrong password. In that
218 case the only solution is for the user to enter a password enough times to
219 force a wipe.
220
221 Note also that there is no need to worry about migration. If this data is
222 wrong, we simply won't recognise a right password, and will continue to
223 prompt. On the first password change, this value will be populated and
224 then we will be OK.
225 */
226 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
227
228 /* sha of this structure with this element set to zero
229 Used when encrypting on reboot to validate structure before doing something
230 fatal
231 */
232 unsigned char sha256[SHA256_DIGEST_LENGTH];
233};
234
235/* Persistant data that should be available before decryption.
236 * Things like airplane mode, locale and timezone are kept
237 * here and can be retrieved by the CryptKeeper UI to properly
238 * configure the phone before asking for the password
239 * This is only valid if the major and minor version above
240 * is set to 1.1 or higher.
241 *
242 * This is a 4K structure. There are 2 copies, and the code alternates
243 * writing one and then clearing the previous one. The reading
244 * code reads the first valid copy it finds, based on the magic number.
245 * The absolute offset to the first of the two copies is kept in rev 1.1
246 * and higher crypt_mnt_ftr structures.
247 */
248struct crypt_persist_entry {
249 char key[PROPERTY_KEY_MAX];
250 char val[PROPERTY_VALUE_MAX];
251};
252
253/* Should be exactly 4K in size */
254struct crypt_persist_data {
255 __le32 persist_magic;
256 __le32 persist_valid_entries;
257 __le32 persist_spare[30];
258 struct crypt_persist_entry persist_entry[0];
259};
260
261static int wait_and_unmount(const char* mountpoint, bool kill);
262
263typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
264 void* params);
265
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800266#define UNUSED __attribute__((unused))
267
Jason parks70a4b3f2011-01-28 10:10:47 -0600268#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800269
270constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
271constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700272constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800273
274// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700275static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600276
Paul Crowley14c8c072018-09-18 13:30:21 -0700277#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700278
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530279#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700280#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800281
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800282#define CRYPTO_BLOCK_DEVICE "userdata"
283
284#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
285
Ken Sumrall29d8da82011-05-18 17:20:07 -0700286#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700287#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700288
Ken Sumralle919efe2012-09-29 17:07:41 -0700289#define TABLE_LOAD_RETRIES 10
290
Shawn Willden47ba10d2014-09-03 17:07:06 -0600291#define RSA_KEY_SIZE 2048
292#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
293#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600294#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530295#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700296
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700297#define RETRY_MOUNT_ATTEMPTS 10
298#define RETRY_MOUNT_DELAY_SECONDS 1
299
Paul Crowley5afbc622017-11-27 09:42:17 -0800300#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
301
Paul Crowley73473332017-11-21 15:43:51 -0800302static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
303
Greg Kaiser59ad0182018-02-16 13:01:36 -0800304static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700305static char* saved_mount_point;
306static int master_key_saved = 0;
307static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800308
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530309static int previous_type;
310
311#ifdef CONFIG_HW_DISK_ENCRYPTION
312static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
313 unsigned char *ikey, void *params);
314static void convert_key_to_hex_ascii(const unsigned char *master_key,
315 unsigned int keysize, char *master_key_ascii);
316static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
317static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
318 const char *passwd, const char *mount_point, const char *label);
319int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
320 const char *newpw);
321int cryptfs_check_passwd_hw(char *passwd);
322int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
323 unsigned char* master_key);
324
325static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
326 unsigned int keysize, char *master_key_ascii)
327{
328 unsigned int i, a;
329 unsigned char nibble;
330
331 for (i = 0, a = 0; i < keysize; i++, a += 2) {
332 /* For each byte, write out two ascii hex digits */
333 nibble = (master_key[i] >> 4) & 0xf;
334 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
335
336 nibble = master_key[i] & 0xf;
337 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
338 }
339
340 /* Add the null termination */
341 master_key_ascii[a] = '\0';
342}
343
344static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
345 unsigned char* salt,
346 const struct crypt_mnt_ftr *ftr)
347{
348 /* if newpw updated, return 0
349 * if newpw not updated return -1
350 */
351 int rc = -1;
352
353 if (should_use_keymaster()) {
354 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
355 SLOGE("scrypt failed");
356 } else {
357 rc = 0;
358 }
359 }
360
361 return rc;
362}
363
364static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
365{
366 unsigned char newpw[32] = {0};
367 int key_index;
368 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
369 key_index = set_hw_device_encryption_key(passwd,
370 (char*) crypt_ftr->crypto_type_name);
371 else
372 key_index = set_hw_device_encryption_key((const char*)newpw,
373 (char*) crypt_ftr->crypto_type_name);
374 return key_index;
375}
376
377static int verify_and_update_hw_fde_passwd(const char *passwd,
378 struct crypt_mnt_ftr* crypt_ftr)
379{
380 char* new_passwd = NULL;
381 unsigned char newpw[32] = {0};
382 int key_index = -1;
383 int passwd_updated = -1;
384 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
385
386 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
387 if (key_index < 0) {
388 ++crypt_ftr->failed_decrypt_count;
389
390 if (ascii_passwd_updated) {
391 SLOGI("Ascii password was updated");
392 } else {
393 /* Code in else part would execute only once:
394 * When device is upgraded from L->M release.
395 * Once upgraded, code flow should never come here.
396 * L release passed actual password in hex, so try with hex
397 * Each nible of passwd was encoded as a byte, so allocate memory
398 * twice of password len plus one more byte for null termination
399 */
400 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
401 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
402 if (new_passwd == NULL) {
403 SLOGE("System out of memory. Password verification incomplete");
404 goto out;
405 }
406 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
407 } else {
408 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
409 if (new_passwd == NULL) {
410 SLOGE("System out of memory. Password verification incomplete");
411 goto out;
412 }
413 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
414 strlen(passwd), new_passwd);
415 }
416 key_index = set_hw_device_encryption_key((const char*)new_passwd,
417 (char*) crypt_ftr->crypto_type_name);
418 if (key_index >=0) {
419 crypt_ftr->failed_decrypt_count = 0;
420 SLOGI("Hex password verified...will try to update with Ascii value");
421 /* Before updating password, tie that with keymaster to tie with ROT */
422
423 if (get_keymaster_hw_fde_passwd(passwd, newpw,
424 crypt_ftr->salt, crypt_ftr)) {
425 passwd_updated = update_hw_device_encryption_key(new_passwd,
426 passwd, (char*)crypt_ftr->crypto_type_name);
427 } else {
428 passwd_updated = update_hw_device_encryption_key(new_passwd,
429 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
430 }
431
432 if (passwd_updated >= 0) {
433 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
434 SLOGI("Ascii password recorded and updated");
435 } else {
436 SLOGI("Passwd verified, could not update...Will try next time");
437 }
438 } else {
439 ++crypt_ftr->failed_decrypt_count;
440 }
441 free(new_passwd);
442 }
443 } else {
444 if (!ascii_passwd_updated)
445 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
446 }
447out:
448 // update footer before leaving
449 put_crypt_ftr_and_key(crypt_ftr);
450 return key_index;
451}
452#endif
453
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700454/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700455static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000456 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700457}
458
459/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700460static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800461 if (ftr->keymaster_blob_size) {
462 SLOGI("Already have key");
463 return 0;
464 }
465
Paul Crowley14c8c072018-09-18 13:30:21 -0700466 int rc = keymaster_create_key_for_cryptfs_scrypt(
467 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
468 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000469 if (rc) {
470 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800471 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000472 ftr->keymaster_blob_size = 0;
473 }
474 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700475 return -1;
476 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000477 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700478}
479
Shawn Willdene17a9c42014-09-08 13:04:08 -0600480/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700481static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
482 const size_t object_size, unsigned char** signature,
483 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600484 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600485 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600486 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600487
Shawn Willdene17a9c42014-09-08 13:04:08 -0600488 // To sign a message with RSA, the message must satisfy two
489 // constraints:
490 //
491 // 1. The message, when interpreted as a big-endian numeric value, must
492 // be strictly less than the public modulus of the RSA key. Note
493 // that because the most significant bit of the public modulus is
494 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
495 // key), an n-bit message with most significant bit 0 always
496 // satisfies this requirement.
497 //
498 // 2. The message must have the same length in bits as the public
499 // modulus of the RSA key. This requirement isn't mathematically
500 // necessary, but is necessary to ensure consistency in
501 // implementations.
502 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600503 case KDF_SCRYPT_KEYMASTER:
504 // This ensures the most significant byte of the signed message
505 // is zero. We could have zero-padded to the left instead, but
506 // this approach is slightly more robust against changes in
507 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600508 // so) because we really should be using a proper deterministic
509 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800510 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600511 SLOGI("Signing safely-padded object");
512 break;
513 default:
514 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000515 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600516 }
Paul Crowley73473332017-11-21 15:43:51 -0800517 for (;;) {
518 auto result = keymaster_sign_object_for_cryptfs_scrypt(
519 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
520 to_sign_size, signature, signature_size);
521 switch (result) {
522 case KeymasterSignResult::ok:
523 return 0;
524 case KeymasterSignResult::upgrade:
525 break;
526 default:
527 return -1;
528 }
529 SLOGD("Upgrading key");
530 if (keymaster_upgrade_key_for_cryptfs_scrypt(
531 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
532 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
533 &ftr->keymaster_blob_size) != 0) {
534 SLOGE("Failed to upgrade key");
535 return -1;
536 }
537 if (put_crypt_ftr_and_key(ftr) != 0) {
538 SLOGE("Failed to write upgraded key to disk");
539 }
540 SLOGD("Key upgraded successfully");
541 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600542}
543
Paul Lawrence399317e2014-03-10 13:20:50 -0700544/* Store password when userdata is successfully decrypted and mounted.
545 * Cleared by cryptfs_clear_password
546 *
547 * To avoid a double prompt at boot, we need to store the CryptKeeper
548 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
549 * Since the entire framework is torn down and rebuilt after encryption,
550 * we have to use a daemon or similar to store the password. Since vold
551 * is secured against IPC except from system processes, it seems a reasonable
552 * place to store this.
553 *
554 * password should be cleared once it has been used.
555 *
556 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800557 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700558static char* password = 0;
559static int password_expiry_time = 0;
560static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800561
Paul Crowley14c8c072018-09-18 13:30:21 -0700562enum class RebootType { reboot, recovery, shutdown };
563static void cryptfs_reboot(RebootType rt) {
564 switch (rt) {
565 case RebootType::reboot:
566 property_set(ANDROID_RB_PROPERTY, "reboot");
567 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800568
Paul Crowley14c8c072018-09-18 13:30:21 -0700569 case RebootType::recovery:
570 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
571 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800572
Paul Crowley14c8c072018-09-18 13:30:21 -0700573 case RebootType::shutdown:
574 property_set(ANDROID_RB_PROPERTY, "shutdown");
575 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700576 }
Paul Lawrence87999172014-02-20 12:21:31 -0800577
Ken Sumralladfba362013-06-04 16:37:52 -0700578 sleep(20);
579
580 /* Shouldn't get here, reboot should happen before sleep times out */
581 return;
582}
583
Greg Kaiser38723f22018-02-16 13:35:35 -0800584namespace {
585
586struct CryptoType;
587
588// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700589const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800590
591struct CryptoType {
592 // We should only be constructing CryptoTypes as part of
593 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
594 // which isn't pure or fully protected as a concession to being able to
595 // do it all at compile time. Add new CryptoTypes in
596 // supported_crypto_types[] below.
597 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
598 constexpr CryptoType set_keysize(uint32_t size) const {
599 return CryptoType(this->property_name, this->crypto_name, size);
600 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700601 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800602 return CryptoType(property, this->crypto_name, this->keysize);
603 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700604 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800605 return CryptoType(this->property_name, crypto, this->keysize);
606 }
607
Paul Crowley14c8c072018-09-18 13:30:21 -0700608 constexpr const char* get_property_name() const { return property_name; }
609 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800610 constexpr uint32_t get_keysize() const { return keysize; }
611
Paul Crowley14c8c072018-09-18 13:30:21 -0700612 private:
613 const char* property_name;
614 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800615 uint32_t keysize;
616
Paul Crowley14c8c072018-09-18 13:30:21 -0700617 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800618 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700619 friend const CryptoType& get_crypto_type();
620 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800621};
622
623// We only want to parse this read-only property once. But we need to wait
624// until the system is initialized before we can read it. So we use a static
625// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700626const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800627 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
628 return crypto_type;
629}
630
631constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700632 .set_property_name("AES-128-CBC")
633 .set_crypto_name("aes-cbc-essiv:sha256")
634 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800635
636constexpr CryptoType supported_crypto_types[] = {
637 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800638 CryptoType()
639 .set_property_name("adiantum")
640 .set_crypto_name("xchacha12,aes-adiantum-plain64")
641 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800642 // Add new CryptoTypes here. Order is not important.
643};
644
Greg Kaiser38723f22018-02-16 13:35:35 -0800645// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
646// We confirm all supported_crypto_types have a small enough keysize and
647// had both set_property_name() and set_crypto_name() called.
648
649template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700650constexpr size_t array_length(T (&)[N]) {
651 return N;
652}
Greg Kaiser38723f22018-02-16 13:35:35 -0800653
654constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
655 return (index >= array_length(supported_crypto_types));
656}
657
Paul Crowley14c8c072018-09-18 13:30:21 -0700658constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800659 return ((crypto_type.get_property_name() != nullptr) &&
660 (crypto_type.get_crypto_name() != nullptr) &&
661 (crypto_type.get_keysize() <= MAX_KEY_LEN));
662}
663
664// Note in C++11 that constexpr functions can only have a single line.
665// So our code is a bit convoluted (using recursion instead of a loop),
666// but it's asserting at compile time that all of our key lengths are valid.
667constexpr bool validateSupportedCryptoTypes(size_t index) {
668 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700669 (isValidCryptoType(supported_crypto_types[index]) &&
670 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800671}
672
673static_assert(validateSupportedCryptoTypes(0),
674 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
675 "incompletely constructed.");
676// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
677
Greg Kaiser38723f22018-02-16 13:35:35 -0800678// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700679const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800680 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
681 char paramstr[PROPERTY_VALUE_MAX];
682
Paul Crowley14c8c072018-09-18 13:30:21 -0700683 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
684 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800685 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
686 return ctype;
687 }
688 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700689 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
690 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800691 return default_crypto_type;
692}
693
694} // namespace
695
Kenny Rootc4c70f12013-06-14 12:11:38 -0700696/**
697 * Gets the default device scrypt parameters for key derivation time tuning.
698 * The parameters should lead to about one second derivation time for the
699 * given device.
700 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700701static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700702 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000703 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700704
Paul Crowley63c18d32016-02-10 14:02:47 +0000705 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
706 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
707 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
708 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700709 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000710 ftr->N_factor = Nf;
711 ftr->r_factor = rf;
712 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700713}
714
Greg Kaiser57f9af62018-02-16 13:13:58 -0800715uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800716 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800717}
718
Paul Crowley14c8c072018-09-18 13:30:21 -0700719const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800720 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800721}
722
Tom Cherry4c5bde22019-01-29 14:34:01 -0800723static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800724 int fd, block_size;
725 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200726 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800727
Paul Crowley14c8c072018-09-18 13:30:21 -0700728 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800729 SLOGE("Cannot open device to get filesystem size ");
730 return 0;
731 }
732
733 if (lseek64(fd, 1024, SEEK_SET) < 0) {
734 SLOGE("Cannot seek to superblock");
735 return 0;
736 }
737
738 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
739 SLOGE("Cannot read superblock");
740 return 0;
741 }
742
743 close(fd);
744
Daniel Rosenberge82df162014-08-15 22:19:23 +0000745 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
746 SLOGE("Not a valid ext4 superblock");
747 return 0;
748 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800749 block_size = 1024 << sb.s_log_block_size;
750 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200751 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800752
753 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200754 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800755}
756
Tom Cherry4c5bde22019-01-29 14:34:01 -0800757static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
758 for (const auto& entry : fstab_default) {
759 if (!entry.fs_mgr_flags.vold_managed &&
760 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
761 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
762 if (key_loc != nullptr) {
763 *key_loc = entry.key_loc;
764 }
765 if (real_blk_device != nullptr) {
766 *real_blk_device = entry.blk_device;
767 }
768 return;
769 }
770 }
771}
772
Paul Crowley14c8c072018-09-18 13:30:21 -0700773static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
774 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200775 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700776 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700777 char key_loc[PROPERTY_VALUE_MAX];
778 char real_blkdev[PROPERTY_VALUE_MAX];
779 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700780
Paul Crowley14c8c072018-09-18 13:30:21 -0700781 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800782 std::string key_loc;
783 std::string real_blkdev;
784 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700785
Tom Cherry4c5bde22019-01-29 14:34:01 -0800786 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200787 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700788 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
789 * encryption info footer and key, and plenty of bytes to spare for future
790 * growth.
791 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800792 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200793 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700794 cached_data = 1;
795 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800796 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700797 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700798 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800799 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700800 cached_off = 0;
801 cached_data = 1;
802 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700803 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700804
Paul Crowley14c8c072018-09-18 13:30:21 -0700805 if (cached_data) {
806 if (metadata_fname) {
807 *metadata_fname = cached_metadata_fname;
808 }
809 if (off) {
810 *off = cached_off;
811 }
812 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700813 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700814
Paul Crowley14c8c072018-09-18 13:30:21 -0700815 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700816}
817
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800818/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700819static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800820 SHA256_CTX c;
821 SHA256_Init(&c);
822 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
823 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
824 SHA256_Final(crypt_ftr->sha256, &c);
825}
826
Ken Sumralle8744072011-01-18 22:01:55 -0800827/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828 * update the failed mount count but not change the key.
829 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700830static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
831 int fd;
832 unsigned int cnt;
833 /* starting_off is set to the SEEK_SET offset
834 * where the crypto structure starts
835 */
836 off64_t starting_off;
837 int rc = -1;
838 char* fname = NULL;
839 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800840
Paul Crowley14c8c072018-09-18 13:30:21 -0700841 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800842
Paul Crowley14c8c072018-09-18 13:30:21 -0700843 if (get_crypt_ftr_info(&fname, &starting_off)) {
844 SLOGE("Unable to get crypt_ftr_info\n");
845 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800846 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700847 if (fname[0] != '/') {
848 SLOGE("Unexpected value for crypto key location\n");
849 return -1;
850 }
851 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
852 SLOGE("Cannot open footer file %s for put\n", fname);
853 return -1;
854 }
Ken Sumralle8744072011-01-18 22:01:55 -0800855
Paul Crowley14c8c072018-09-18 13:30:21 -0700856 /* Seek to the start of the crypt footer */
857 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
858 SLOGE("Cannot seek to real block device footer\n");
859 goto errout;
860 }
861
862 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
863 SLOGE("Cannot write real block device footer\n");
864 goto errout;
865 }
866
867 fstat(fd, &statbuf);
868 /* If the keys are kept on a raw block device, do not try to truncate it. */
869 if (S_ISREG(statbuf.st_mode)) {
870 if (ftruncate(fd, 0x4000)) {
871 SLOGE("Cannot set footer file size\n");
872 goto errout;
873 }
874 }
875
876 /* Success! */
877 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800878
879errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700880 close(fd);
881 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800882}
883
Paul Crowley14c8c072018-09-18 13:30:21 -0700884static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800885 struct crypt_mnt_ftr copy;
886 memcpy(&copy, crypt_ftr, sizeof(copy));
887 set_ftr_sha(&copy);
888 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
889}
890
Paul Crowley14c8c072018-09-18 13:30:21 -0700891static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700892 return TEMP_FAILURE_RETRY(read(fd, buff, len));
893}
894
Paul Crowley14c8c072018-09-18 13:30:21 -0700895static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700896 return TEMP_FAILURE_RETRY(write(fd, buff, len));
897}
898
Paul Crowley14c8c072018-09-18 13:30:21 -0700899static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700900 memset(pdata, 0, len);
901 pdata->persist_magic = PERSIST_DATA_MAGIC;
902 pdata->persist_valid_entries = 0;
903}
904
905/* A routine to update the passed in crypt_ftr to the lastest version.
906 * fd is open read/write on the device that holds the crypto footer and persistent
907 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
908 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
909 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700910static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700911 int orig_major = crypt_ftr->major_version;
912 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700913
Kenny Root7434b312013-06-14 11:29:53 -0700914 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700915 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700916 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700917
Kenny Rootc4c70f12013-06-14 12:11:38 -0700918 SLOGW("upgrading crypto footer to 1.1");
919
Paul Crowley14c8c072018-09-18 13:30:21 -0700920 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700921 if (pdata == NULL) {
922 SLOGE("Cannot allocate persisent data\n");
923 return;
924 }
925 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
926
927 /* Need to initialize the persistent data area */
928 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
929 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100930 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700931 return;
932 }
933 /* Write all zeros to the first copy, making it invalid */
934 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
935
936 /* Write a valid but empty structure to the second copy */
937 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
938 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
939
940 /* Update the footer */
941 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
942 crypt_ftr->persist_data_offset[0] = pdata_offset;
943 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
944 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100945 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700946 }
947
Paul Lawrencef4faa572014-01-29 13:31:03 -0800948 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700949 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800950 /* But keep the old kdf_type.
951 * It will get updated later to KDF_SCRYPT after the password has been verified.
952 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700953 crypt_ftr->kdf_type = KDF_PBKDF2;
954 get_device_scrypt_params(crypt_ftr);
955 crypt_ftr->minor_version = 2;
956 }
957
Paul Lawrencef4faa572014-01-29 13:31:03 -0800958 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
959 SLOGW("upgrading crypto footer to 1.3");
960 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
961 crypt_ftr->minor_version = 3;
962 }
963
Kenny Root7434b312013-06-14 11:29:53 -0700964 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
965 if (lseek64(fd, offset, SEEK_SET) == -1) {
966 SLOGE("Cannot seek to crypt footer\n");
967 return;
968 }
969 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700970 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700971}
972
Paul Crowley14c8c072018-09-18 13:30:21 -0700973static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
974 int fd;
975 unsigned int cnt;
976 off64_t starting_off;
977 int rc = -1;
978 char* fname = NULL;
979 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700980
Paul Crowley14c8c072018-09-18 13:30:21 -0700981 if (get_crypt_ftr_info(&fname, &starting_off)) {
982 SLOGE("Unable to get crypt_ftr_info\n");
983 return -1;
984 }
985 if (fname[0] != '/') {
986 SLOGE("Unexpected value for crypto key location\n");
987 return -1;
988 }
989 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
990 SLOGE("Cannot open footer file %s for get\n", fname);
991 return -1;
992 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800993
Paul Crowley14c8c072018-09-18 13:30:21 -0700994 /* Make sure it's 16 Kbytes in length */
995 fstat(fd, &statbuf);
996 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
997 SLOGE("footer file %s is not the expected size!\n", fname);
998 goto errout;
999 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07001000
Paul Crowley14c8c072018-09-18 13:30:21 -07001001 /* Seek to the start of the crypt footer */
1002 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
1003 SLOGE("Cannot seek to real block device footer\n");
1004 goto errout;
1005 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07001006
Paul Crowley14c8c072018-09-18 13:30:21 -07001007 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
1008 SLOGE("Cannot read real block device footer\n");
1009 goto errout;
1010 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001011
Paul Crowley14c8c072018-09-18 13:30:21 -07001012 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
1013 SLOGE("Bad magic for real block device %s\n", fname);
1014 goto errout;
1015 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001016
Paul Crowley14c8c072018-09-18 13:30:21 -07001017 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
1018 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
1019 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
1020 goto errout;
1021 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001022
Paul Crowley14c8c072018-09-18 13:30:21 -07001023 // We risk buffer overflows with oversized keys, so we just reject them.
1024 // 0-sized keys are problematic (essentially by-passing encryption), and
1025 // AES-CBC key wrapping only works for multiples of 16 bytes.
1026 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
1027 (crypt_ftr->keysize > MAX_KEY_LEN)) {
1028 SLOGE(
1029 "Invalid keysize (%u) for block device %s; Must be non-zero, "
1030 "divisible by 16, and <= %d\n",
1031 crypt_ftr->keysize, fname, MAX_KEY_LEN);
1032 goto errout;
1033 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001034
Paul Crowley14c8c072018-09-18 13:30:21 -07001035 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
1036 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
1037 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
1038 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08001039
Paul Crowley14c8c072018-09-18 13:30:21 -07001040 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
1041 * copy on disk before returning.
1042 */
1043 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
1044 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
1045 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001046
Paul Crowley14c8c072018-09-18 13:30:21 -07001047 /* Success! */
1048 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001049
1050errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001051 close(fd);
1052 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001053}
1054
Paul Crowley14c8c072018-09-18 13:30:21 -07001055static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001056 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
1057 crypt_ftr->persist_data_offset[1]) {
1058 SLOGE("Crypt_ftr persist data regions overlap");
1059 return -1;
1060 }
1061
1062 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
1063 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
1064 return -1;
1065 }
1066
1067 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -07001068 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -07001069 CRYPT_FOOTER_OFFSET) {
1070 SLOGE("Persistent data extends past crypto footer");
1071 return -1;
1072 }
1073
1074 return 0;
1075}
1076
Paul Crowley14c8c072018-09-18 13:30:21 -07001077static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001078 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001079 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001080 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07001081 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001082 int found = 0;
1083 int fd;
1084 int ret;
1085 int i;
1086
1087 if (persist_data) {
1088 /* Nothing to do, we've already loaded or initialized it */
1089 return 0;
1090 }
1091
Ken Sumrall160b4d62013-04-22 12:15:39 -07001092 /* If not encrypted, just allocate an empty table and initialize it */
1093 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001094 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -08001095 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001096 if (pdata) {
1097 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1098 persist_data = pdata;
1099 return 0;
1100 }
1101 return -1;
1102 }
1103
Paul Crowley14c8c072018-09-18 13:30:21 -07001104 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001105 return -1;
1106 }
1107
Paul Crowley14c8c072018-09-18 13:30:21 -07001108 if ((crypt_ftr.major_version < 1) ||
1109 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001110 SLOGE("Crypt_ftr version doesn't support persistent data");
1111 return -1;
1112 }
1113
1114 if (get_crypt_ftr_info(&fname, NULL)) {
1115 return -1;
1116 }
1117
1118 ret = validate_persistent_data_storage(&crypt_ftr);
1119 if (ret) {
1120 return -1;
1121 }
1122
Paul Crowley14c8c072018-09-18 13:30:21 -07001123 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001124 if (fd < 0) {
1125 SLOGE("Cannot open %s metadata file", fname);
1126 return -1;
1127 }
1128
Wei Wang4375f1b2017-02-24 17:43:01 -08001129 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -08001130 if (pdata == NULL) {
1131 SLOGE("Cannot allocate memory for persistent data");
1132 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001133 }
1134
1135 for (i = 0; i < 2; i++) {
1136 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
1137 SLOGE("Cannot seek to read persistent data on %s", fname);
1138 goto err2;
1139 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001140 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001141 SLOGE("Error reading persistent data on iteration %d", i);
1142 goto err2;
1143 }
1144 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1145 found = 1;
1146 break;
1147 }
1148 }
1149
1150 if (!found) {
1151 SLOGI("Could not find valid persistent data, creating");
1152 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
1153 }
1154
1155 /* Success */
1156 persist_data = pdata;
1157 close(fd);
1158 return 0;
1159
1160err2:
1161 free(pdata);
1162
1163err:
1164 close(fd);
1165 return -1;
1166}
1167
Paul Crowley14c8c072018-09-18 13:30:21 -07001168static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001169 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001170 struct crypt_persist_data* pdata;
1171 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001172 off64_t write_offset;
1173 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001174 int fd;
1175 int ret;
1176
1177 if (persist_data == NULL) {
1178 SLOGE("No persistent data to save");
1179 return -1;
1180 }
1181
Paul Crowley14c8c072018-09-18 13:30:21 -07001182 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001183 return -1;
1184 }
1185
Paul Crowley14c8c072018-09-18 13:30:21 -07001186 if ((crypt_ftr.major_version < 1) ||
1187 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001188 SLOGE("Crypt_ftr version doesn't support persistent data");
1189 return -1;
1190 }
1191
1192 ret = validate_persistent_data_storage(&crypt_ftr);
1193 if (ret) {
1194 return -1;
1195 }
1196
1197 if (get_crypt_ftr_info(&fname, NULL)) {
1198 return -1;
1199 }
1200
Paul Crowley14c8c072018-09-18 13:30:21 -07001201 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001202 if (fd < 0) {
1203 SLOGE("Cannot open %s metadata file", fname);
1204 return -1;
1205 }
1206
Wei Wang4375f1b2017-02-24 17:43:01 -08001207 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001208 if (pdata == NULL) {
1209 SLOGE("Cannot allocate persistant data");
1210 goto err;
1211 }
1212
1213 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1214 SLOGE("Cannot seek to read persistent data on %s", fname);
1215 goto err2;
1216 }
1217
1218 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001219 SLOGE("Error reading persistent data before save");
1220 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001221 }
1222
1223 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1224 /* The first copy is the curent valid copy, so write to
1225 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001226 write_offset = crypt_ftr.persist_data_offset[1];
1227 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001228 } else {
1229 /* The second copy must be the valid copy, so write to
1230 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001231 write_offset = crypt_ftr.persist_data_offset[0];
1232 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001233 }
1234
1235 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001236 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001237 SLOGE("Cannot seek to write persistent data");
1238 goto err2;
1239 }
1240 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001241 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001242 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001243 SLOGE("Cannot seek to erase previous persistent data");
1244 goto err2;
1245 }
1246 fsync(fd);
1247 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001248 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001249 SLOGE("Cannot write to erase previous persistent data");
1250 goto err2;
1251 }
1252 fsync(fd);
1253 } else {
1254 SLOGE("Cannot write to save persistent data");
1255 goto err2;
1256 }
1257
1258 /* Success */
1259 free(pdata);
1260 close(fd);
1261 return 0;
1262
1263err2:
1264 free(pdata);
1265err:
1266 close(fd);
1267 return -1;
1268}
1269
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001270/* Convert a binary key of specified length into an ascii hex string equivalent,
1271 * without the leading 0x and with null termination
1272 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001273static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1274 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001275 unsigned int i, a;
1276 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001277
Paul Crowley14c8c072018-09-18 13:30:21 -07001278 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001279 /* For each byte, write out two ascii hex digits */
1280 nibble = (master_key[i] >> 4) & 0xf;
1281 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001282
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001283 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001284 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001285 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001286
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001287 /* Add the null termination */
1288 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001289}
1290
Eric Biggersed45ec32019-01-25 10:47:55 -08001291/*
1292 * If the ro.crypto.fde_sector_size system property is set, append the
1293 * parameters to make dm-crypt use the specified crypto sector size and round
1294 * the crypto device size down to a crypto sector boundary.
1295 */
David Andersonb9224732019-05-13 13:02:54 -07001296static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001297 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001298 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001299
Eric Biggersed45ec32019-01-25 10:47:55 -08001300 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1301 unsigned int sector_size;
1302
1303 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1304 (sector_size & (sector_size - 1)) != 0) {
1305 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1306 DM_CRYPT_SECTOR_SIZE, value);
1307 return -1;
1308 }
1309
David Andersonb9224732019-05-13 13:02:54 -07001310 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001311
1312 // With this option, IVs will match the sector numbering, instead
1313 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001314 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001315
1316 // Round the crypto device size down to a crypto sector boundary.
1317 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001318 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001319 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001320}
1321
Neeraj Soni73b46952019-09-12 16:47:27 +05301322#if defined(CONFIG_HW_DISK_ENCRYPTION) && !defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1323#define DM_CRYPT_BUF_SIZE 4096
1324
1325static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
1326 memset(io, 0, dataSize);
1327 io->data_size = dataSize;
1328 io->data_start = sizeof(struct dm_ioctl);
1329 io->version[0] = 4;
1330 io->version[1] = 0;
1331 io->version[2] = 0;
1332 io->flags = flags;
1333 if (name) {
1334 strlcpy(io->name, name, sizeof(io->name));
1335 }
1336}
1337
1338static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1339 const unsigned char* master_key, const char* real_blk_name,
1340 const char* name, int fd, const char* extra_params) {
1341 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1342 struct dm_ioctl* io;
1343 struct dm_target_spec* tgt;
1344 char* crypt_params;
1345 // We need two ASCII characters to represent each byte, and need space for
1346 // the '\0' terminator.
1347 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1348 size_t buff_offset;
1349 int i;
1350
1351 io = (struct dm_ioctl*)buffer;
1352
1353 /* Load the mapping table for this device */
1354 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
1355
1356 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1357 io->target_count = 1;
1358 tgt->status = 0;
1359 tgt->sector_start = 0;
1360 tgt->length = crypt_ftr->fs_size;
1361 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1362 buff_offset = crypt_params - buffer;
1363 SLOGI(
1364 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1365 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1366 extra_params);
1367 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1368 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1369 if (is_ice_enabled())
1370 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1371 else
1372 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1373 }
1374 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1375 crypt_ftr->crypto_type_name, master_key_ascii,
1376 real_blk_name, extra_params);
1377
1378 SLOGI("target_type = %s", tgt->target_type);
1379 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1380
1381 crypt_params += strlen(crypt_params) + 1;
1382 crypt_params =
1383 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1384 tgt->next = crypt_params - buffer;
1385
1386 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1387 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1388 break;
1389 }
1390 usleep(500000);
1391 }
1392
1393 if (i == TABLE_LOAD_RETRIES) {
1394 /* We failed to load the table, return an error */
1395 return -1;
1396 } else {
1397 return i + 1;
1398 }
1399}
1400
1401static int create_crypto_blk_dev_hw(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1402 const char* real_blk_name, char* crypto_blk_name, const char* name,
1403 uint32_t flags) {
1404 char buffer[DM_CRYPT_BUF_SIZE];
1405 struct dm_ioctl* io;
1406 unsigned int minor;
1407 int fd = 0;
1408 int err;
1409 int retval = -1;
1410 int version[3];
1411 int load_count;
1412 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1413 char progress[PROPERTY_VALUE_MAX] = {0};
1414 const char *extra_params;
1415
1416 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1417 SLOGE("Cannot open device-mapper\n");
1418 goto errout;
1419 }
1420
1421 io = (struct dm_ioctl*)buffer;
1422
1423 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1424 err = ioctl(fd, DM_DEV_CREATE, io);
1425 if (err) {
1426 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1427 goto errout;
1428 }
1429
1430 /* Get the device status, in particular, the name of it's device file */
1431 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1432 if (ioctl(fd, DM_DEV_STATUS, io)) {
1433 SLOGE("Cannot retrieve dm-crypt device status\n");
1434 goto errout;
1435 }
1436 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1437 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1438
1439 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1440 /* Set fde_enabled if either FDE completed or in-progress */
1441 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1442 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1443 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1444 if (is_ice_enabled()) {
1445 extra_params = "fde_enabled ice allow_encrypt_override";
1446 } else {
1447 extra_params = "fde_enabled allow_encrypt_override";
1448 }
1449 } else {
1450 extra_params = "fde_enabled allow_encrypt_override";
1451 }
1452 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1453 extra_params);
1454 }
1455
1456 if (load_count < 0) {
1457 SLOGE("Cannot load dm-crypt mapping table.\n");
1458 goto errout;
1459 } else if (load_count > 1) {
1460 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1461 }
1462
1463 /* Resume this device to activate it */
1464 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1465
1466 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1467 SLOGE("Cannot resume the dm-crypt device\n");
1468 goto errout;
1469 }
1470
1471 /* Ensure the dm device has been created before returning. */
1472 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1473 // WaitForFile generates a suitable log message
1474 goto errout;
1475 }
1476
1477 /* We made it here with no errors. Woot! */
1478 retval = 0;
1479
1480errout:
1481 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1482
1483 return retval;
1484}
1485#endif
1486
Paul Crowley5afbc622017-11-27 09:42:17 -08001487static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001488 const char* real_blk_name, std::string* crypto_blk_name,
1489 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001490 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001491
David Andersonb9224732019-05-13 13:02:54 -07001492 // We need two ASCII characters to represent each byte, and need space for
1493 // the '\0' terminator.
1494 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1495 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001496
David Andersonb9224732019-05-13 13:02:54 -07001497 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1498 (const char*)crypt_ftr->crypto_type_name,
1499 master_key_ascii, 0, real_blk_name, 0);
1500 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001501
Paul Crowley5afbc622017-11-27 09:42:17 -08001502 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001503 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001504 }
David Andersonb9224732019-05-13 13:02:54 -07001505 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001506 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001507 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001508 }
David Andersonb9224732019-05-13 13:02:54 -07001509
1510 DmTable table;
1511 table.AddTarget(std::move(target));
1512
1513 int load_count = 1;
1514 while (load_count < TABLE_LOAD_RETRIES) {
1515 if (dm.CreateDevice(name, table)) {
1516 break;
1517 }
1518 load_count++;
1519 }
1520
1521 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001522 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001523 return -1;
1524 }
1525 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001526 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1527 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001528
Paul Crowley81796e92020-02-07 11:27:49 -08001529 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001530 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1531 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001532 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001533
Paul Crowley298fa322018-10-30 15:59:24 -07001534 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001535 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowley298fa322018-10-30 15:59:24 -07001536 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001537 return -1;
Paul Crowley298fa322018-10-30 15:59:24 -07001538 }
David Andersonb9224732019-05-13 13:02:54 -07001539 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540}
1541
David Andersonb9224732019-05-13 13:02:54 -07001542static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001543 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001544 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001545 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1546 // to delete the device fails with EBUSY; for now, work around this by retrying.
1547 int tries = 5;
1548 while (tries-- > 0) {
1549 ret = dm.DeleteDevice(name);
1550 if (ret || errno != EBUSY) {
1551 break;
1552 }
1553 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1554 strerror(errno));
1555 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1556 }
1557 if (!ret) {
1558 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001559 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001560 }
David Andersonb9224732019-05-13 13:02:54 -07001561 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562}
1563
Paul Crowley14c8c072018-09-18 13:30:21 -07001564static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1565 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001566 SLOGI("Using pbkdf2 for cryptfs KDF");
1567
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001568 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001569 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1570 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001571}
1572
Paul Crowley14c8c072018-09-18 13:30:21 -07001573static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001574 SLOGI("Using scrypt for cryptfs KDF");
1575
Paul Crowley14c8c072018-09-18 13:30:21 -07001576 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001577
1578 int N = 1 << ftr->N_factor;
1579 int r = 1 << ftr->r_factor;
1580 int p = 1 << ftr->p_factor;
1581
1582 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001583 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001584 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001585
Paul Crowley14c8c072018-09-18 13:30:21 -07001586 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001587}
1588
Paul Crowley14c8c072018-09-18 13:30:21 -07001589static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1590 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001591 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1592
1593 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001594 size_t signature_size;
1595 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001596 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001597
1598 int N = 1 << ftr->N_factor;
1599 int r = 1 << ftr->r_factor;
1600 int p = 1 << ftr->p_factor;
1601
Paul Crowley14c8c072018-09-18 13:30:21 -07001602 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001603 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001604
1605 if (rc) {
1606 SLOGE("scrypt failed");
1607 return -1;
1608 }
1609
Paul Crowley14c8c072018-09-18 13:30:21 -07001610 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001611 SLOGE("Signing failed");
1612 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001613 }
1614
Paul Crowley14c8c072018-09-18 13:30:21 -07001615 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1616 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001617 free(signature);
1618
1619 if (rc) {
1620 SLOGE("scrypt failed");
1621 return -1;
1622 }
1623
1624 return 0;
1625}
1626
Paul Crowley14c8c072018-09-18 13:30:21 -07001627static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1628 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001629 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1630 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001631 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001632 EVP_CIPHER_CTX e_ctx;
1633 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001634 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001635
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001636 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001637 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001638
1639 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001640 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001641 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001642 SLOGE("keymaster_create_key failed");
1643 return -1;
1644 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001645
Paul Crowley14c8c072018-09-18 13:30:21 -07001646 if (scrypt_keymaster(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 case KDF_SCRYPT:
1653 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1654 SLOGE("scrypt failed");
1655 return -1;
1656 }
1657 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001658
Paul Crowley14c8c072018-09-18 13:30:21 -07001659 default:
1660 SLOGE("Invalid kdf_type");
1661 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001662 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001663
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001664 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001665 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001666 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1667 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001668 SLOGE("EVP_EncryptInit failed\n");
1669 return -1;
1670 }
1671 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001672
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001673 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001674 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1675 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001676 SLOGE("EVP_EncryptUpdate failed\n");
1677 return -1;
1678 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001679 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001680 SLOGE("EVP_EncryptFinal failed\n");
1681 return -1;
1682 }
1683
Greg Kaiser59ad0182018-02-16 13:01:36 -08001684 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001685 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1686 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001687 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001688
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001689 /* Store the scrypt of the intermediate key, so we can validate if it's a
1690 password error or mount error when things go wrong.
1691 Note there's no need to check for errors, since if this is incorrect, we
1692 simply won't wipe userdata, which is the correct default behavior
1693 */
1694 int N = 1 << crypt_ftr->N_factor;
1695 int r = 1 << crypt_ftr->r_factor;
1696 int p = 1 << crypt_ftr->p_factor;
1697
Paul Crowley14c8c072018-09-18 13:30:21 -07001698 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1699 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001700 sizeof(crypt_ftr->scrypted_intermediate_key));
1701
1702 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001703 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001704 }
1705
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001706 EVP_CIPHER_CTX_cleanup(&e_ctx);
1707
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001708 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001709}
1710
Paul Crowley14c8c072018-09-18 13:30:21 -07001711static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1712 const unsigned char* encrypted_master_key, size_t keysize,
1713 unsigned char* decrypted_master_key, kdf_func kdf,
1714 void* kdf_params, unsigned char** intermediate_key,
1715 size_t* intermediate_key_size) {
1716 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1717 EVP_CIPHER_CTX d_ctx;
1718 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719
Paul Crowley14c8c072018-09-18 13:30:21 -07001720 /* Turn the password into an intermediate key and IV that can decrypt the
1721 master key */
1722 if (kdf(passwd, salt, ikey, kdf_params)) {
1723 SLOGE("kdf failed");
1724 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001725 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001726
Paul Crowley14c8c072018-09-18 13:30:21 -07001727 /* Initialize the decryption engine */
1728 EVP_CIPHER_CTX_init(&d_ctx);
1729 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1730 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1731 return -1;
1732 }
1733 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1734 /* Decrypt the master key */
1735 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1736 keysize)) {
1737 return -1;
1738 }
1739 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1740 return -1;
1741 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001742
Paul Crowley14c8c072018-09-18 13:30:21 -07001743 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1744 return -1;
1745 }
1746
1747 /* Copy intermediate key if needed by params */
1748 if (intermediate_key && intermediate_key_size) {
1749 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1750 if (*intermediate_key) {
1751 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1752 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1753 }
1754 }
1755
1756 EVP_CIPHER_CTX_cleanup(&d_ctx);
1757
1758 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001759}
1760
Paul Crowley14c8c072018-09-18 13:30:21 -07001761static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001762 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001763 *kdf = scrypt_keymaster;
1764 *kdf_params = ftr;
1765 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001766 *kdf = scrypt;
1767 *kdf_params = ftr;
1768 } else {
1769 *kdf = pbkdf2;
1770 *kdf_params = NULL;
1771 }
1772}
1773
Paul Crowley14c8c072018-09-18 13:30:21 -07001774static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1775 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1776 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001777 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001778 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001779 int ret;
1780
1781 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001782 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1783 decrypted_master_key, kdf, kdf_params, intermediate_key,
1784 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001785 if (ret != 0) {
1786 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001787 }
1788
1789 return ret;
1790}
1791
Paul Crowley14c8c072018-09-18 13:30:21 -07001792static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1793 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001794 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001795
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001796 /* Get some random bits for a key and salt */
1797 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1798 return -1;
1799 }
1800 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1801 return -1;
1802 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001803
1804 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301805 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001806}
1807
Paul Crowley73be12d2020-02-03 12:22:03 -08001808static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001809 int i, err, rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301810#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001811
1812 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001813 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001814 if (umount(mountpoint) == 0) {
1815 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001816 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001817
1818 if (errno == EINVAL) {
1819 /* EINVAL is returned if the directory is not a mountpoint,
1820 * i.e. there is no filesystem mounted there. So just get out.
1821 */
1822 break;
1823 }
1824
1825 err = errno;
1826
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301827 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001828 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301829 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001830 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001831 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301832 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001833 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001834 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001835 }
1836 }
1837
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301838 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001839 }
1840
1841 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001842 SLOGD("unmounting %s succeeded\n", mountpoint);
1843 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001844 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001845 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1846 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1847 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001848 }
1849
1850 return rc;
1851}
1852
Paul Crowley14c8c072018-09-18 13:30:21 -07001853static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001854 // NOTE: post_fs_data results in init calling back around to vold, so all
1855 // callers to this method must be async
1856
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001857 /* Do the prep of the /data filesystem */
1858 property_set("vold.post_fs_data_done", "0");
1859 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001860 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001861
Ken Sumrallc5872692013-05-14 15:26:31 -07001862 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001863 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001864 /* We timed out to prep /data in time. Continue wait. */
1865 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001866 }
Wei Wang42e38102017-06-07 10:46:12 -07001867 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001868}
1869
Paul Crowley14c8c072018-09-18 13:30:21 -07001870static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001871 // Mark the footer as bad
1872 struct crypt_mnt_ftr crypt_ftr;
1873 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1874 SLOGE("Failed to get crypto footer - panic");
1875 return;
1876 }
1877
1878 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1879 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1880 SLOGE("Failed to set crypto footer - panic");
1881 return;
1882 }
1883}
1884
Paul Crowley14c8c072018-09-18 13:30:21 -07001885static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001886 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001887 SLOGE("Failed to mount tmpfs on data - panic");
1888 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001889 }
1890
1891 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1892 SLOGE("Failed to trigger post fs data - panic");
1893 return;
1894 }
1895
1896 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1897 SLOGE("Failed to trigger restart min framework - panic");
1898 return;
1899 }
1900}
1901
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001902/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001903static int cryptfs_restart_internal(int restart_main) {
Yifan Hong804afe12019-02-07 12:56:47 -08001904 std::string crypto_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301905#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001906 std::string blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301907#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001908 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001909 static int restart_successful = 0;
1910
1911 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001912 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001913 SLOGE("Encrypted filesystem not validated, aborting");
1914 return -1;
1915 }
1916
1917 if (restart_successful) {
1918 SLOGE("System already restarted with encrypted disk, aborting");
1919 return -1;
1920 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001921
Paul Lawrencef4faa572014-01-29 13:31:03 -08001922 if (restart_main) {
1923 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001924 * start all services in one of these classes: core, early_hal, hal,
1925 * main and late_start. To get to the minimal UI for PIN entry, we
1926 * need to start core, early_hal, hal and main. When we want to
1927 * shutdown the framework again, we need to stop most of the services in
1928 * these classes, but only those services that were started after
1929 * /data was mounted. This excludes critical services like vold and
1930 * ueventd, which need to keep running. We could possible stop
1931 * even fewer services, but because we want services to pick up APEX
1932 * libraries from the real /data, restarting is better, as it makes
1933 * these devices consistent with FBE devices and lets them use the
1934 * most recent code.
1935 *
1936 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001937 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001938 * We then restart the class core, hal, main, and also the class
1939 * late_start.
1940 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001941 * At the moment, I've only put a few things in late_start that I know
1942 * are not needed to bring up the framework, and that also cause problems
1943 * with unmounting the tmpfs /data, but I hope to add add more services
1944 * to the late_start class as we optimize this to decrease the delay
1945 * till the user is asked for the password to the filesystem.
1946 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001947
Martijn Coenenf629b002019-04-24 10:41:11 +02001948 /* The init files are setup to stop the right set of services when
1949 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001950 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001951 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001952 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001953
Paul Lawrencef4faa572014-01-29 13:31:03 -08001954 /* Ugh, shutting down the framework is not synchronous, so until it
1955 * can be fixed, this horrible hack will wait a moment for it all to
1956 * shut down before proceeding. Without it, some devices cannot
1957 * restart the graphics services.
1958 */
1959 sleep(2);
1960 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001961
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001962 /* Now that the framework is shutdown, we should be able to umount()
1963 * the tmpfs filesystem, and mount the real one.
1964 */
1965
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301966#if defined(CONFIG_HW_DISK_ENCRYPTION)
1967#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1968 if (is_ice_enabled()) {
Yifan Hong804afe12019-02-07 12:56:47 -08001969 get_crypt_info(nullptr, &blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301970 if (set_ice_param(START_ENCDEC)) {
1971 SLOGE("Failed to set ICE data");
1972 return -1;
1973 }
1974 }
1975#else
Yifan Hong804afe12019-02-07 12:56:47 -08001976 blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1977 if (blkdev.empty()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301978 SLOGE("fs_crypto_blkdev not set\n");
1979 return -1;
1980 }
1981 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1982#endif
1983#else
Yifan Hong804afe12019-02-07 12:56:47 -08001984 crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1985 if (crypto_blkdev.empty()) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001986 SLOGE("fs_crypto_blkdev not set\n");
1987 return -1;
1988 }
1989
Paul Crowley14c8c072018-09-18 13:30:21 -07001990 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301991#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001992 /* If ro.crypto.readonly is set to 1, mount the decrypted
1993 * filesystem readonly. This is used when /data is mounted by
1994 * recovery mode.
1995 */
1996 char ro_prop[PROPERTY_VALUE_MAX];
1997 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001998 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001999 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2000 if (entry != nullptr) {
2001 entry->flags |= MS_RDONLY;
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07002002 }
Doug Zongker6fd57712013-12-17 09:43:23 -08002003 }
JP Abgrall62c7af32014-06-16 13:01:23 -07002004
Ken Sumralle5032c42012-04-01 23:58:44 -07002005 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002006 int retries = RETRY_MOUNT_ATTEMPTS;
2007 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002008
2009 /*
2010 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
2011 * partitions in the fsck domain.
2012 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08002013 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002014 SLOGE("Failed to setexeccon");
2015 return -1;
2016 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07002017 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302018#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08002019 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev.data(), 0,
Bill Peckham0db11972018-10-10 10:25:42 -07002020 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302021#else
Yifan Hong804afe12019-02-07 12:56:47 -08002022 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev.data(), 0,
Daniel Rosenberg4f684712018-08-28 01:58:49 -07002023 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302024#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002025 if (mount_rc == FS_MGR_DOMNT_BUSY) {
2026 /* TODO: invoke something similar to
2027 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
2028 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302029#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08002030 SLOGI("Failed to mount %s because it is busy - waiting", blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302031#else
Yifan Hong804afe12019-02-07 12:56:47 -08002032 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302033#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002034 if (--retries) {
2035 sleep(RETRY_MOUNT_DELAY_SECONDS);
2036 } else {
2037 /* Let's hope that a reboot clears away whatever is keeping
2038 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07002039 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002040 }
2041 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302042#ifdef CONFIG_HW_DISK_ENCRYPTION
2043 if (--retries) {
2044 sleep(RETRY_MOUNT_DELAY_SECONDS);
2045 } else {
2046 SLOGE("Failed to mount decrypted data");
2047 cryptfs_set_corrupt();
2048 cryptfs_trigger_restart_min_framework();
2049 SLOGI("Started framework to offer wipe");
2050 return -1;
2051 }
2052#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002053 SLOGE("Failed to mount decrypted data");
2054 cryptfs_set_corrupt();
2055 cryptfs_trigger_restart_min_framework();
2056 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002057 if (setexeccon(NULL)) {
2058 SLOGE("Failed to setexeccon");
2059 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002060 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302061#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07002062 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002063 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08002064 if (setexeccon(NULL)) {
2065 SLOGE("Failed to setexeccon");
2066 return -1;
2067 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002068
Ken Sumralle5032c42012-04-01 23:58:44 -07002069 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002070 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09002071 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07002072
2073 /* startup service classes main and late_start */
2074 property_set("vold.decrypt", "trigger_restart_framework");
2075 SLOGD("Just triggered restart_framework\n");
2076
2077 /* Give it a few moments to get started */
2078 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302079#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002080 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302081#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002082
Ken Sumrall0cc16632011-01-18 20:32:26 -08002083 if (rc == 0) {
2084 restart_successful = 1;
2085 }
2086
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002087 return rc;
2088}
2089
Paul Crowley14c8c072018-09-18 13:30:21 -07002090int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002091 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07002092 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002093 SLOGE("cryptfs_restart not valid for file encryption:");
2094 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002095 }
2096
Paul Lawrencef4faa572014-01-29 13:31:03 -08002097 /* Call internal implementation forcing a restart of main service group */
2098 return cryptfs_restart_internal(1);
2099}
2100
Paul Crowley14c8c072018-09-18 13:30:21 -07002101static int do_crypto_complete(const char* mount_point) {
2102 struct crypt_mnt_ftr crypt_ftr;
2103 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002104
Paul Crowley14c8c072018-09-18 13:30:21 -07002105 property_get("ro.crypto.state", encrypted_state, "");
2106 if (strcmp(encrypted_state, "encrypted")) {
2107 SLOGE("not running with encryption, aborting");
2108 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08002109 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002110
Paul Crowley14c8c072018-09-18 13:30:21 -07002111 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07002112 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002113 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2114 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002115
Paul Crowley14c8c072018-09-18 13:30:21 -07002116 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002117 std::string key_loc;
2118 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002119
Paul Crowley14c8c072018-09-18 13:30:21 -07002120 /*
2121 * Only report this error if key_loc is a file and it exists.
2122 * If the device was never encrypted, and /data is not mountable for
2123 * some reason, returning 1 should prevent the UI from presenting the
2124 * a "enter password" screen, or worse, a "press button to wipe the
2125 * device" screen.
2126 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002127 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002128 SLOGE("master key file does not exist, aborting");
2129 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2130 } else {
2131 SLOGE("Error getting crypt footer and key\n");
2132 return CRYPTO_COMPLETE_BAD_METADATA;
2133 }
2134 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002135
Paul Crowley14c8c072018-09-18 13:30:21 -07002136 // Test for possible error flags
2137 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2138 SLOGE("Encryption process is partway completed\n");
2139 return CRYPTO_COMPLETE_PARTIAL;
2140 }
2141
2142 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2143 SLOGE("Encryption process was interrupted but cannot continue\n");
2144 return CRYPTO_COMPLETE_INCONSISTENT;
2145 }
2146
2147 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
2148 SLOGE("Encryption is successful but data is corrupt\n");
2149 return CRYPTO_COMPLETE_CORRUPT;
2150 }
2151
2152 /* We passed the test! We shall diminish, and return to the west */
2153 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002154}
2155
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302156#ifdef CONFIG_HW_DISK_ENCRYPTION
2157static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2158 const char *passwd, const char *mount_point, const char *label)
2159{
Bill Peckham0db11972018-10-10 10:25:42 -07002160 /* Allocate enough space for a 256 bit key, but we may use less */
2161 unsigned char decrypted_master_key[32];
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002162 char crypto_blkdev_hw[MAXPATHLEN];
2163 std::string crypto_blkdev;
Yifan Hong804afe12019-02-07 12:56:47 -08002164 std::string real_blkdev;
Bill Peckham0db11972018-10-10 10:25:42 -07002165 unsigned int orig_failed_decrypt_count;
2166 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302167
Bill Peckham0db11972018-10-10 10:25:42 -07002168 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2169 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302170
Yifan Hong804afe12019-02-07 12:56:47 -08002171 get_crypt_info(nullptr, &real_blkdev);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302172
Bill Peckham0db11972018-10-10 10:25:42 -07002173 int key_index = 0;
2174 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2175 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2176 if (key_index < 0) {
2177 rc = crypt_ftr->failed_decrypt_count;
2178 goto errout;
2179 }
2180 else {
2181 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302182#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Neeraj Soni73b46952019-09-12 16:47:27 +05302183 if (create_crypto_blk_dev_hw(crypt_ftr, (unsigned char*)&key_index,
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002184 real_blkdev.c_str(), crypto_blkdev_hw, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002185 SLOGE("Error creating decrypted block device");
2186 rc = -1;
2187 goto errout;
2188 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302189#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002190 } else {
2191 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002192 real_blkdev.c_str(), &crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002193 SLOGE("Error creating decrypted block device");
2194 rc = -1;
2195 goto errout;
2196 }
2197 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302198 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302199 }
2200
Bill Peckham0db11972018-10-10 10:25:42 -07002201 if (rc == 0) {
2202 crypt_ftr->failed_decrypt_count = 0;
2203 if (orig_failed_decrypt_count != 0) {
2204 put_crypt_ftr_and_key(crypt_ftr);
2205 }
2206
2207 /* Save the name of the crypto block device
2208 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302209#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002210 if (!is_ice_enabled())
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002211 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev_hw);
2212#else
Bill Peckham0db11972018-10-10 10:25:42 -07002213 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002214#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002215 master_key_saved = 1;
2216 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302217
Bill Peckham0db11972018-10-10 10:25:42 -07002218 errout:
2219 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302220}
2221#endif
2222
Paul Crowley14c8c072018-09-18 13:30:21 -07002223static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2224 const char* mount_point, const char* label) {
2225 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08002226 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002227 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002228 char tmp_mount_point[64];
2229 unsigned int orig_failed_decrypt_count;
2230 int rc;
2231 int use_keymaster = 0;
2232 int upgrade = 0;
2233 unsigned char* intermediate_key = 0;
2234 size_t intermediate_key_size = 0;
2235 int N = 1 << crypt_ftr->N_factor;
2236 int r = 1 << crypt_ftr->r_factor;
2237 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302238
Paul Crowley14c8c072018-09-18 13:30:21 -07002239 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2240 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002241
Paul Crowley14c8c072018-09-18 13:30:21 -07002242 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2243 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2244 &intermediate_key_size)) {
2245 SLOGE("Failed to decrypt master key\n");
2246 rc = -1;
2247 goto errout;
2248 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002249 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002250
Tom Cherry4c5bde22019-01-29 14:34:01 -08002251 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002252
Paul Crowley14c8c072018-09-18 13:30:21 -07002253 // Create crypto block device - all (non fatal) code paths
2254 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08002255 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08002256 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002257 SLOGE("Error creating decrypted block device\n");
2258 rc = -1;
2259 goto errout;
2260 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002261
Paul Crowley14c8c072018-09-18 13:30:21 -07002262 /* Work out if the problem is the password or the data */
2263 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002264
Paul Crowley14c8c072018-09-18 13:30:21 -07002265 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2266 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2267 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002268
Paul Crowley14c8c072018-09-18 13:30:21 -07002269 // Does the key match the crypto footer?
2270 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2271 sizeof(scrypted_intermediate_key)) == 0) {
2272 SLOGI("Password matches");
2273 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002274 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002275 /* Try mounting the file system anyway, just in case the problem's with
2276 * the footer, not the key. */
2277 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2278 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08002279 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
2280 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002281 SLOGE("Error temp mounting decrypted block device\n");
2282 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002283
Paul Crowley14c8c072018-09-18 13:30:21 -07002284 rc = ++crypt_ftr->failed_decrypt_count;
2285 put_crypt_ftr_and_key(crypt_ftr);
2286 } else {
2287 /* Success! */
2288 SLOGI("Password did not match but decrypted drive mounted - continue");
2289 umount(tmp_mount_point);
2290 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002291 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002292 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002293
Paul Crowley14c8c072018-09-18 13:30:21 -07002294 if (rc == 0) {
2295 crypt_ftr->failed_decrypt_count = 0;
2296 if (orig_failed_decrypt_count != 0) {
2297 put_crypt_ftr_and_key(crypt_ftr);
2298 }
2299
2300 /* Save the name of the crypto block device
2301 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08002302 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07002303
2304 /* Also save a the master key so we can reencrypted the key
2305 * the key when we want to change the password on it. */
2306 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2307 saved_mount_point = strdup(mount_point);
2308 master_key_saved = 1;
2309 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2310 rc = 0;
2311
2312 // Upgrade if we're not using the latest KDF.
2313 use_keymaster = keymaster_check_compatibility();
2314 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2315 // Don't allow downgrade
2316 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2317 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2318 upgrade = 1;
2319 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2320 crypt_ftr->kdf_type = KDF_SCRYPT;
2321 upgrade = 1;
2322 }
2323
2324 if (upgrade) {
2325 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002326 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002327 if (!rc) {
2328 rc = put_crypt_ftr_and_key(crypt_ftr);
2329 }
2330 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2331
2332 // Do not fail even if upgrade failed - machine is bootable
2333 // Note that if this code is ever hit, there is a *serious* problem
2334 // since KDFs should never fail. You *must* fix the kdf before
2335 // proceeding!
2336 if (rc) {
2337 SLOGW(
2338 "Upgrade failed with error %d,"
2339 " but continuing with previous state",
2340 rc);
2341 rc = 0;
2342 }
2343 }
2344 }
2345
2346errout:
2347 if (intermediate_key) {
2348 memset(intermediate_key, 0, intermediate_key_size);
2349 free(intermediate_key);
2350 }
2351 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002352}
2353
Ken Sumrall29d8da82011-05-18 17:20:07 -07002354/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002355 * Called by vold when it's asked to mount an encrypted external
2356 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002357 * as any metadata is been stored in a separate, small partition. We
2358 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002359 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002360int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08002361 std::string* out_crypto_blkdev) {
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002362 if (key.size() != cryptfs_get_keysize()) {
2363 SLOGE("Raw keysize %zu does not match crypt keysize %" PRIu32, key.size(),
2364 cryptfs_get_keysize());
2365 return -1;
2366 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002367 uint64_t nr_sec = 0;
2368 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002369 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002370 return -1;
2371 }
2372
Jeff Sharkey9c484982015-03-31 10:35:33 -07002373 struct crypt_mnt_ftr ext_crypt_ftr;
2374 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2375 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002376 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002377 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002378 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002379 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002380 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002381 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2382 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002383
Paul Crowley3d98f5d2020-02-07 11:49:09 -08002384 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
2385 real_blkdev, out_crypto_blkdev, label, flags);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002386}
2387
Paul Crowley14c8c072018-09-18 13:30:21 -07002388int cryptfs_crypto_complete(void) {
2389 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002390}
2391
Paul Crowley14c8c072018-09-18 13:30:21 -07002392int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002393 char encrypted_state[PROPERTY_VALUE_MAX];
2394 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002395 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2396 SLOGE(
2397 "encrypted fs already validated or not running with encryption,"
2398 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002399 return -1;
2400 }
2401
2402 if (get_crypt_ftr_and_key(crypt_ftr)) {
2403 SLOGE("Error getting crypt footer and key");
2404 return -1;
2405 }
2406
2407 return 0;
2408}
2409
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302410#ifdef CONFIG_HW_DISK_ENCRYPTION
2411int cryptfs_check_passwd_hw(const char* passwd)
2412{
2413 struct crypt_mnt_ftr crypt_ftr;
2414 int rc;
2415 unsigned char master_key[KEY_LEN_BYTES];
2416
2417 /* get key */
2418 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2419 SLOGE("Error getting crypt footer and key");
2420 return -1;
2421 }
2422
2423 /*
2424 * in case of manual encryption (from GUI), the encryption is done with
2425 * default password
2426 */
2427 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2428 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2429 * which was created with actual password before reboot.
2430 */
2431 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2432 if (rc) {
2433 SLOGE("password doesn't match");
2434 rc = ++crypt_ftr.failed_decrypt_count;
2435 put_crypt_ftr_and_key(&crypt_ftr);
2436 return rc;
2437 }
2438
2439 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2440 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2441
2442 if (rc) {
2443 SLOGE("Default password did not match on reboot encryption");
2444 return rc;
2445 }
2446
2447 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2448 put_crypt_ftr_and_key(&crypt_ftr);
2449 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2450 if (rc) {
2451 SLOGE("Could not change password on reboot encryption");
2452 return rc;
2453 }
2454 } else
2455 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2456 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2457
2458 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2459 cryptfs_clear_password();
2460 password = strdup(passwd);
2461 struct timespec now;
2462 clock_gettime(CLOCK_BOOTTIME, &now);
2463 password_expiry_time = now.tv_sec + password_max_age_seconds;
2464 }
2465
2466 return rc;
2467}
2468#endif
2469
Paul Crowley14c8c072018-09-18 13:30:21 -07002470int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002471 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002472 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002473 SLOGE("cryptfs_check_passwd not valid for file encryption");
2474 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002475 }
2476
Paul Lawrencef4faa572014-01-29 13:31:03 -08002477 struct crypt_mnt_ftr crypt_ftr;
2478 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002479
Paul Lawrencef4faa572014-01-29 13:31:03 -08002480 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002481 if (rc) {
2482 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002483 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002484 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002485
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302486#ifdef CONFIG_HW_DISK_ENCRYPTION
2487 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2488 return cryptfs_check_passwd_hw(passwd);
2489#endif
2490
Paul Crowley14c8c072018-09-18 13:30:21 -07002491 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002492 if (rc) {
2493 SLOGE("Password did not match");
2494 return rc;
2495 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002496
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002497 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2498 // Here we have a default actual password but a real password
2499 // we must test against the scrypted value
2500 // First, we must delete the crypto block device that
2501 // test_mount_encrypted_fs leaves behind as a side effect
2502 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002503 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2504 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002505 if (rc) {
2506 SLOGE("Default password did not match on reboot encryption");
2507 return rc;
2508 }
2509
2510 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2511 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302512 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002513 if (rc) {
2514 SLOGE("Could not change password on reboot encryption");
2515 return rc;
2516 }
2517 }
2518
2519 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002520 cryptfs_clear_password();
2521 password = strdup(passwd);
2522 struct timespec now;
2523 clock_gettime(CLOCK_BOOTTIME, &now);
2524 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002525 }
2526
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002527 return rc;
2528}
2529
Paul Crowley14c8c072018-09-18 13:30:21 -07002530int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002531 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002532 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002533 char encrypted_state[PROPERTY_VALUE_MAX];
2534 int rc;
2535
2536 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002537 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002538 SLOGE("device not encrypted, aborting");
2539 return -2;
2540 }
2541
2542 if (!master_key_saved) {
2543 SLOGE("encrypted fs not yet mounted, aborting");
2544 return -1;
2545 }
2546
2547 if (!saved_mount_point) {
2548 SLOGE("encrypted fs failed to save mount point, aborting");
2549 return -1;
2550 }
2551
Ken Sumrall160b4d62013-04-22 12:15:39 -07002552 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002553 SLOGE("Error getting crypt footer and key\n");
2554 return -1;
2555 }
2556
2557 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2558 /* If the device has no password, then just say the password is valid */
2559 rc = 0;
2560 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302561#ifdef CONFIG_HW_DISK_ENCRYPTION
2562 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2563 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2564 rc = 0;
2565 else
2566 rc = -1;
2567 } else {
2568 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2569 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2570 /* They match, the password is correct */
2571 rc = 0;
2572 } else {
2573 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2574 sleep(1);
2575 rc = 1;
2576 }
2577 }
2578#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002579 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002580 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2581 /* They match, the password is correct */
2582 rc = 0;
2583 } else {
2584 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2585 sleep(1);
2586 rc = 1;
2587 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302588#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002589 }
2590
2591 return rc;
2592}
2593
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002594/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002595 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002596 * Presumably, at a minimum, the caller will update the
2597 * filesystem size and crypto_type_name after calling this function.
2598 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002599static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002600 off64_t off;
2601
2602 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002603 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002604 ftr->major_version = CURRENT_MAJOR_VERSION;
2605 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002606 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002607 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002608
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002609 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002610 case 1:
2611 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2612 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002613
Paul Crowley14c8c072018-09-18 13:30:21 -07002614 case 0:
2615 ftr->kdf_type = KDF_SCRYPT;
2616 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002617
Paul Crowley14c8c072018-09-18 13:30:21 -07002618 default:
2619 SLOGE("keymaster_check_compatibility failed");
2620 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002621 }
2622
Kenny Rootc4c70f12013-06-14 12:11:38 -07002623 get_device_scrypt_params(ftr);
2624
Ken Sumrall160b4d62013-04-22 12:15:39 -07002625 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2626 if (get_crypt_ftr_info(NULL, &off) == 0) {
2627 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002628 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002629 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002630
2631 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002632}
2633
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002634#define FRAMEWORK_BOOT_WAIT 60
2635
Paul Crowley14c8c072018-09-18 13:30:21 -07002636static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2637 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002638 if (fd == -1) {
2639 SLOGE("Error opening file %s", filename);
2640 return -1;
2641 }
2642
2643 char block[CRYPT_INPLACE_BUFSIZE];
2644 memset(block, 0, sizeof(block));
2645 if (unix_read(fd, block, sizeof(block)) < 0) {
2646 SLOGE("Error reading file %s", filename);
2647 close(fd);
2648 return -1;
2649 }
2650
2651 close(fd);
2652
2653 SHA256_CTX c;
2654 SHA256_Init(&c);
2655 SHA256_Update(&c, block, sizeof(block));
2656 SHA256_Final(buf, &c);
2657
2658 return 0;
2659}
2660
Paul Crowley81796e92020-02-07 11:27:49 -08002661static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2662 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002663 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002664 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002665
Paul Lawrence87999172014-02-20 12:21:31 -08002666 /* The size of the userdata partition, and add in the vold volumes below */
2667 tot_encryption_size = crypt_ftr->fs_size;
2668
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002669 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002670 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002671
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002672 if (rc == ENABLE_INPLACE_ERR_DEV) {
2673 /* Hack for b/17898962 */
2674 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2675 cryptfs_reboot(RebootType::reboot);
2676 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002677
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002678 if (!rc) {
2679 crypt_ftr->encrypted_upto = cur_encryption_done;
2680 }
Paul Lawrence87999172014-02-20 12:21:31 -08002681
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002682 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2683 /* The inplace routine never actually sets the progress to 100% due
2684 * to the round down nature of integer division, so set it here */
2685 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002686 }
2687
2688 return rc;
2689}
2690
Paul Crowleyb64933a2017-10-31 08:25:55 -07002691static int vold_unmountAll(void) {
2692 VolumeManager* vm = VolumeManager::Instance();
2693 return vm->unmountAll();
2694}
2695
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002696int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002697 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002698 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002699 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002700 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002701 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002702 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002703 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002704 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002705 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002706 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002707 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002708 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002709 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302710#ifdef CONFIG_HW_DISK_ENCRYPTION
2711 unsigned char newpw[32];
2712 int key_index = 0;
2713#endif
2714 int index = 0;
Tri Vo15bbe222019-06-21 12:21:48 -07002715 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302716
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002717 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002718 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2719 /* An encryption was underway and was interrupted */
2720 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2721 crypt_ftr.encrypted_upto = 0;
2722 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002723
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002724 /* At this point, we are in an inconsistent state. Until we successfully
2725 complete encryption, a reboot will leave us broken. So mark the
2726 encryption failed in case that happens.
2727 On successfully completing encryption, remove this flag */
2728 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002729
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002730 put_crypt_ftr_and_key(&crypt_ftr);
2731 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2732 if (!check_ftr_sha(&crypt_ftr)) {
2733 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2734 put_crypt_ftr_and_key(&crypt_ftr);
2735 goto error_unencrypted;
2736 }
2737
2738 /* Doing a reboot-encryption*/
2739 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2740 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2741 rebootEncryption = true;
2742 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002743 } else {
2744 // We don't want to accidentally reference invalid data.
2745 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002746 }
2747
2748 property_get("ro.crypto.state", encrypted_state, "");
2749 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2750 SLOGE("Device is already running encrypted, aborting");
2751 goto error_unencrypted;
2752 }
2753
Tom Cherry4c5bde22019-01-29 14:34:01 -08002754 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002755
Ken Sumrall3ed82362011-01-28 23:31:16 -08002756 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002757 uint64_t nr_sec;
2758 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002759 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002760 goto error_unencrypted;
2761 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002762
2763 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002764 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002765 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002766 fs_size_sec = get_fs_size(real_blkdev.c_str());
2767 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002768
Paul Lawrence87999172014-02-20 12:21:31 -08002769 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002770
2771 if (fs_size_sec > max_fs_size_sec) {
2772 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2773 goto error_unencrypted;
2774 }
2775 }
2776
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002777 /* Get a wakelock as this may take a while, and we don't want the
2778 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2779 * wants to keep the screen on, it can grab a full wakelock.
2780 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002781 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002782 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002783
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002784 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002785 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002786 */
2787 property_set("vold.decrypt", "trigger_shutdown_framework");
2788 SLOGD("Just asked init to shut down class main\n");
2789
Jeff Sharkey9c484982015-03-31 10:35:33 -07002790 /* Ask vold to unmount all devices that it manages */
2791 if (vold_unmountAll()) {
2792 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002793 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002794
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002795 /* no_ui means we are being called from init, not settings.
2796 Now we always reboot from settings, so !no_ui means reboot
2797 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002798 if (!no_ui) {
2799 /* Try fallback, which is to reboot and try there */
2800 onlyCreateHeader = true;
2801 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2802 if (breadcrumb == 0) {
2803 SLOGE("Failed to create breadcrumb file");
2804 goto error_shutting_down;
2805 }
2806 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002807 }
2808
2809 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002810 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002811 /* Now that /data is unmounted, we need to mount a tmpfs
2812 * /data, set a property saying we're doing inplace encryption,
2813 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002814 */
xzj7e38a3a2018-10-12 10:17:11 +08002815 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002816 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002817 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002818 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002819 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002820 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002821
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002822 /* restart the framework. */
2823 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002824 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002825
Ken Sumrall92736ef2012-10-17 20:57:14 -07002826 /* Ugh, shutting down the framework is not synchronous, so until it
2827 * can be fixed, this horrible hack will wait a moment for it all to
2828 * shut down before proceeding. Without it, some devices cannot
2829 * restart the graphics services.
2830 */
2831 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002832 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002833
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002834 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002835 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002836 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002837 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2838 goto error_shutting_down;
2839 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002840
Tom Cherry4c5bde22019-01-29 14:34:01 -08002841 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002842 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002843 } else {
2844 crypt_ftr.fs_size = nr_sec;
2845 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002846 /* At this point, we are in an inconsistent state. Until we successfully
2847 complete encryption, a reboot will leave us broken. So mark the
2848 encryption failed in case that happens.
2849 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002850 if (onlyCreateHeader) {
2851 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2852 } else {
2853 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2854 }
Paul Lawrence87999172014-02-20 12:21:31 -08002855 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302856#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002857 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2858 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302859#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002860 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2861 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302862#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002863
Paul Lawrence87999172014-02-20 12:21:31 -08002864 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002865 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2866 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002867 SLOGE("Cannot create encrypted master key\n");
2868 goto error_shutting_down;
2869 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002870
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002871 /* Replace scrypted intermediate key if we are preparing for a reboot */
2872 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002873 unsigned char fake_master_key[MAX_KEY_LEN];
2874 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002875 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002876 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002877 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002878 }
2879
Paul Lawrence87999172014-02-20 12:21:31 -08002880 /* Write the key to the end of the partition */
2881 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002882
Paul Lawrence87999172014-02-20 12:21:31 -08002883 /* If any persistent data has been remembered, save it.
2884 * If none, create a valid empty table and save that.
2885 */
2886 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002887 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2888 if (pdata) {
2889 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2890 persist_data = pdata;
2891 }
Paul Lawrence87999172014-02-20 12:21:31 -08002892 }
2893 if (persist_data) {
2894 save_persistent_data();
2895 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002896 }
2897
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302898 /* When encryption triggered from settings, encryption starts after reboot.
2899 So set the encryption key when the actual encryption starts.
2900 */
2901#ifdef CONFIG_HW_DISK_ENCRYPTION
2902 if (previously_encrypted_upto == 0) {
2903 if (!rebootEncryption)
2904 clear_hw_device_encryption_key();
2905
2906 if (get_keymaster_hw_fde_passwd(
2907 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2908 newpw, crypt_ftr.salt, &crypt_ftr))
2909 key_index = set_hw_device_encryption_key(
2910 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2911 (char*)crypt_ftr.crypto_type_name);
2912 else
2913 key_index = set_hw_device_encryption_key((const char*)newpw,
2914 (char*) crypt_ftr.crypto_type_name);
2915 if (key_index < 0)
2916 goto error_shutting_down;
2917
2918 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2919 put_crypt_ftr_and_key(&crypt_ftr);
2920 }
2921#endif
2922
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002923 if (onlyCreateHeader) {
2924 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002925 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302926 } else {
2927 /* Do extra work for a better UX when doing the long inplace encryption */
2928 /* Now that /data is unmounted, we need to mount a tmpfs
2929 * /data, set a property saying we're doing inplace encryption,
2930 * and restart the framework.
2931 */
2932 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2933 goto error_shutting_down;
2934 }
2935 /* Tells the framework that inplace encryption is starting */
2936 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002937
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302938 /* restart the framework. */
2939 /* Create necessary paths on /data */
2940 prep_data_fs();
2941
2942 /* Ugh, shutting down the framework is not synchronous, so until it
2943 * can be fixed, this horrible hack will wait a moment for it all to
2944 * shut down before proceeding. Without it, some devices cannot
2945 * restart the graphics services.
2946 */
2947 sleep(2);
2948
Ajay Dudani87701e22014-09-17 21:02:52 -07002949 /* startup service classes main and late_start */
2950 property_set("vold.decrypt", "trigger_restart_min_framework");
2951 SLOGD("Just triggered restart_min_framework\n");
2952
2953 /* OK, the framework is restarted and will soon be showing a
2954 * progress bar. Time to setup an encrypted mapping, and
2955 * either write a new filesystem, or encrypt in place updating
2956 * the progress bar as we work.
2957 */
2958 }
2959
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002960 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302961#ifdef CONFIG_HW_DISK_ENCRYPTION
2962 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302963#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002964 crypto_blkdev = real_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302965#else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002966 create_crypto_blk_dev_hw(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302967 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302968#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302969 else
Steven Laver7fe4cdb2020-02-14 13:18:26 -08002970 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302971 CRYPTO_BLOCK_DEVICE, 0);
2972#else
Paul Crowley81796e92020-02-07 11:27:49 -08002973 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002974 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302975#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002976
Paul Lawrence87999172014-02-20 12:21:31 -08002977 /* If we are continuing, check checksums match */
2978 rc = 0;
2979 if (previously_encrypted_upto) {
2980 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302981#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2982 if (set_ice_param(START_ENCDEC)) {
2983 SLOGE("Failed to set ICE data");
2984 goto error_shutting_down;
2985 }
2986#endif
Paul Crowley81796e92020-02-07 11:27:49 -08002987 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002988
Paul Crowley14c8c072018-09-18 13:30:21 -07002989 if (!rc &&
2990 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002991 SLOGE("Checksums do not match - trigger wipe");
2992 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002993 }
2994 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002995
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302996#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2997 if (set_ice_param(START_ENC)) {
2998 SLOGE("Failed to set ICE data");
2999 goto error_shutting_down;
3000 }
3001#endif
Paul Lawrence87999172014-02-20 12:21:31 -08003002 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08003003 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08003004 previously_encrypted_upto);
3005 }
3006
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05303007#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
3008 if (set_ice_param(START_ENCDEC)) {
3009 SLOGE("Failed to set ICE data");
3010 goto error_shutting_down;
3011 }
3012#endif
Paul Lawrence87999172014-02-20 12:21:31 -08003013 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003014 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08003015 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003016 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003017 SLOGE("Error calculating checksum for continuing encryption");
3018 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003019 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003020 }
3021
3022 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05303023#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
3024 if (!is_ice_enabled())
3025 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
3026#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003027 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05303028#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07003029
Paul Crowley14c8c072018-09-18 13:30:21 -07003030 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003031 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003032 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003033
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003034 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003035 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3036 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003037 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003038 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003039
Paul Lawrence6bfed202014-07-28 12:47:22 -07003040 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003041
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003042 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
3043 char value[PROPERTY_VALUE_MAX];
3044 property_get("ro.crypto.state", value, "");
3045 if (!strcmp(value, "")) {
3046 /* default encryption - continue first boot sequence */
3047 property_set("ro.crypto.state", "encrypted");
3048 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07003049 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003050 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
3051 // Bring up cryptkeeper that will check the password and set it
3052 property_set("vold.decrypt", "trigger_shutdown_framework");
3053 sleep(2);
3054 property_set("vold.encrypt_progress", "");
3055 cryptfs_trigger_restart_min_framework();
3056 } else {
3057 cryptfs_check_passwd(DEFAULT_PASSWORD);
3058 cryptfs_restart_internal(1);
3059 }
3060 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003061 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003062 sleep(2); /* Give the UI a chance to show 100% progress */
3063 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08003064 }
Paul Lawrence87999172014-02-20 12:21:31 -08003065 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003066 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07003067 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08003068 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003069 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003070 char value[PROPERTY_VALUE_MAX];
3071
Ken Sumrall319369a2012-06-27 16:30:18 -07003072 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003073 if (!strcmp(value, "1")) {
3074 /* wipe data if encryption failed */
3075 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08003076 std::string err;
3077 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07003078 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08003079 if (!write_bootloader_message(options, &err)) {
3080 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003081 }
Josh Gaofec44372017-08-28 13:22:55 -07003082 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003083 } else {
3084 /* set property to trigger dialog */
3085 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003086 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003087 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003088 }
3089
Ken Sumrall3ed82362011-01-28 23:31:16 -08003090 /* hrm, the encrypt step claims success, but the reboot failed.
3091 * This should not happen.
3092 * Set the property and return. Hope the framework can deal with it.
3093 */
3094 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003095 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003096
3097error_unencrypted:
3098 property_set("vold.encrypt_progress", "error_not_encrypted");
3099 return -1;
3100
3101error_shutting_down:
3102 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3103 * but the framework is stopped and not restarted to show the error, so it's up to
3104 * vold to restart the system.
3105 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003106 SLOGE(
3107 "Error enabling encryption after framework is shutdown, no data changed, restarting "
3108 "system");
Josh Gaofec44372017-08-28 13:22:55 -07003109 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003110
3111 /* shouldn't get here */
3112 property_set("vold.encrypt_progress", "error_shutting_down");
3113 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003114}
3115
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003116int cryptfs_enable(int type, const char* passwd, int no_ui) {
3117 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003118}
3119
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08003120int cryptfs_enable_default(int no_ui) {
3121 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08003122}
3123
Bill Peckham0db11972018-10-10 10:25:42 -07003124int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07003125 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003126 SLOGE("cryptfs_changepw not valid for file encryption");
3127 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003128 }
3129
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003130 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003131 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003132
3133 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003134 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003135 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003136 return -1;
3137 }
3138
Paul Lawrencef4faa572014-01-29 13:31:03 -08003139 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3140 SLOGE("Invalid crypt_type %d", crypt_type);
3141 return -1;
3142 }
3143
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003144 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003145 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003146 SLOGE("Error getting crypt footer and key");
3147 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003148 }
3149
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303150#ifdef CONFIG_HW_DISK_ENCRYPTION
3151 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
3152 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
3153 else {
3154 crypt_ftr.crypt_type = crypt_type;
3155
3156 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
3157 DEFAULT_PASSWORD : newpw,
3158 crypt_ftr.salt,
3159 saved_master_key,
3160 crypt_ftr.master_key,
3161 &crypt_ftr, false);
3162 if (rc) {
3163 SLOGE("Encrypt master key failed: %d", rc);
3164 return -1;
3165 }
3166 /* save the key */
3167 put_crypt_ftr_and_key(&crypt_ftr);
3168
3169 return 0;
3170 }
3171#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003172 crypt_ftr.crypt_type = crypt_type;
3173
Paul Crowley14c8c072018-09-18 13:30:21 -07003174 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07003175 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
3176 false);
JP Abgrall933216c2015-02-11 13:44:32 -08003177 if (rc) {
3178 SLOGE("Encrypt master key failed: %d", rc);
3179 return -1;
3180 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003181 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003182 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003183
3184 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303185#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003186}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003187
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303188#ifdef CONFIG_HW_DISK_ENCRYPTION
3189int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3190{
3191 struct crypt_mnt_ftr crypt_ftr;
3192 int rc;
3193 int previous_type;
3194
3195 /* get key */
3196 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3197 SLOGE("Error getting crypt footer and key");
3198 return -1;
3199 }
3200
3201 previous_type = crypt_ftr.crypt_type;
3202 int rc1;
3203 unsigned char tmp_curpw[32] = {0};
3204 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3205 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3206 crypt_ftr.salt, &crypt_ftr);
3207
3208 crypt_ftr.crypt_type = crypt_type;
3209
3210 int ret, rc2;
3211 unsigned char tmp_newpw[32] = {0};
3212
3213 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3214 DEFAULT_PASSWORD : newpw , tmp_newpw,
3215 crypt_ftr.salt, &crypt_ftr);
3216
3217 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3218 ret = update_hw_device_encryption_key(
3219 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3220 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3221 (char*)crypt_ftr.crypto_type_name);
3222 if (ret) {
3223 SLOGE("Error updating device encryption hardware key ret %d", ret);
3224 return -1;
3225 } else {
3226 SLOGI("Encryption hardware key updated");
3227 }
3228 }
3229
3230 /* save the key */
3231 put_crypt_ftr_and_key(&crypt_ftr);
3232 return 0;
3233}
3234#endif
3235
Rubin Xu85c01f92014-10-13 12:49:54 +01003236static unsigned int persist_get_max_entries(int encrypted) {
3237 struct crypt_mnt_ftr crypt_ftr;
3238 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003239
3240 /* If encrypted, use the values from the crypt_ftr, otherwise
3241 * use the values for the current spec.
3242 */
3243 if (encrypted) {
3244 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003245 /* Something is wrong, assume no space for entries */
3246 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003247 }
3248 dsize = crypt_ftr.persist_data_size;
3249 } else {
3250 dsize = CRYPT_PERSIST_DATA_SIZE;
3251 }
3252
Rubin Xud78181b2018-10-09 16:13:38 +01003253 if (dsize > sizeof(struct crypt_persist_data)) {
3254 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3255 } else {
3256 return 0;
3257 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003258}
3259
Paul Crowley14c8c072018-09-18 13:30:21 -07003260static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003261 unsigned int i;
3262
3263 if (persist_data == NULL) {
3264 return -1;
3265 }
3266 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3267 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3268 /* We found it! */
3269 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3270 return 0;
3271 }
3272 }
3273
3274 return -1;
3275}
3276
Paul Crowley14c8c072018-09-18 13:30:21 -07003277static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003278 unsigned int i;
3279 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003280 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003281
3282 if (persist_data == NULL) {
3283 return -1;
3284 }
3285
Rubin Xu85c01f92014-10-13 12:49:54 +01003286 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003287
3288 num = persist_data->persist_valid_entries;
3289
3290 for (i = 0; i < num; i++) {
3291 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3292 /* We found an existing entry, update it! */
3293 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3294 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3295 return 0;
3296 }
3297 }
3298
3299 /* We didn't find it, add it to the end, if there is room */
3300 if (persist_data->persist_valid_entries < max_persistent_entries) {
3301 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3302 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3303 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3304 persist_data->persist_valid_entries++;
3305 return 0;
3306 }
3307
3308 return -1;
3309}
3310
Rubin Xu85c01f92014-10-13 12:49:54 +01003311/**
3312 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3313 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3314 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003315int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003316 std::string key_ = key;
3317 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003318
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003319 std::string parsed_field;
3320 unsigned parsed_index;
3321
3322 std::string::size_type split = key_.find_last_of('_');
3323 if (split == std::string::npos) {
3324 parsed_field = key_;
3325 parsed_index = 0;
3326 } else {
3327 parsed_field = key_.substr(0, split);
3328 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003329 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003330
3331 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003332}
3333
3334/*
3335 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3336 * remaining entries starting from index will be deleted.
3337 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3338 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3339 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3340 *
3341 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003342static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003343 unsigned int i;
3344 unsigned int j;
3345 unsigned int num;
3346
3347 if (persist_data == NULL) {
3348 return PERSIST_DEL_KEY_ERROR_OTHER;
3349 }
3350
3351 num = persist_data->persist_valid_entries;
3352
Paul Crowley14c8c072018-09-18 13:30:21 -07003353 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003354 // Filter out to-be-deleted entries in place.
3355 for (i = 0; i < num; i++) {
3356 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3357 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3358 j++;
3359 }
3360 }
3361
3362 if (j < num) {
3363 persist_data->persist_valid_entries = j;
3364 // Zeroise the remaining entries
3365 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3366 return PERSIST_DEL_KEY_OK;
3367 } else {
3368 // Did not find an entry matching the given fieldname
3369 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3370 }
3371}
3372
Paul Crowley14c8c072018-09-18 13:30:21 -07003373static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003374 unsigned int i;
3375 unsigned int count;
3376
3377 if (persist_data == NULL) {
3378 return -1;
3379 }
3380
3381 count = 0;
3382 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3383 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3384 count++;
3385 }
3386 }
3387
3388 return count;
3389}
3390
Ken Sumrall160b4d62013-04-22 12:15:39 -07003391/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003392int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003393 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003394 SLOGE("Cannot get field when file encrypted");
3395 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003396 }
3397
Ken Sumrall160b4d62013-04-22 12:15:39 -07003398 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003399 /* CRYPTO_GETFIELD_OK is success,
3400 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3401 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3402 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003403 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003404 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3405 int i;
3406 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003407
3408 if (persist_data == NULL) {
3409 load_persistent_data();
3410 if (persist_data == NULL) {
3411 SLOGE("Getfield error, cannot load persistent data");
3412 goto out;
3413 }
3414 }
3415
Rubin Xu85c01f92014-10-13 12:49:54 +01003416 // Read value from persistent entries. If the original value is split into multiple entries,
3417 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003418 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003419 // 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 -07003420 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003421 // value too small
3422 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3423 goto out;
3424 }
3425 rc = CRYPTO_GETFIELD_OK;
3426
3427 for (i = 1; /* break explicitly */; i++) {
3428 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003429 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003430 // If the fieldname is very long, we stop as soon as it begins to overflow the
3431 // maximum field length. At this point we have in fact fully read out the original
3432 // value because cryptfs_setfield would not allow fields with longer names to be
3433 // written in the first place.
3434 break;
3435 }
3436 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003437 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3438 // value too small.
3439 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3440 goto out;
3441 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003442 } else {
3443 // Exhaust all entries.
3444 break;
3445 }
3446 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003447 } else {
3448 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003449 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003450 }
3451
3452out:
3453 return rc;
3454}
3455
3456/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003457int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003458 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003459 SLOGE("Cannot set field when file encrypted");
3460 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003461 }
3462
Ken Sumrall160b4d62013-04-22 12:15:39 -07003463 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003464 /* 0 is success, negative values are error */
3465 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003466 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003467 unsigned int field_id;
3468 char temp_field[PROPERTY_KEY_MAX];
3469 unsigned int num_entries;
3470 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003471
3472 if (persist_data == NULL) {
3473 load_persistent_data();
3474 if (persist_data == NULL) {
3475 SLOGE("Setfield error, cannot load persistent data");
3476 goto out;
3477 }
3478 }
3479
3480 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003481 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003482 encrypted = 1;
3483 }
3484
Rubin Xu85c01f92014-10-13 12:49:54 +01003485 // Compute the number of entries required to store value, each entry can store up to
3486 // (PROPERTY_VALUE_MAX - 1) chars
3487 if (strlen(value) == 0) {
3488 // Empty value also needs one entry to store.
3489 num_entries = 1;
3490 } else {
3491 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3492 }
3493
3494 max_keylen = strlen(fieldname);
3495 if (num_entries > 1) {
3496 // Need an extra "_%d" suffix.
3497 max_keylen += 1 + log10(num_entries);
3498 }
3499 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3500 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003501 goto out;
3502 }
3503
Rubin Xu85c01f92014-10-13 12:49:54 +01003504 // Make sure we have enough space to write the new value
3505 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3506 persist_get_max_entries(encrypted)) {
3507 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3508 goto out;
3509 }
3510
3511 // Now that we know persist_data has enough space for value, let's delete the old field first
3512 // to make up space.
3513 persist_del_keys(fieldname, 0);
3514
3515 if (persist_set_key(fieldname, value, encrypted)) {
3516 // fail to set key, should not happen as we have already checked the available space
3517 SLOGE("persist_set_key() error during setfield()");
3518 goto out;
3519 }
3520
3521 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003522 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003523
3524 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3525 // fail to set key, should not happen as we have already checked the available space.
3526 SLOGE("persist_set_key() error during setfield()");
3527 goto out;
3528 }
3529 }
3530
Ken Sumrall160b4d62013-04-22 12:15:39 -07003531 /* If we are running encrypted, save the persistent data now */
3532 if (encrypted) {
3533 if (save_persistent_data()) {
3534 SLOGE("Setfield error, cannot save persistent data");
3535 goto out;
3536 }
3537 }
3538
Rubin Xu85c01f92014-10-13 12:49:54 +01003539 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003540
3541out:
3542 return rc;
3543}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003544
3545/* Checks userdata. Attempt to mount the volume if default-
3546 * encrypted.
3547 * On success trigger next init phase and return 0.
3548 * Currently do not handle failure - see TODO below.
3549 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003550int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003551 int crypt_type = cryptfs_get_password_type();
3552 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3553 SLOGE("Bad crypt type - error");
3554 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003555 SLOGD(
3556 "Password is not default - "
3557 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003558 property_set("vold.decrypt", "trigger_restart_min_framework");
3559 return 0;
3560 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3561 SLOGD("Password is default - restarting filesystem");
3562 cryptfs_restart_internal(0);
3563 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003564 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003565 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003566 }
3567
Paul Lawrence6bfed202014-07-28 12:47:22 -07003568 /** Corrupt. Allow us to boot into framework, which will detect bad
3569 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003570 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003571 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003572 return 0;
3573}
3574
3575/* Returns type of the password, default, pattern, pin or password.
3576 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003577int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003578 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003579 SLOGE("cryptfs_get_password_type not valid for file encryption");
3580 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003581 }
3582
Paul Lawrencef4faa572014-01-29 13:31:03 -08003583 struct crypt_mnt_ftr crypt_ftr;
3584
3585 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3586 SLOGE("Error getting crypt footer and key\n");
3587 return -1;
3588 }
3589
Paul Lawrence6bfed202014-07-28 12:47:22 -07003590 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3591 return -1;
3592 }
3593
Paul Lawrencef4faa572014-01-29 13:31:03 -08003594 return crypt_ftr.crypt_type;
3595}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003596
Paul Crowley14c8c072018-09-18 13:30:21 -07003597const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003598 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003599 SLOGE("cryptfs_get_password not valid for file encryption");
3600 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003601 }
3602
Paul Lawrence399317e2014-03-10 13:20:50 -07003603 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003604 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003605 if (now.tv_sec < password_expiry_time) {
3606 return password;
3607 } else {
3608 cryptfs_clear_password();
3609 return 0;
3610 }
3611}
3612
Paul Crowley14c8c072018-09-18 13:30:21 -07003613void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003614 if (password) {
3615 size_t len = strlen(password);
3616 memset(password, 0, len);
3617 free(password);
3618 password = 0;
3619 password_expiry_time = 0;
3620 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003621}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003622
Paul Crowley14c8c072018-09-18 13:30:21 -07003623int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003624 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3625 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003626}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303627
3628int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3629{
3630 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3631 SLOGE("Failed to initialize crypt_ftr");
3632 return -1;
3633 }
3634
3635 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3636 crypt_ftr->salt, crypt_ftr)) {
3637 SLOGE("Cannot create encrypted master key\n");
3638 return -1;
3639 }
3640
3641 //crypt_ftr->keysize = key_length / 8;
3642 return 0;
3643}
3644
3645int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3646 unsigned char* master_key)
3647{
3648 int rc;
3649
3650 unsigned char* intermediate_key = 0;
3651 size_t intermediate_key_size = 0;
3652
3653 if (password == 0 || *password == 0) {
3654 password = DEFAULT_PASSWORD;
3655 }
3656
3657 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3658 &intermediate_key_size);
3659
3660 if (rc) {
3661 SLOGE("Can't calculate intermediate key");
3662 return rc;
3663 }
3664
3665 int N = 1 << ftr->N_factor;
3666 int r = 1 << ftr->r_factor;
3667 int p = 1 << ftr->p_factor;
3668
3669 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3670
3671 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3672 ftr->salt, sizeof(ftr->salt), N, r, p,
3673 scrypted_intermediate_key,
3674 sizeof(scrypted_intermediate_key));
3675
3676 free(intermediate_key);
3677
3678 if (rc) {
3679 SLOGE("Can't scrypt intermediate key");
3680 return rc;
3681 }
3682
3683 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3684 intermediate_key_size);
3685}