blob: 04497b08ef5c855d716151d70bb57b16e9760849 [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 Rosenberg65f99c92018-08-28 01:58:49 -070021#include "Checkpoint.h"
Paul Crowley220567c2020-02-07 12:45:20 -080022#include "CryptoType.h"
Logan Chiend557d762018-05-02 11:36:45 +080023#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070024#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080025#include "Keymaster.h"
26#include "Process.h"
27#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070028#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080029#include "VoldUtil.h"
30#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080031
Eric Biggersed45ec32019-01-25 10:47:55 -080032#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080033#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080034#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080035#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080036#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080037#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070038#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070040#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070041#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070042#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080043#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080044#include <logwrap/logwrap.h>
45#include <openssl/evp.h>
46#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070048#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080049
50#include <ctype.h>
51#include <errno.h>
52#include <fcntl.h>
53#include <inttypes.h>
54#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080055#include <linux/kdev_t.h>
56#include <math.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080060#include <sys/mount.h>
61#include <sys/param.h>
62#include <sys/stat.h>
63#include <sys/types.h>
64#include <sys/wait.h>
65#include <time.h>
66#include <unistd.h>
67
Wei Wang4375f1b2017-02-24 17:43:01 -080068extern "C" {
69#include <crypto_scrypt.h>
70}
Mark Salyzyn3e971272014-01-21 13:27:04 -080071
Eric Biggersed45ec32019-01-25 10:47:55 -080072using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080073using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080074using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080075using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080076using android::vold::KeyBuffer;
Paul Crowley4eac2642020-02-12 11:04:05 -080077using android::vold::KeyGeneration;
David Andersonb9224732019-05-13 13:02:54 -070078using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070079using namespace std::chrono_literals;
80
Paul Crowley73be12d2020-02-03 12:22:03 -080081/* The current cryptfs version */
82#define CURRENT_MAJOR_VERSION 1
83#define CURRENT_MINOR_VERSION 3
84
85#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
86#define CRYPT_PERSIST_DATA_SIZE 0x1000
87
88#define MAX_CRYPTO_TYPE_NAME_LEN 64
89
90#define MAX_KEY_LEN 48
91#define SALT_LEN 16
92#define SCRYPT_LEN 32
93
94/* definitions of flags in the structure below */
95#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
96#define CRYPT_ENCRYPTION_IN_PROGRESS \
97 0x2 /* Encryption partially completed, \
98 encrypted_upto valid*/
99#define CRYPT_INCONSISTENT_STATE \
100 0x4 /* Set when starting encryption, clear when \
101 exit cleanly, either through success or \
102 correctly marked partial encryption */
103#define CRYPT_DATA_CORRUPT \
104 0x8 /* Set when encryption is fine, but the \
105 underlying volume is corrupt */
106#define CRYPT_FORCE_ENCRYPTION \
107 0x10 /* Set when it is time to encrypt this \
108 volume on boot. Everything in this \
109 structure is set up correctly as \
110 though device is encrypted except \
111 that the master key is encrypted with the \
112 default password. */
113#define CRYPT_FORCE_COMPLETE \
114 0x20 /* Set when the above encryption cycle is \
115 complete. On next cryptkeeper entry, match \
116 the password. If it matches fix the master \
117 key and remove this flag. */
118
119/* Allowed values for type in the structure below */
120#define CRYPT_TYPE_PASSWORD \
121 0 /* master_key is encrypted with a password \
122 * Must be zero to be compatible with pre-L \
123 * devices where type is always password.*/
124#define CRYPT_TYPE_DEFAULT \
125 1 /* master_key is encrypted with default \
126 * password */
127#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
128#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
129#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
130
131#define CRYPT_MNT_MAGIC 0xD0B5B1C4
132#define PERSIST_DATA_MAGIC 0xE950CD44
133
134/* Key Derivation Function algorithms */
135#define KDF_PBKDF2 1
136#define KDF_SCRYPT 2
137/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
138#define KDF_SCRYPT_KEYMASTER 5
139
140/* Maximum allowed keymaster blob size. */
141#define KEYMASTER_BLOB_SIZE 2048
142
143/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
144#define __le8 unsigned char
145
146#if !defined(SHA256_DIGEST_LENGTH)
147#define SHA256_DIGEST_LENGTH 32
148#endif
149
150/* This structure starts 16,384 bytes before the end of a hardware
151 * partition that is encrypted, or in a separate partition. It's location
152 * is specified by a property set in init.<device>.rc.
153 * The structure allocates 48 bytes for a key, but the real key size is
154 * specified in the struct. Currently, the code is hardcoded to use 128
155 * bit keys.
156 * The fields after salt are only valid in rev 1.1 and later stuctures.
157 * Obviously, the filesystem does not include the last 16 kbytes
158 * of the partition if the crypt_mnt_ftr lives at the end of the
159 * partition.
160 */
161
162struct crypt_mnt_ftr {
163 __le32 magic; /* See above */
164 __le16 major_version;
165 __le16 minor_version;
166 __le32 ftr_size; /* in bytes, not including key following */
167 __le32 flags; /* See above */
168 __le32 keysize; /* in bytes */
169 __le32 crypt_type; /* how master_key is encrypted. Must be a
170 * CRYPT_TYPE_XXX value */
171 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
172 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
173 mount, set to 0 on successful mount */
174 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
175 needed to decrypt this
176 partition, null terminated */
177 __le32 spare2; /* ignored */
178 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
179 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
180 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
181 * on device with that info, either the footer of the
182 * real_blkdevice or the metadata partition. */
183
184 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
185 * persistent data table*/
186
187 __le8 kdf_type; /* The key derivation function used. */
188
189 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
190 __le8 N_factor; /* (1 << N) */
191 __le8 r_factor; /* (1 << r) */
192 __le8 p_factor; /* (1 << p) */
193 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
194 we have to stop (e.g. power low) this is the last
195 encrypted 512 byte sector.*/
196 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
197 set, hash of first block, used
198 to validate before continuing*/
199
200 /* key_master key, used to sign the derived key which is then used to generate
201 * the intermediate key
202 * This key should be used for no other purposes! We use this key to sign unpadded
203 * data, which is acceptable but only if the key is not reused elsewhere. */
204 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
205 __le32 keymaster_blob_size;
206
207 /* Store scrypt of salted intermediate key. When decryption fails, we can
208 check if this matches, and if it does, we know that the problem is with the
209 drive, and there is no point in asking the user for more passwords.
210
211 Note that if any part of this structure is corrupt, this will not match and
212 we will continue to believe the user entered the wrong password. In that
213 case the only solution is for the user to enter a password enough times to
214 force a wipe.
215
216 Note also that there is no need to worry about migration. If this data is
217 wrong, we simply won't recognise a right password, and will continue to
218 prompt. On the first password change, this value will be populated and
219 then we will be OK.
220 */
221 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
222
223 /* sha of this structure with this element set to zero
224 Used when encrypting on reboot to validate structure before doing something
225 fatal
226 */
227 unsigned char sha256[SHA256_DIGEST_LENGTH];
228};
229
230/* Persistant data that should be available before decryption.
231 * Things like airplane mode, locale and timezone are kept
232 * here and can be retrieved by the CryptKeeper UI to properly
233 * configure the phone before asking for the password
234 * This is only valid if the major and minor version above
235 * is set to 1.1 or higher.
236 *
237 * This is a 4K structure. There are 2 copies, and the code alternates
238 * writing one and then clearing the previous one. The reading
239 * code reads the first valid copy it finds, based on the magic number.
240 * The absolute offset to the first of the two copies is kept in rev 1.1
241 * and higher crypt_mnt_ftr structures.
242 */
243struct crypt_persist_entry {
244 char key[PROPERTY_KEY_MAX];
245 char val[PROPERTY_VALUE_MAX];
246};
247
248/* Should be exactly 4K in size */
249struct crypt_persist_data {
250 __le32 persist_magic;
251 __le32 persist_valid_entries;
252 __le32 persist_spare[30];
253 struct crypt_persist_entry persist_entry[0];
254};
255
256static int wait_and_unmount(const char* mountpoint, bool kill);
257
258typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
259 void* params);
260
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800261#define UNUSED __attribute__((unused))
262
Jason parks70a4b3f2011-01-28 10:10:47 -0600263#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800264
265constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
266constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700267constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800268
269// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700270static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600271
Paul Crowley14c8c072018-09-18 13:30:21 -0700272#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700273
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700274#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800275
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800276#define CRYPTO_BLOCK_DEVICE "userdata"
277
278#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
279
Ken Sumrall29d8da82011-05-18 17:20:07 -0700280#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700281#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700282
Ken Sumralle919efe2012-09-29 17:07:41 -0700283#define TABLE_LOAD_RETRIES 10
284
Shawn Willden47ba10d2014-09-03 17:07:06 -0600285#define RSA_KEY_SIZE 2048
286#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
287#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600288#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700289
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700290#define RETRY_MOUNT_ATTEMPTS 10
291#define RETRY_MOUNT_DELAY_SECONDS 1
292
Paul Crowley5afbc622017-11-27 09:42:17 -0800293#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
294
Paul Crowley73473332017-11-21 15:43:51 -0800295static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
296
Greg Kaiser59ad0182018-02-16 13:01:36 -0800297static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700298static char* saved_mount_point;
299static int master_key_saved = 0;
300static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800301
Paul Crowley220567c2020-02-07 12:45:20 -0800302constexpr CryptoType aes_128_cbc = CryptoType()
303 .set_config_name("AES-128-CBC")
304 .set_kernel_name("aes-cbc-essiv:sha256")
305 .set_keysize(16);
306
307constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
308
309static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
310 array_length(supported_crypto_types)),
311 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
312 "incompletely constructed.");
313
314static const CryptoType& get_crypto_type() {
315 // We only want to parse this read-only property once. But we need to wait
316 // until the system is initialized before we can read it. So we use a static
317 // scoped within this function to get it only once.
318 static CryptoType crypto_type =
319 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
320 aes_128_cbc, "ro.crypto.fde_algorithm");
321 return crypto_type;
322}
323
Paul Crowley4eac2642020-02-12 11:04:05 -0800324const KeyGeneration cryptfs_get_keygen() {
325 return makeGen(get_crypto_type());
326}
327
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700328/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700329static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000330 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700331}
332
333/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700334static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800335 if (ftr->keymaster_blob_size) {
336 SLOGI("Already have key");
337 return 0;
338 }
339
Paul Crowley14c8c072018-09-18 13:30:21 -0700340 int rc = keymaster_create_key_for_cryptfs_scrypt(
341 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
342 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000343 if (rc) {
344 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800345 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000346 ftr->keymaster_blob_size = 0;
347 }
348 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700349 return -1;
350 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000351 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700352}
353
Shawn Willdene17a9c42014-09-08 13:04:08 -0600354/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700355static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
356 const size_t object_size, unsigned char** signature,
357 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600358 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600359 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600360 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600361
Shawn Willdene17a9c42014-09-08 13:04:08 -0600362 // To sign a message with RSA, the message must satisfy two
363 // constraints:
364 //
365 // 1. The message, when interpreted as a big-endian numeric value, must
366 // be strictly less than the public modulus of the RSA key. Note
367 // that because the most significant bit of the public modulus is
368 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
369 // key), an n-bit message with most significant bit 0 always
370 // satisfies this requirement.
371 //
372 // 2. The message must have the same length in bits as the public
373 // modulus of the RSA key. This requirement isn't mathematically
374 // necessary, but is necessary to ensure consistency in
375 // implementations.
376 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600377 case KDF_SCRYPT_KEYMASTER:
378 // This ensures the most significant byte of the signed message
379 // is zero. We could have zero-padded to the left instead, but
380 // this approach is slightly more robust against changes in
381 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600382 // so) because we really should be using a proper deterministic
383 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800384 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600385 SLOGI("Signing safely-padded object");
386 break;
387 default:
388 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000389 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600390 }
Paul Crowley73473332017-11-21 15:43:51 -0800391 for (;;) {
392 auto result = keymaster_sign_object_for_cryptfs_scrypt(
393 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
394 to_sign_size, signature, signature_size);
395 switch (result) {
396 case KeymasterSignResult::ok:
397 return 0;
398 case KeymasterSignResult::upgrade:
399 break;
400 default:
401 return -1;
402 }
403 SLOGD("Upgrading key");
404 if (keymaster_upgrade_key_for_cryptfs_scrypt(
405 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
406 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
407 &ftr->keymaster_blob_size) != 0) {
408 SLOGE("Failed to upgrade key");
409 return -1;
410 }
411 if (put_crypt_ftr_and_key(ftr) != 0) {
412 SLOGE("Failed to write upgraded key to disk");
413 }
414 SLOGD("Key upgraded successfully");
415 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600416}
417
Paul Lawrence399317e2014-03-10 13:20:50 -0700418/* Store password when userdata is successfully decrypted and mounted.
419 * Cleared by cryptfs_clear_password
420 *
421 * To avoid a double prompt at boot, we need to store the CryptKeeper
422 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
423 * Since the entire framework is torn down and rebuilt after encryption,
424 * we have to use a daemon or similar to store the password. Since vold
425 * is secured against IPC except from system processes, it seems a reasonable
426 * place to store this.
427 *
428 * password should be cleared once it has been used.
429 *
430 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800431 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700432static char* password = 0;
433static int password_expiry_time = 0;
434static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800435
Paul Crowley14c8c072018-09-18 13:30:21 -0700436enum class RebootType { reboot, recovery, shutdown };
437static void cryptfs_reboot(RebootType rt) {
438 switch (rt) {
439 case RebootType::reboot:
440 property_set(ANDROID_RB_PROPERTY, "reboot");
441 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800442
Paul Crowley14c8c072018-09-18 13:30:21 -0700443 case RebootType::recovery:
444 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
445 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800446
Paul Crowley14c8c072018-09-18 13:30:21 -0700447 case RebootType::shutdown:
448 property_set(ANDROID_RB_PROPERTY, "shutdown");
449 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700450 }
Paul Lawrence87999172014-02-20 12:21:31 -0800451
Ken Sumralladfba362013-06-04 16:37:52 -0700452 sleep(20);
453
454 /* Shouldn't get here, reboot should happen before sleep times out */
455 return;
456}
457
Kenny Rootc4c70f12013-06-14 12:11:38 -0700458/**
459 * Gets the default device scrypt parameters for key derivation time tuning.
460 * The parameters should lead to about one second derivation time for the
461 * given device.
462 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700463static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700464 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000465 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700466
Paul Crowley63c18d32016-02-10 14:02:47 +0000467 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
468 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
469 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
470 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700471 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000472 ftr->N_factor = Nf;
473 ftr->r_factor = rf;
474 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700475}
476
Tom Cherry4c5bde22019-01-29 14:34:01 -0800477static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800478 int fd, block_size;
479 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200480 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800481
Paul Crowley14c8c072018-09-18 13:30:21 -0700482 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800483 SLOGE("Cannot open device to get filesystem size ");
484 return 0;
485 }
486
487 if (lseek64(fd, 1024, SEEK_SET) < 0) {
488 SLOGE("Cannot seek to superblock");
489 return 0;
490 }
491
492 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
493 SLOGE("Cannot read superblock");
494 return 0;
495 }
496
497 close(fd);
498
Daniel Rosenberge82df162014-08-15 22:19:23 +0000499 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
500 SLOGE("Not a valid ext4 superblock");
501 return 0;
502 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800503 block_size = 1024 << sb.s_log_block_size;
504 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200505 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800506
507 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200508 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800509}
510
Tom Cherry4c5bde22019-01-29 14:34:01 -0800511static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
512 for (const auto& entry : fstab_default) {
513 if (!entry.fs_mgr_flags.vold_managed &&
514 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
515 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
516 if (key_loc != nullptr) {
517 *key_loc = entry.key_loc;
518 }
519 if (real_blk_device != nullptr) {
520 *real_blk_device = entry.blk_device;
521 }
522 return;
523 }
524 }
525}
526
Paul Crowley14c8c072018-09-18 13:30:21 -0700527static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
528 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200529 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700530 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700531 char key_loc[PROPERTY_VALUE_MAX];
532 char real_blkdev[PROPERTY_VALUE_MAX];
533 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700534
Paul Crowley14c8c072018-09-18 13:30:21 -0700535 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800536 std::string key_loc;
537 std::string real_blkdev;
538 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700539
Tom Cherry4c5bde22019-01-29 14:34:01 -0800540 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200541 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700542 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
543 * encryption info footer and key, and plenty of bytes to spare for future
544 * growth.
545 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800546 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200547 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700548 cached_data = 1;
549 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800550 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700551 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700552 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800553 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700554 cached_off = 0;
555 cached_data = 1;
556 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700558
Paul Crowley14c8c072018-09-18 13:30:21 -0700559 if (cached_data) {
560 if (metadata_fname) {
561 *metadata_fname = cached_metadata_fname;
562 }
563 if (off) {
564 *off = cached_off;
565 }
566 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700567 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700568
Paul Crowley14c8c072018-09-18 13:30:21 -0700569 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700570}
571
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800572/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700573static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800574 SHA256_CTX c;
575 SHA256_Init(&c);
576 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
577 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
578 SHA256_Final(crypt_ftr->sha256, &c);
579}
580
Ken Sumralle8744072011-01-18 22:01:55 -0800581/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800582 * update the failed mount count but not change the key.
583 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700584static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
585 int fd;
586 unsigned int cnt;
587 /* starting_off is set to the SEEK_SET offset
588 * where the crypto structure starts
589 */
590 off64_t starting_off;
591 int rc = -1;
592 char* fname = NULL;
593 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800594
Paul Crowley14c8c072018-09-18 13:30:21 -0700595 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800596
Paul Crowley14c8c072018-09-18 13:30:21 -0700597 if (get_crypt_ftr_info(&fname, &starting_off)) {
598 SLOGE("Unable to get crypt_ftr_info\n");
599 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800600 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700601 if (fname[0] != '/') {
602 SLOGE("Unexpected value for crypto key location\n");
603 return -1;
604 }
605 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
606 SLOGE("Cannot open footer file %s for put\n", fname);
607 return -1;
608 }
Ken Sumralle8744072011-01-18 22:01:55 -0800609
Paul Crowley14c8c072018-09-18 13:30:21 -0700610 /* Seek to the start of the crypt footer */
611 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
612 SLOGE("Cannot seek to real block device footer\n");
613 goto errout;
614 }
615
616 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
617 SLOGE("Cannot write real block device footer\n");
618 goto errout;
619 }
620
621 fstat(fd, &statbuf);
622 /* If the keys are kept on a raw block device, do not try to truncate it. */
623 if (S_ISREG(statbuf.st_mode)) {
624 if (ftruncate(fd, 0x4000)) {
625 SLOGE("Cannot set footer file size\n");
626 goto errout;
627 }
628 }
629
630 /* Success! */
631 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800632
633errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700634 close(fd);
635 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800636}
637
Paul Crowley14c8c072018-09-18 13:30:21 -0700638static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800639 struct crypt_mnt_ftr copy;
640 memcpy(&copy, crypt_ftr, sizeof(copy));
641 set_ftr_sha(&copy);
642 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
643}
644
Paul Crowley14c8c072018-09-18 13:30:21 -0700645static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700646 return TEMP_FAILURE_RETRY(read(fd, buff, len));
647}
648
Paul Crowley14c8c072018-09-18 13:30:21 -0700649static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700650 return TEMP_FAILURE_RETRY(write(fd, buff, len));
651}
652
Paul Crowley14c8c072018-09-18 13:30:21 -0700653static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700654 memset(pdata, 0, len);
655 pdata->persist_magic = PERSIST_DATA_MAGIC;
656 pdata->persist_valid_entries = 0;
657}
658
659/* A routine to update the passed in crypt_ftr to the lastest version.
660 * fd is open read/write on the device that holds the crypto footer and persistent
661 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
662 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
663 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700664static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700665 int orig_major = crypt_ftr->major_version;
666 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700667
Kenny Root7434b312013-06-14 11:29:53 -0700668 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700669 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700670 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671
Kenny Rootc4c70f12013-06-14 12:11:38 -0700672 SLOGW("upgrading crypto footer to 1.1");
673
Paul Crowley14c8c072018-09-18 13:30:21 -0700674 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700675 if (pdata == NULL) {
676 SLOGE("Cannot allocate persisent data\n");
677 return;
678 }
679 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
680
681 /* Need to initialize the persistent data area */
682 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
683 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100684 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700685 return;
686 }
687 /* Write all zeros to the first copy, making it invalid */
688 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
689
690 /* Write a valid but empty structure to the second copy */
691 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
692 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
693
694 /* Update the footer */
695 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
696 crypt_ftr->persist_data_offset[0] = pdata_offset;
697 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
698 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100699 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700700 }
701
Paul Lawrencef4faa572014-01-29 13:31:03 -0800702 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700703 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800704 /* But keep the old kdf_type.
705 * It will get updated later to KDF_SCRYPT after the password has been verified.
706 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700707 crypt_ftr->kdf_type = KDF_PBKDF2;
708 get_device_scrypt_params(crypt_ftr);
709 crypt_ftr->minor_version = 2;
710 }
711
Paul Lawrencef4faa572014-01-29 13:31:03 -0800712 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
713 SLOGW("upgrading crypto footer to 1.3");
714 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
715 crypt_ftr->minor_version = 3;
716 }
717
Kenny Root7434b312013-06-14 11:29:53 -0700718 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
719 if (lseek64(fd, offset, SEEK_SET) == -1) {
720 SLOGE("Cannot seek to crypt footer\n");
721 return;
722 }
723 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700724 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700725}
726
Paul Crowley14c8c072018-09-18 13:30:21 -0700727static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
728 int fd;
729 unsigned int cnt;
730 off64_t starting_off;
731 int rc = -1;
732 char* fname = NULL;
733 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700734
Paul Crowley14c8c072018-09-18 13:30:21 -0700735 if (get_crypt_ftr_info(&fname, &starting_off)) {
736 SLOGE("Unable to get crypt_ftr_info\n");
737 return -1;
738 }
739 if (fname[0] != '/') {
740 SLOGE("Unexpected value for crypto key location\n");
741 return -1;
742 }
743 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
744 SLOGE("Cannot open footer file %s for get\n", fname);
745 return -1;
746 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800747
Paul Crowley14c8c072018-09-18 13:30:21 -0700748 /* Make sure it's 16 Kbytes in length */
749 fstat(fd, &statbuf);
750 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
751 SLOGE("footer file %s is not the expected size!\n", fname);
752 goto errout;
753 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700754
Paul Crowley14c8c072018-09-18 13:30:21 -0700755 /* Seek to the start of the crypt footer */
756 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
757 SLOGE("Cannot seek to real block device footer\n");
758 goto errout;
759 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700760
Paul Crowley14c8c072018-09-18 13:30:21 -0700761 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
762 SLOGE("Cannot read real block device footer\n");
763 goto errout;
764 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800765
Paul Crowley14c8c072018-09-18 13:30:21 -0700766 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
767 SLOGE("Bad magic for real block device %s\n", fname);
768 goto errout;
769 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800770
Paul Crowley14c8c072018-09-18 13:30:21 -0700771 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
772 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
773 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
774 goto errout;
775 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800776
Paul Crowley14c8c072018-09-18 13:30:21 -0700777 // We risk buffer overflows with oversized keys, so we just reject them.
778 // 0-sized keys are problematic (essentially by-passing encryption), and
779 // AES-CBC key wrapping only works for multiples of 16 bytes.
780 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
781 (crypt_ftr->keysize > MAX_KEY_LEN)) {
782 SLOGE(
783 "Invalid keysize (%u) for block device %s; Must be non-zero, "
784 "divisible by 16, and <= %d\n",
785 crypt_ftr->keysize, fname, MAX_KEY_LEN);
786 goto errout;
787 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800788
Paul Crowley14c8c072018-09-18 13:30:21 -0700789 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
790 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
791 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
792 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800793
Paul Crowley14c8c072018-09-18 13:30:21 -0700794 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
795 * copy on disk before returning.
796 */
797 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
798 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
799 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800800
Paul Crowley14c8c072018-09-18 13:30:21 -0700801 /* Success! */
802 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800803
804errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700805 close(fd);
806 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800807}
808
Paul Crowley14c8c072018-09-18 13:30:21 -0700809static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700810 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
811 crypt_ftr->persist_data_offset[1]) {
812 SLOGE("Crypt_ftr persist data regions overlap");
813 return -1;
814 }
815
816 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
817 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
818 return -1;
819 }
820
821 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700822 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700823 CRYPT_FOOTER_OFFSET) {
824 SLOGE("Persistent data extends past crypto footer");
825 return -1;
826 }
827
828 return 0;
829}
830
Paul Crowley14c8c072018-09-18 13:30:21 -0700831static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700832 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700833 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700834 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700835 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700836 int found = 0;
837 int fd;
838 int ret;
839 int i;
840
841 if (persist_data) {
842 /* Nothing to do, we've already loaded or initialized it */
843 return 0;
844 }
845
Ken Sumrall160b4d62013-04-22 12:15:39 -0700846 /* If not encrypted, just allocate an empty table and initialize it */
847 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700848 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800849 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700850 if (pdata) {
851 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
852 persist_data = pdata;
853 return 0;
854 }
855 return -1;
856 }
857
Paul Crowley14c8c072018-09-18 13:30:21 -0700858 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700859 return -1;
860 }
861
Paul Crowley14c8c072018-09-18 13:30:21 -0700862 if ((crypt_ftr.major_version < 1) ||
863 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700864 SLOGE("Crypt_ftr version doesn't support persistent data");
865 return -1;
866 }
867
868 if (get_crypt_ftr_info(&fname, NULL)) {
869 return -1;
870 }
871
872 ret = validate_persistent_data_storage(&crypt_ftr);
873 if (ret) {
874 return -1;
875 }
876
Paul Crowley14c8c072018-09-18 13:30:21 -0700877 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700878 if (fd < 0) {
879 SLOGE("Cannot open %s metadata file", fname);
880 return -1;
881 }
882
Wei Wang4375f1b2017-02-24 17:43:01 -0800883 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800884 if (pdata == NULL) {
885 SLOGE("Cannot allocate memory for persistent data");
886 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700887 }
888
889 for (i = 0; i < 2; i++) {
890 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
891 SLOGE("Cannot seek to read persistent data on %s", fname);
892 goto err2;
893 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700894 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700895 SLOGE("Error reading persistent data on iteration %d", i);
896 goto err2;
897 }
898 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
899 found = 1;
900 break;
901 }
902 }
903
904 if (!found) {
905 SLOGI("Could not find valid persistent data, creating");
906 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
907 }
908
909 /* Success */
910 persist_data = pdata;
911 close(fd);
912 return 0;
913
914err2:
915 free(pdata);
916
917err:
918 close(fd);
919 return -1;
920}
921
Paul Crowley14c8c072018-09-18 13:30:21 -0700922static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700923 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700924 struct crypt_persist_data* pdata;
925 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700926 off64_t write_offset;
927 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700928 int fd;
929 int ret;
930
931 if (persist_data == NULL) {
932 SLOGE("No persistent data to save");
933 return -1;
934 }
935
Paul Crowley14c8c072018-09-18 13:30:21 -0700936 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700937 return -1;
938 }
939
Paul Crowley14c8c072018-09-18 13:30:21 -0700940 if ((crypt_ftr.major_version < 1) ||
941 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700942 SLOGE("Crypt_ftr version doesn't support persistent data");
943 return -1;
944 }
945
946 ret = validate_persistent_data_storage(&crypt_ftr);
947 if (ret) {
948 return -1;
949 }
950
951 if (get_crypt_ftr_info(&fname, NULL)) {
952 return -1;
953 }
954
Paul Crowley14c8c072018-09-18 13:30:21 -0700955 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700956 if (fd < 0) {
957 SLOGE("Cannot open %s metadata file", fname);
958 return -1;
959 }
960
Wei Wang4375f1b2017-02-24 17:43:01 -0800961 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700962 if (pdata == NULL) {
963 SLOGE("Cannot allocate persistant data");
964 goto err;
965 }
966
967 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
968 SLOGE("Cannot seek to read persistent data on %s", fname);
969 goto err2;
970 }
971
972 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700973 SLOGE("Error reading persistent data before save");
974 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700975 }
976
977 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
978 /* The first copy is the curent valid copy, so write to
979 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700980 write_offset = crypt_ftr.persist_data_offset[1];
981 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700982 } else {
983 /* The second copy must be the valid copy, so write to
984 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700985 write_offset = crypt_ftr.persist_data_offset[0];
986 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700987 }
988
989 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100990 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700991 SLOGE("Cannot seek to write persistent data");
992 goto err2;
993 }
994 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700995 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100996 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700997 SLOGE("Cannot seek to erase previous persistent data");
998 goto err2;
999 }
1000 fsync(fd);
1001 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001002 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001003 SLOGE("Cannot write to erase previous persistent data");
1004 goto err2;
1005 }
1006 fsync(fd);
1007 } else {
1008 SLOGE("Cannot write to save persistent data");
1009 goto err2;
1010 }
1011
1012 /* Success */
1013 free(pdata);
1014 close(fd);
1015 return 0;
1016
1017err2:
1018 free(pdata);
1019err:
1020 close(fd);
1021 return -1;
1022}
1023
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001024/* Convert a binary key of specified length into an ascii hex string equivalent,
1025 * without the leading 0x and with null termination
1026 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001027static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1028 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001029 unsigned int i, a;
1030 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001031
Paul Crowley14c8c072018-09-18 13:30:21 -07001032 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001033 /* For each byte, write out two ascii hex digits */
1034 nibble = (master_key[i] >> 4) & 0xf;
1035 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001036
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001037 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001038 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001039 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001040
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001041 /* Add the null termination */
1042 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001043}
1044
Eric Biggersed45ec32019-01-25 10:47:55 -08001045/*
1046 * If the ro.crypto.fde_sector_size system property is set, append the
1047 * parameters to make dm-crypt use the specified crypto sector size and round
1048 * the crypto device size down to a crypto sector boundary.
1049 */
David Andersonb9224732019-05-13 13:02:54 -07001050static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001051 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001052 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001053
Eric Biggersed45ec32019-01-25 10:47:55 -08001054 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1055 unsigned int sector_size;
1056
1057 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1058 (sector_size & (sector_size - 1)) != 0) {
1059 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1060 DM_CRYPT_SECTOR_SIZE, value);
1061 return -1;
1062 }
1063
David Andersonb9224732019-05-13 13:02:54 -07001064 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001065
1066 // With this option, IVs will match the sector numbering, instead
1067 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001068 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001069
1070 // Round the crypto device size down to a crypto sector boundary.
1071 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001072 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001073 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001074}
1075
Paul Crowley5afbc622017-11-27 09:42:17 -08001076static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001077 const char* real_blk_name, std::string* crypto_blk_name,
1078 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001079 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001080
David Andersonb9224732019-05-13 13:02:54 -07001081 // We need two ASCII characters to represent each byte, and need space for
1082 // the '\0' terminator.
1083 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1084 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001085
David Andersonb9224732019-05-13 13:02:54 -07001086 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1087 (const char*)crypt_ftr->crypto_type_name,
1088 master_key_ascii, 0, real_blk_name, 0);
1089 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001090
Paul Crowley5afbc622017-11-27 09:42:17 -08001091 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001092 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001093 }
David Andersonb9224732019-05-13 13:02:54 -07001094 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001095 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001096 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001097 }
David Andersonb9224732019-05-13 13:02:54 -07001098
1099 DmTable table;
1100 table.AddTarget(std::move(target));
1101
1102 int load_count = 1;
1103 while (load_count < TABLE_LOAD_RETRIES) {
1104 if (dm.CreateDevice(name, table)) {
1105 break;
1106 }
1107 load_count++;
1108 }
1109
1110 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001111 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001112 return -1;
1113 }
1114 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001115 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1116 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117
Paul Crowley81796e92020-02-07 11:27:49 -08001118 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001119 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1120 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001121 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122
Paul Crowleycfe39722018-10-30 15:59:24 -07001123 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001124 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001125 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001126 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001127 }
David Andersonb9224732019-05-13 13:02:54 -07001128 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129}
1130
David Andersonb9224732019-05-13 13:02:54 -07001131static int delete_crypto_blk_dev(const std::string& name) {
1132 auto& dm = DeviceMapper::Instance();
1133 if (!dm.DeleteDevice(name)) {
1134 SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1135 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001136 }
David Andersonb9224732019-05-13 13:02:54 -07001137 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001138}
1139
Paul Crowley14c8c072018-09-18 13:30:21 -07001140static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1141 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001142 SLOGI("Using pbkdf2 for cryptfs KDF");
1143
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001144 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001145 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1146 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001147}
1148
Paul Crowley14c8c072018-09-18 13:30:21 -07001149static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001150 SLOGI("Using scrypt for cryptfs KDF");
1151
Paul Crowley14c8c072018-09-18 13:30:21 -07001152 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001153
1154 int N = 1 << ftr->N_factor;
1155 int r = 1 << ftr->r_factor;
1156 int p = 1 << ftr->p_factor;
1157
1158 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001159 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001160 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001161
Paul Crowley14c8c072018-09-18 13:30:21 -07001162 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001163}
1164
Paul Crowley14c8c072018-09-18 13:30:21 -07001165static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1166 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001167 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1168
1169 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001170 size_t signature_size;
1171 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001172 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001173
1174 int N = 1 << ftr->N_factor;
1175 int r = 1 << ftr->r_factor;
1176 int p = 1 << ftr->p_factor;
1177
Paul Crowley14c8c072018-09-18 13:30:21 -07001178 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001179 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001180
1181 if (rc) {
1182 SLOGE("scrypt failed");
1183 return -1;
1184 }
1185
Paul Crowley14c8c072018-09-18 13:30:21 -07001186 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001187 SLOGE("Signing failed");
1188 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001189 }
1190
Paul Crowley14c8c072018-09-18 13:30:21 -07001191 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1192 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001193 free(signature);
1194
1195 if (rc) {
1196 SLOGE("scrypt failed");
1197 return -1;
1198 }
1199
1200 return 0;
1201}
1202
Paul Crowley14c8c072018-09-18 13:30:21 -07001203static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1204 const unsigned char* decrypted_master_key,
1205 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1206 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001207 EVP_CIPHER_CTX e_ctx;
1208 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001209 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001210
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001211 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001212 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001213
1214 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001215 case KDF_SCRYPT_KEYMASTER:
1216 if (keymaster_create_key(crypt_ftr)) {
1217 SLOGE("keymaster_create_key failed");
1218 return -1;
1219 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001220
Paul Crowley14c8c072018-09-18 13:30:21 -07001221 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1222 SLOGE("scrypt failed");
1223 return -1;
1224 }
1225 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001226
Paul Crowley14c8c072018-09-18 13:30:21 -07001227 case KDF_SCRYPT:
1228 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1229 SLOGE("scrypt failed");
1230 return -1;
1231 }
1232 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001233
Paul Crowley14c8c072018-09-18 13:30:21 -07001234 default:
1235 SLOGE("Invalid kdf_type");
1236 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001237 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001238
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001239 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001240 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001241 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1242 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001243 SLOGE("EVP_EncryptInit failed\n");
1244 return -1;
1245 }
1246 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001247
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001248 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001249 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1250 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 SLOGE("EVP_EncryptUpdate failed\n");
1252 return -1;
1253 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001254 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001255 SLOGE("EVP_EncryptFinal failed\n");
1256 return -1;
1257 }
1258
Greg Kaiser59ad0182018-02-16 13:01:36 -08001259 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1261 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001262 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001263
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001264 /* Store the scrypt of the intermediate key, so we can validate if it's a
1265 password error or mount error when things go wrong.
1266 Note there's no need to check for errors, since if this is incorrect, we
1267 simply won't wipe userdata, which is the correct default behavior
1268 */
1269 int N = 1 << crypt_ftr->N_factor;
1270 int r = 1 << crypt_ftr->r_factor;
1271 int p = 1 << crypt_ftr->p_factor;
1272
Paul Crowley14c8c072018-09-18 13:30:21 -07001273 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1274 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001275 sizeof(crypt_ftr->scrypted_intermediate_key));
1276
1277 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001278 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001279 }
1280
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001281 EVP_CIPHER_CTX_cleanup(&e_ctx);
1282
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001283 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001284}
1285
Paul Crowley14c8c072018-09-18 13:30:21 -07001286static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1287 const unsigned char* encrypted_master_key, size_t keysize,
1288 unsigned char* decrypted_master_key, kdf_func kdf,
1289 void* kdf_params, unsigned char** intermediate_key,
1290 size_t* intermediate_key_size) {
1291 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1292 EVP_CIPHER_CTX d_ctx;
1293 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294
Paul Crowley14c8c072018-09-18 13:30:21 -07001295 /* Turn the password into an intermediate key and IV that can decrypt the
1296 master key */
1297 if (kdf(passwd, salt, ikey, kdf_params)) {
1298 SLOGE("kdf failed");
1299 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001300 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001301
Paul Crowley14c8c072018-09-18 13:30:21 -07001302 /* Initialize the decryption engine */
1303 EVP_CIPHER_CTX_init(&d_ctx);
1304 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1305 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1306 return -1;
1307 }
1308 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1309 /* Decrypt the master key */
1310 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1311 keysize)) {
1312 return -1;
1313 }
1314 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1315 return -1;
1316 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001317
Paul Crowley14c8c072018-09-18 13:30:21 -07001318 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1319 return -1;
1320 }
1321
1322 /* Copy intermediate key if needed by params */
1323 if (intermediate_key && intermediate_key_size) {
1324 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1325 if (*intermediate_key) {
1326 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1327 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1328 }
1329 }
1330
1331 EVP_CIPHER_CTX_cleanup(&d_ctx);
1332
1333 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001334}
1335
Paul Crowley14c8c072018-09-18 13:30:21 -07001336static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001337 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001338 *kdf = scrypt_keymaster;
1339 *kdf_params = ftr;
1340 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001341 *kdf = scrypt;
1342 *kdf_params = ftr;
1343 } else {
1344 *kdf = pbkdf2;
1345 *kdf_params = NULL;
1346 }
1347}
1348
Paul Crowley14c8c072018-09-18 13:30:21 -07001349static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1350 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1351 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001352 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001353 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001354 int ret;
1355
1356 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001357 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1358 decrypted_master_key, kdf, kdf_params, intermediate_key,
1359 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001360 if (ret != 0) {
1361 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001362 }
1363
1364 return ret;
1365}
1366
Paul Crowley14c8c072018-09-18 13:30:21 -07001367static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1368 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001369 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001370
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001371 /* Get some random bits for a key and salt */
1372 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1373 return -1;
1374 }
1375 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1376 return -1;
1377 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001378
1379 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001380 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001381}
1382
Paul Crowley73be12d2020-02-03 12:22:03 -08001383static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001384 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001385#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001386
1387 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001388 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001389 if (umount(mountpoint) == 0) {
1390 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001392
1393 if (errno == EINVAL) {
1394 /* EINVAL is returned if the directory is not a mountpoint,
1395 * i.e. there is no filesystem mounted there. So just get out.
1396 */
1397 break;
1398 }
1399
1400 err = errno;
1401
1402 /* If allowed, be increasingly aggressive before the last two retries */
1403 if (kill) {
1404 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1405 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001406 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001407 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1408 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001409 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001410 }
1411 }
1412
1413 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001414 }
1415
1416 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001417 SLOGD("unmounting %s succeeded\n", mountpoint);
1418 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001419 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001420 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1421 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1422 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001423 }
1424
1425 return rc;
1426}
1427
Paul Crowley14c8c072018-09-18 13:30:21 -07001428static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001429 // NOTE: post_fs_data results in init calling back around to vold, so all
1430 // callers to this method must be async
1431
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001432 /* Do the prep of the /data filesystem */
1433 property_set("vold.post_fs_data_done", "0");
1434 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001435 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001436
Ken Sumrallc5872692013-05-14 15:26:31 -07001437 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001438 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001439 /* We timed out to prep /data in time. Continue wait. */
1440 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001441 }
Wei Wang42e38102017-06-07 10:46:12 -07001442 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001443}
1444
Paul Crowley14c8c072018-09-18 13:30:21 -07001445static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001446 // Mark the footer as bad
1447 struct crypt_mnt_ftr crypt_ftr;
1448 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1449 SLOGE("Failed to get crypto footer - panic");
1450 return;
1451 }
1452
1453 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1454 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1455 SLOGE("Failed to set crypto footer - panic");
1456 return;
1457 }
1458}
1459
Paul Crowley14c8c072018-09-18 13:30:21 -07001460static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001461 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001462 SLOGE("Failed to mount tmpfs on data - panic");
1463 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001464 }
1465
1466 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1467 SLOGE("Failed to trigger post fs data - panic");
1468 return;
1469 }
1470
1471 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1472 SLOGE("Failed to trigger restart min framework - panic");
1473 return;
1474 }
1475}
1476
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001477/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001478static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001479 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001480 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001481 static int restart_successful = 0;
1482
1483 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001484 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001485 SLOGE("Encrypted filesystem not validated, aborting");
1486 return -1;
1487 }
1488
1489 if (restart_successful) {
1490 SLOGE("System already restarted with encrypted disk, aborting");
1491 return -1;
1492 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001493
Paul Lawrencef4faa572014-01-29 13:31:03 -08001494 if (restart_main) {
1495 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001496 * start all services in one of these classes: core, early_hal, hal,
1497 * main and late_start. To get to the minimal UI for PIN entry, we
1498 * need to start core, early_hal, hal and main. When we want to
1499 * shutdown the framework again, we need to stop most of the services in
1500 * these classes, but only those services that were started after
1501 * /data was mounted. This excludes critical services like vold and
1502 * ueventd, which need to keep running. We could possible stop
1503 * even fewer services, but because we want services to pick up APEX
1504 * libraries from the real /data, restarting is better, as it makes
1505 * these devices consistent with FBE devices and lets them use the
1506 * most recent code.
1507 *
1508 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001509 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001510 * We then restart the class core, hal, main, and also the class
1511 * late_start.
1512 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001513 * At the moment, I've only put a few things in late_start that I know
1514 * are not needed to bring up the framework, and that also cause problems
1515 * with unmounting the tmpfs /data, but I hope to add add more services
1516 * to the late_start class as we optimize this to decrease the delay
1517 * till the user is asked for the password to the filesystem.
1518 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001519
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001520 /* The init files are setup to stop the right set of services when
1521 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001522 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001523 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001524 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525
Paul Lawrencef4faa572014-01-29 13:31:03 -08001526 /* Ugh, shutting down the framework is not synchronous, so until it
1527 * can be fixed, this horrible hack will wait a moment for it all to
1528 * shut down before proceeding. Without it, some devices cannot
1529 * restart the graphics services.
1530 */
1531 sleep(2);
1532 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001533
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534 /* Now that the framework is shutdown, we should be able to umount()
1535 * the tmpfs filesystem, and mount the real one.
1536 */
1537
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001538 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1539 if (strlen(crypto_blkdev) == 0) {
1540 SLOGE("fs_crypto_blkdev not set\n");
1541 return -1;
1542 }
1543
Paul Crowley14c8c072018-09-18 13:30:21 -07001544 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001545 /* If ro.crypto.readonly is set to 1, mount the decrypted
1546 * filesystem readonly. This is used when /data is mounted by
1547 * recovery mode.
1548 */
1549 char ro_prop[PROPERTY_VALUE_MAX];
1550 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001551 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001552 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1553 if (entry != nullptr) {
1554 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001555 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001556 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001557
Ken Sumralle5032c42012-04-01 23:58:44 -07001558 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001559 int retries = RETRY_MOUNT_ATTEMPTS;
1560 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001561
1562 /*
1563 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1564 * partitions in the fsck domain.
1565 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001566 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001567 SLOGE("Failed to setexeccon");
1568 return -1;
1569 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001570 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001571 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001572 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001573 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1574 /* TODO: invoke something similar to
1575 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1576 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001577 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001578 if (--retries) {
1579 sleep(RETRY_MOUNT_DELAY_SECONDS);
1580 } else {
1581 /* Let's hope that a reboot clears away whatever is keeping
1582 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001583 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001584 }
1585 } else {
1586 SLOGE("Failed to mount decrypted data");
1587 cryptfs_set_corrupt();
1588 cryptfs_trigger_restart_min_framework();
1589 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001590 if (setexeccon(NULL)) {
1591 SLOGE("Failed to setexeccon");
1592 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001593 return -1;
1594 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001595 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001596 if (setexeccon(NULL)) {
1597 SLOGE("Failed to setexeccon");
1598 return -1;
1599 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001600
Ken Sumralle5032c42012-04-01 23:58:44 -07001601 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001602 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001603 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001604
1605 /* startup service classes main and late_start */
1606 property_set("vold.decrypt", "trigger_restart_framework");
1607 SLOGD("Just triggered restart_framework\n");
1608
1609 /* Give it a few moments to get started */
1610 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001611 }
1612
Ken Sumrall0cc16632011-01-18 20:32:26 -08001613 if (rc == 0) {
1614 restart_successful = 1;
1615 }
1616
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001617 return rc;
1618}
1619
Paul Crowley14c8c072018-09-18 13:30:21 -07001620int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001621 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001622 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001623 SLOGE("cryptfs_restart not valid for file encryption:");
1624 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001625 }
1626
Paul Lawrencef4faa572014-01-29 13:31:03 -08001627 /* Call internal implementation forcing a restart of main service group */
1628 return cryptfs_restart_internal(1);
1629}
1630
Paul Crowley14c8c072018-09-18 13:30:21 -07001631static int do_crypto_complete(const char* mount_point) {
1632 struct crypt_mnt_ftr crypt_ftr;
1633 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001634
Paul Crowley14c8c072018-09-18 13:30:21 -07001635 property_get("ro.crypto.state", encrypted_state, "");
1636 if (strcmp(encrypted_state, "encrypted")) {
1637 SLOGE("not running with encryption, aborting");
1638 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001639 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001640
Paul Crowley14c8c072018-09-18 13:30:21 -07001641 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001642 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001643 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1644 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001645
Paul Crowley14c8c072018-09-18 13:30:21 -07001646 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001647 std::string key_loc;
1648 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001649
Paul Crowley14c8c072018-09-18 13:30:21 -07001650 /*
1651 * Only report this error if key_loc is a file and it exists.
1652 * If the device was never encrypted, and /data is not mountable for
1653 * some reason, returning 1 should prevent the UI from presenting the
1654 * a "enter password" screen, or worse, a "press button to wipe the
1655 * device" screen.
1656 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001657 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001658 SLOGE("master key file does not exist, aborting");
1659 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1660 } else {
1661 SLOGE("Error getting crypt footer and key\n");
1662 return CRYPTO_COMPLETE_BAD_METADATA;
1663 }
1664 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001665
Paul Crowley14c8c072018-09-18 13:30:21 -07001666 // Test for possible error flags
1667 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1668 SLOGE("Encryption process is partway completed\n");
1669 return CRYPTO_COMPLETE_PARTIAL;
1670 }
1671
1672 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1673 SLOGE("Encryption process was interrupted but cannot continue\n");
1674 return CRYPTO_COMPLETE_INCONSISTENT;
1675 }
1676
1677 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1678 SLOGE("Encryption is successful but data is corrupt\n");
1679 return CRYPTO_COMPLETE_CORRUPT;
1680 }
1681
1682 /* We passed the test! We shall diminish, and return to the west */
1683 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001684}
1685
Paul Crowley14c8c072018-09-18 13:30:21 -07001686static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1687 const char* mount_point, const char* label) {
1688 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001689 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001690 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001691 char tmp_mount_point[64];
1692 unsigned int orig_failed_decrypt_count;
1693 int rc;
1694 int use_keymaster = 0;
1695 int upgrade = 0;
1696 unsigned char* intermediate_key = 0;
1697 size_t intermediate_key_size = 0;
1698 int N = 1 << crypt_ftr->N_factor;
1699 int r = 1 << crypt_ftr->r_factor;
1700 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001701
Paul Crowley14c8c072018-09-18 13:30:21 -07001702 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1703 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001704
Paul Crowley14c8c072018-09-18 13:30:21 -07001705 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1706 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1707 &intermediate_key_size)) {
1708 SLOGE("Failed to decrypt master key\n");
1709 rc = -1;
1710 goto errout;
1711 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001712 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713
Tom Cherry4c5bde22019-01-29 14:34:01 -08001714 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001715
Paul Crowley14c8c072018-09-18 13:30:21 -07001716 // Create crypto block device - all (non fatal) code paths
1717 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001718 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001719 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001720 SLOGE("Error creating decrypted block device\n");
1721 rc = -1;
1722 goto errout;
1723 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724
Paul Crowley14c8c072018-09-18 13:30:21 -07001725 /* Work out if the problem is the password or the data */
1726 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001727
Paul Crowley14c8c072018-09-18 13:30:21 -07001728 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1729 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1730 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001731
Paul Crowley14c8c072018-09-18 13:30:21 -07001732 // Does the key match the crypto footer?
1733 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1734 sizeof(scrypted_intermediate_key)) == 0) {
1735 SLOGI("Password matches");
1736 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001737 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001738 /* Try mounting the file system anyway, just in case the problem's with
1739 * the footer, not the key. */
1740 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1741 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001742 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1743 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001744 SLOGE("Error temp mounting decrypted block device\n");
1745 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001746
Paul Crowley14c8c072018-09-18 13:30:21 -07001747 rc = ++crypt_ftr->failed_decrypt_count;
1748 put_crypt_ftr_and_key(crypt_ftr);
1749 } else {
1750 /* Success! */
1751 SLOGI("Password did not match but decrypted drive mounted - continue");
1752 umount(tmp_mount_point);
1753 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001754 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001755 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001756
Paul Crowley14c8c072018-09-18 13:30:21 -07001757 if (rc == 0) {
1758 crypt_ftr->failed_decrypt_count = 0;
1759 if (orig_failed_decrypt_count != 0) {
1760 put_crypt_ftr_and_key(crypt_ftr);
1761 }
1762
1763 /* Save the name of the crypto block device
1764 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001765 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001766
1767 /* Also save a the master key so we can reencrypted the key
1768 * the key when we want to change the password on it. */
1769 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1770 saved_mount_point = strdup(mount_point);
1771 master_key_saved = 1;
1772 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1773 rc = 0;
1774
1775 // Upgrade if we're not using the latest KDF.
1776 use_keymaster = keymaster_check_compatibility();
1777 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1778 // Don't allow downgrade
1779 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1780 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1781 upgrade = 1;
1782 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1783 crypt_ftr->kdf_type = KDF_SCRYPT;
1784 upgrade = 1;
1785 }
1786
1787 if (upgrade) {
1788 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1789 crypt_ftr->master_key, crypt_ftr);
1790 if (!rc) {
1791 rc = put_crypt_ftr_and_key(crypt_ftr);
1792 }
1793 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1794
1795 // Do not fail even if upgrade failed - machine is bootable
1796 // Note that if this code is ever hit, there is a *serious* problem
1797 // since KDFs should never fail. You *must* fix the kdf before
1798 // proceeding!
1799 if (rc) {
1800 SLOGW(
1801 "Upgrade failed with error %d,"
1802 " but continuing with previous state",
1803 rc);
1804 rc = 0;
1805 }
1806 }
1807 }
1808
1809errout:
1810 if (intermediate_key) {
1811 memset(intermediate_key, 0, intermediate_key_size);
1812 free(intermediate_key);
1813 }
1814 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001815}
1816
Ken Sumrall29d8da82011-05-18 17:20:07 -07001817/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001818 * Called by vold when it's asked to mount an encrypted external
1819 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001820 * as any metadata is been stored in a separate, small partition. We
1821 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001822 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001823int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001824 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001825 auto crypto_type = get_crypto_type();
1826 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001827 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001828 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001829 return -1;
1830 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001831 uint64_t nr_sec = 0;
1832 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001833 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001834 return -1;
1835 }
1836
Jeff Sharkey9c484982015-03-31 10:35:33 -07001837 struct crypt_mnt_ftr ext_crypt_ftr;
1838 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1839 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001840 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1841 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001842 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001843 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001844 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001845 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1846 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001847
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001848 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1849 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001850}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001851
Paul Crowley14c8c072018-09-18 13:30:21 -07001852int cryptfs_crypto_complete(void) {
1853 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001854}
1855
Paul Crowley14c8c072018-09-18 13:30:21 -07001856int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001857 char encrypted_state[PROPERTY_VALUE_MAX];
1858 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001859 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1860 SLOGE(
1861 "encrypted fs already validated or not running with encryption,"
1862 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001863 return -1;
1864 }
1865
1866 if (get_crypt_ftr_and_key(crypt_ftr)) {
1867 SLOGE("Error getting crypt footer and key");
1868 return -1;
1869 }
1870
1871 return 0;
1872}
1873
Paul Crowley14c8c072018-09-18 13:30:21 -07001874int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001875 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001876 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001877 SLOGE("cryptfs_check_passwd not valid for file encryption");
1878 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001879 }
1880
Paul Lawrencef4faa572014-01-29 13:31:03 -08001881 struct crypt_mnt_ftr crypt_ftr;
1882 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001883
Paul Lawrencef4faa572014-01-29 13:31:03 -08001884 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001885 if (rc) {
1886 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001887 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001888 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001889
Paul Crowley14c8c072018-09-18 13:30:21 -07001890 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001891 if (rc) {
1892 SLOGE("Password did not match");
1893 return rc;
1894 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001895
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001896 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1897 // Here we have a default actual password but a real password
1898 // we must test against the scrypted value
1899 // First, we must delete the crypto block device that
1900 // test_mount_encrypted_fs leaves behind as a side effect
1901 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001902 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1903 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001904 if (rc) {
1905 SLOGE("Default password did not match on reboot encryption");
1906 return rc;
1907 }
1908
1909 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1910 put_crypt_ftr_and_key(&crypt_ftr);
1911 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1912 if (rc) {
1913 SLOGE("Could not change password on reboot encryption");
1914 return rc;
1915 }
1916 }
1917
1918 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001919 cryptfs_clear_password();
1920 password = strdup(passwd);
1921 struct timespec now;
1922 clock_gettime(CLOCK_BOOTTIME, &now);
1923 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001924 }
1925
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001926 return rc;
1927}
1928
Paul Crowley14c8c072018-09-18 13:30:21 -07001929int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001930 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001931 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001932 char encrypted_state[PROPERTY_VALUE_MAX];
1933 int rc;
1934
1935 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001936 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001937 SLOGE("device not encrypted, aborting");
1938 return -2;
1939 }
1940
1941 if (!master_key_saved) {
1942 SLOGE("encrypted fs not yet mounted, aborting");
1943 return -1;
1944 }
1945
1946 if (!saved_mount_point) {
1947 SLOGE("encrypted fs failed to save mount point, aborting");
1948 return -1;
1949 }
1950
Ken Sumrall160b4d62013-04-22 12:15:39 -07001951 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001952 SLOGE("Error getting crypt footer and key\n");
1953 return -1;
1954 }
1955
1956 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1957 /* If the device has no password, then just say the password is valid */
1958 rc = 0;
1959 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001960 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001961 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1962 /* They match, the password is correct */
1963 rc = 0;
1964 } else {
1965 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1966 sleep(1);
1967 rc = 1;
1968 }
1969 }
1970
1971 return rc;
1972}
1973
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001974/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08001975 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001976 * Presumably, at a minimum, the caller will update the
1977 * filesystem size and crypto_type_name after calling this function.
1978 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001979static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001980 off64_t off;
1981
1982 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001983 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001984 ftr->major_version = CURRENT_MAJOR_VERSION;
1985 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001986 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08001987 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001988
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001989 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001990 case 1:
1991 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1992 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001993
Paul Crowley14c8c072018-09-18 13:30:21 -07001994 case 0:
1995 ftr->kdf_type = KDF_SCRYPT;
1996 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001997
Paul Crowley14c8c072018-09-18 13:30:21 -07001998 default:
1999 SLOGE("keymaster_check_compatibility failed");
2000 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002001 }
2002
Kenny Rootc4c70f12013-06-14 12:11:38 -07002003 get_device_scrypt_params(ftr);
2004
Ken Sumrall160b4d62013-04-22 12:15:39 -07002005 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2006 if (get_crypt_ftr_info(NULL, &off) == 0) {
2007 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002008 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002009 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002010
2011 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002012}
2013
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002014#define FRAMEWORK_BOOT_WAIT 60
2015
Paul Crowley14c8c072018-09-18 13:30:21 -07002016static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2017 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002018 if (fd == -1) {
2019 SLOGE("Error opening file %s", filename);
2020 return -1;
2021 }
2022
2023 char block[CRYPT_INPLACE_BUFSIZE];
2024 memset(block, 0, sizeof(block));
2025 if (unix_read(fd, block, sizeof(block)) < 0) {
2026 SLOGE("Error reading file %s", filename);
2027 close(fd);
2028 return -1;
2029 }
2030
2031 close(fd);
2032
2033 SHA256_CTX c;
2034 SHA256_Init(&c);
2035 SHA256_Update(&c, block, sizeof(block));
2036 SHA256_Final(buf, &c);
2037
2038 return 0;
2039}
2040
Paul Crowley81796e92020-02-07 11:27:49 -08002041static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2042 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002043 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002044 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002045
Paul Lawrence87999172014-02-20 12:21:31 -08002046 /* The size of the userdata partition, and add in the vold volumes below */
2047 tot_encryption_size = crypt_ftr->fs_size;
2048
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002049 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002050 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002051
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002052 if (rc == ENABLE_INPLACE_ERR_DEV) {
2053 /* Hack for b/17898962 */
2054 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2055 cryptfs_reboot(RebootType::reboot);
2056 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002057
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002058 if (!rc) {
2059 crypt_ftr->encrypted_upto = cur_encryption_done;
2060 }
Paul Lawrence87999172014-02-20 12:21:31 -08002061
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002062 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2063 /* The inplace routine never actually sets the progress to 100% due
2064 * to the round down nature of integer division, so set it here */
2065 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002066 }
2067
2068 return rc;
2069}
2070
Paul Crowleyb64933a2017-10-31 08:25:55 -07002071static int vold_unmountAll(void) {
2072 VolumeManager* vm = VolumeManager::Instance();
2073 return vm->unmountAll();
2074}
2075
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002076int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002077 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002078 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002079 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002080 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002081 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002082 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002083 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002084 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002085 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002086 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002087 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002088 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002089 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002090 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002091
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002092 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002093 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2094 /* An encryption was underway and was interrupted */
2095 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2096 crypt_ftr.encrypted_upto = 0;
2097 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002098
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002099 /* At this point, we are in an inconsistent state. Until we successfully
2100 complete encryption, a reboot will leave us broken. So mark the
2101 encryption failed in case that happens.
2102 On successfully completing encryption, remove this flag */
2103 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002104
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002105 put_crypt_ftr_and_key(&crypt_ftr);
2106 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2107 if (!check_ftr_sha(&crypt_ftr)) {
2108 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2109 put_crypt_ftr_and_key(&crypt_ftr);
2110 goto error_unencrypted;
2111 }
2112
2113 /* Doing a reboot-encryption*/
2114 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2115 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2116 rebootEncryption = true;
2117 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002118 } else {
2119 // We don't want to accidentally reference invalid data.
2120 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002121 }
2122
2123 property_get("ro.crypto.state", encrypted_state, "");
2124 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2125 SLOGE("Device is already running encrypted, aborting");
2126 goto error_unencrypted;
2127 }
2128
Tom Cherry4c5bde22019-01-29 14:34:01 -08002129 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002130
Ken Sumrall3ed82362011-01-28 23:31:16 -08002131 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002132 uint64_t nr_sec;
2133 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002134 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002135 goto error_unencrypted;
2136 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002137
2138 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002139 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002140 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002141 fs_size_sec = get_fs_size(real_blkdev.c_str());
2142 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002143
Paul Lawrence87999172014-02-20 12:21:31 -08002144 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002145
2146 if (fs_size_sec > max_fs_size_sec) {
2147 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2148 goto error_unencrypted;
2149 }
2150 }
2151
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002152 /* Get a wakelock as this may take a while, and we don't want the
2153 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2154 * wants to keep the screen on, it can grab a full wakelock.
2155 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002156 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002157 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002158
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002159 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002160 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002161 */
2162 property_set("vold.decrypt", "trigger_shutdown_framework");
2163 SLOGD("Just asked init to shut down class main\n");
2164
Jeff Sharkey9c484982015-03-31 10:35:33 -07002165 /* Ask vold to unmount all devices that it manages */
2166 if (vold_unmountAll()) {
2167 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002168 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002169
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002170 /* no_ui means we are being called from init, not settings.
2171 Now we always reboot from settings, so !no_ui means reboot
2172 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002173 if (!no_ui) {
2174 /* Try fallback, which is to reboot and try there */
2175 onlyCreateHeader = true;
2176 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2177 if (breadcrumb == 0) {
2178 SLOGE("Failed to create breadcrumb file");
2179 goto error_shutting_down;
2180 }
2181 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002182 }
2183
2184 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002185 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002186 /* Now that /data is unmounted, we need to mount a tmpfs
2187 * /data, set a property saying we're doing inplace encryption,
2188 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002189 */
xzj7e38a3a2018-10-12 10:17:11 +08002190 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002191 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002192 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002193 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002194 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002195 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002196
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002197 /* restart the framework. */
2198 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002199 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002200
Ken Sumrall92736ef2012-10-17 20:57:14 -07002201 /* Ugh, shutting down the framework is not synchronous, so until it
2202 * can be fixed, this horrible hack will wait a moment for it all to
2203 * shut down before proceeding. Without it, some devices cannot
2204 * restart the graphics services.
2205 */
2206 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002207 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002208
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002209 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002210 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002211 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002212 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2213 goto error_shutting_down;
2214 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002215
Tom Cherry4c5bde22019-01-29 14:34:01 -08002216 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002217 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002218 } else {
2219 crypt_ftr.fs_size = nr_sec;
2220 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002221 /* At this point, we are in an inconsistent state. Until we successfully
2222 complete encryption, a reboot will leave us broken. So mark the
2223 encryption failed in case that happens.
2224 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002225 if (onlyCreateHeader) {
2226 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2227 } else {
2228 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2229 }
Paul Lawrence87999172014-02-20 12:21:31 -08002230 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002231 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002232 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002233
Paul Lawrence87999172014-02-20 12:21:31 -08002234 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002235 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2236 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002237 SLOGE("Cannot create encrypted master key\n");
2238 goto error_shutting_down;
2239 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002240
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002241 /* Replace scrypted intermediate key if we are preparing for a reboot */
2242 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002243 unsigned char fake_master_key[MAX_KEY_LEN];
2244 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002245 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002246 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2247 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002248 }
2249
Paul Lawrence87999172014-02-20 12:21:31 -08002250 /* Write the key to the end of the partition */
2251 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002252
Paul Lawrence87999172014-02-20 12:21:31 -08002253 /* If any persistent data has been remembered, save it.
2254 * If none, create a valid empty table and save that.
2255 */
2256 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002257 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2258 if (pdata) {
2259 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2260 persist_data = pdata;
2261 }
Paul Lawrence87999172014-02-20 12:21:31 -08002262 }
2263 if (persist_data) {
2264 save_persistent_data();
2265 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002266 }
2267
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002268 if (onlyCreateHeader) {
2269 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002270 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002271 }
2272
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002273 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002274 /* startup service classes main and late_start */
2275 property_set("vold.decrypt", "trigger_restart_min_framework");
2276 SLOGD("Just triggered restart_min_framework\n");
2277
2278 /* OK, the framework is restarted and will soon be showing a
2279 * progress bar. Time to setup an encrypted mapping, and
2280 * either write a new filesystem, or encrypt in place updating
2281 * the progress bar as we work.
2282 */
2283 }
2284
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002285 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002286 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002287 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002288
Paul Lawrence87999172014-02-20 12:21:31 -08002289 /* If we are continuing, check checksums match */
2290 rc = 0;
2291 if (previously_encrypted_upto) {
2292 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002293 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002294
Paul Crowley14c8c072018-09-18 13:30:21 -07002295 if (!rc &&
2296 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002297 SLOGE("Checksums do not match - trigger wipe");
2298 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002299 }
2300 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002301
Paul Lawrence87999172014-02-20 12:21:31 -08002302 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002303 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002304 previously_encrypted_upto);
2305 }
2306
2307 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002308 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002309 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002310 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002311 SLOGE("Error calculating checksum for continuing encryption");
2312 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002313 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002314 }
2315
2316 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002317 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002318
Paul Crowley14c8c072018-09-18 13:30:21 -07002319 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002320 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002321 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002322
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002323 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002324 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2325 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002326 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002327 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002328
Paul Lawrence6bfed202014-07-28 12:47:22 -07002329 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002330
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002331 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2332 char value[PROPERTY_VALUE_MAX];
2333 property_get("ro.crypto.state", value, "");
2334 if (!strcmp(value, "")) {
2335 /* default encryption - continue first boot sequence */
2336 property_set("ro.crypto.state", "encrypted");
2337 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002338 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002339 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2340 // Bring up cryptkeeper that will check the password and set it
2341 property_set("vold.decrypt", "trigger_shutdown_framework");
2342 sleep(2);
2343 property_set("vold.encrypt_progress", "");
2344 cryptfs_trigger_restart_min_framework();
2345 } else {
2346 cryptfs_check_passwd(DEFAULT_PASSWORD);
2347 cryptfs_restart_internal(1);
2348 }
2349 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002350 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002351 sleep(2); /* Give the UI a chance to show 100% progress */
2352 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002353 }
Paul Lawrence87999172014-02-20 12:21:31 -08002354 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002355 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002356 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002357 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002358 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002359 char value[PROPERTY_VALUE_MAX];
2360
Ken Sumrall319369a2012-06-27 16:30:18 -07002361 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002362 if (!strcmp(value, "1")) {
2363 /* wipe data if encryption failed */
2364 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002365 std::string err;
2366 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002367 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002368 if (!write_bootloader_message(options, &err)) {
2369 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002370 }
Josh Gaofec44372017-08-28 13:22:55 -07002371 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002372 } else {
2373 /* set property to trigger dialog */
2374 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002375 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002376 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002377 }
2378
Ken Sumrall3ed82362011-01-28 23:31:16 -08002379 /* hrm, the encrypt step claims success, but the reboot failed.
2380 * This should not happen.
2381 * Set the property and return. Hope the framework can deal with it.
2382 */
2383 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002384 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002385
2386error_unencrypted:
2387 property_set("vold.encrypt_progress", "error_not_encrypted");
2388 return -1;
2389
2390error_shutting_down:
2391 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2392 * but the framework is stopped and not restarted to show the error, so it's up to
2393 * vold to restart the system.
2394 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002395 SLOGE(
2396 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2397 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002398 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002399
2400 /* shouldn't get here */
2401 property_set("vold.encrypt_progress", "error_shutting_down");
2402 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002403}
2404
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002405int cryptfs_enable(int type, const char* passwd, int no_ui) {
2406 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002407}
2408
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002409int cryptfs_enable_default(int no_ui) {
2410 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002411}
2412
Paul Crowley14c8c072018-09-18 13:30:21 -07002413int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002414 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002415 SLOGE("cryptfs_changepw not valid for file encryption");
2416 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002417 }
2418
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002419 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002420 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002421
2422 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002423 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002424 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002425 return -1;
2426 }
2427
Paul Lawrencef4faa572014-01-29 13:31:03 -08002428 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2429 SLOGE("Invalid crypt_type %d", crypt_type);
2430 return -1;
2431 }
2432
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002433 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002434 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002435 SLOGE("Error getting crypt footer and key");
2436 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002437 }
2438
Paul Lawrencef4faa572014-01-29 13:31:03 -08002439 crypt_ftr.crypt_type = crypt_type;
2440
Paul Crowley14c8c072018-09-18 13:30:21 -07002441 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2442 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002443 if (rc) {
2444 SLOGE("Encrypt master key failed: %d", rc);
2445 return -1;
2446 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002447 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002448 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002449
2450 return 0;
2451}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002452
Rubin Xu85c01f92014-10-13 12:49:54 +01002453static unsigned int persist_get_max_entries(int encrypted) {
2454 struct crypt_mnt_ftr crypt_ftr;
2455 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002456
2457 /* If encrypted, use the values from the crypt_ftr, otherwise
2458 * use the values for the current spec.
2459 */
2460 if (encrypted) {
2461 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002462 /* Something is wrong, assume no space for entries */
2463 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002464 }
2465 dsize = crypt_ftr.persist_data_size;
2466 } else {
2467 dsize = CRYPT_PERSIST_DATA_SIZE;
2468 }
2469
Rubin Xuf83cc612018-10-09 16:13:38 +01002470 if (dsize > sizeof(struct crypt_persist_data)) {
2471 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2472 } else {
2473 return 0;
2474 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002475}
2476
Paul Crowley14c8c072018-09-18 13:30:21 -07002477static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002478 unsigned int i;
2479
2480 if (persist_data == NULL) {
2481 return -1;
2482 }
2483 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2484 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2485 /* We found it! */
2486 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2487 return 0;
2488 }
2489 }
2490
2491 return -1;
2492}
2493
Paul Crowley14c8c072018-09-18 13:30:21 -07002494static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002495 unsigned int i;
2496 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002497 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002498
2499 if (persist_data == NULL) {
2500 return -1;
2501 }
2502
Rubin Xu85c01f92014-10-13 12:49:54 +01002503 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002504
2505 num = persist_data->persist_valid_entries;
2506
2507 for (i = 0; i < num; i++) {
2508 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2509 /* We found an existing entry, update it! */
2510 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2511 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2512 return 0;
2513 }
2514 }
2515
2516 /* We didn't find it, add it to the end, if there is room */
2517 if (persist_data->persist_valid_entries < max_persistent_entries) {
2518 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2519 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2520 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2521 persist_data->persist_valid_entries++;
2522 return 0;
2523 }
2524
2525 return -1;
2526}
2527
Rubin Xu85c01f92014-10-13 12:49:54 +01002528/**
2529 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2530 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2531 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002532int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002533 std::string key_ = key;
2534 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002535
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002536 std::string parsed_field;
2537 unsigned parsed_index;
2538
2539 std::string::size_type split = key_.find_last_of('_');
2540 if (split == std::string::npos) {
2541 parsed_field = key_;
2542 parsed_index = 0;
2543 } else {
2544 parsed_field = key_.substr(0, split);
2545 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002546 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002547
2548 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002549}
2550
2551/*
2552 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2553 * remaining entries starting from index will be deleted.
2554 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2555 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2556 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2557 *
2558 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002559static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002560 unsigned int i;
2561 unsigned int j;
2562 unsigned int num;
2563
2564 if (persist_data == NULL) {
2565 return PERSIST_DEL_KEY_ERROR_OTHER;
2566 }
2567
2568 num = persist_data->persist_valid_entries;
2569
Paul Crowley14c8c072018-09-18 13:30:21 -07002570 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002571 // Filter out to-be-deleted entries in place.
2572 for (i = 0; i < num; i++) {
2573 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2574 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2575 j++;
2576 }
2577 }
2578
2579 if (j < num) {
2580 persist_data->persist_valid_entries = j;
2581 // Zeroise the remaining entries
2582 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2583 return PERSIST_DEL_KEY_OK;
2584 } else {
2585 // Did not find an entry matching the given fieldname
2586 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2587 }
2588}
2589
Paul Crowley14c8c072018-09-18 13:30:21 -07002590static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002591 unsigned int i;
2592 unsigned int count;
2593
2594 if (persist_data == NULL) {
2595 return -1;
2596 }
2597
2598 count = 0;
2599 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2600 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2601 count++;
2602 }
2603 }
2604
2605 return count;
2606}
2607
Ken Sumrall160b4d62013-04-22 12:15:39 -07002608/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002609int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002610 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002611 SLOGE("Cannot get field when file encrypted");
2612 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002613 }
2614
Ken Sumrall160b4d62013-04-22 12:15:39 -07002615 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002616 /* CRYPTO_GETFIELD_OK is success,
2617 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2618 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2619 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002620 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002621 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2622 int i;
2623 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002624
2625 if (persist_data == NULL) {
2626 load_persistent_data();
2627 if (persist_data == NULL) {
2628 SLOGE("Getfield error, cannot load persistent data");
2629 goto out;
2630 }
2631 }
2632
Rubin Xu85c01f92014-10-13 12:49:54 +01002633 // Read value from persistent entries. If the original value is split into multiple entries,
2634 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002635 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002636 // 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 -07002637 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002638 // value too small
2639 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2640 goto out;
2641 }
2642 rc = CRYPTO_GETFIELD_OK;
2643
2644 for (i = 1; /* break explicitly */; i++) {
2645 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002646 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002647 // If the fieldname is very long, we stop as soon as it begins to overflow the
2648 // maximum field length. At this point we have in fact fully read out the original
2649 // value because cryptfs_setfield would not allow fields with longer names to be
2650 // written in the first place.
2651 break;
2652 }
2653 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002654 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2655 // value too small.
2656 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2657 goto out;
2658 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002659 } else {
2660 // Exhaust all entries.
2661 break;
2662 }
2663 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002664 } else {
2665 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002666 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002667 }
2668
2669out:
2670 return rc;
2671}
2672
2673/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002674int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002675 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002676 SLOGE("Cannot set field when file encrypted");
2677 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002678 }
2679
Ken Sumrall160b4d62013-04-22 12:15:39 -07002680 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002681 /* 0 is success, negative values are error */
2682 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002683 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002684 unsigned int field_id;
2685 char temp_field[PROPERTY_KEY_MAX];
2686 unsigned int num_entries;
2687 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688
2689 if (persist_data == NULL) {
2690 load_persistent_data();
2691 if (persist_data == NULL) {
2692 SLOGE("Setfield error, cannot load persistent data");
2693 goto out;
2694 }
2695 }
2696
2697 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002698 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002699 encrypted = 1;
2700 }
2701
Rubin Xu85c01f92014-10-13 12:49:54 +01002702 // Compute the number of entries required to store value, each entry can store up to
2703 // (PROPERTY_VALUE_MAX - 1) chars
2704 if (strlen(value) == 0) {
2705 // Empty value also needs one entry to store.
2706 num_entries = 1;
2707 } else {
2708 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2709 }
2710
2711 max_keylen = strlen(fieldname);
2712 if (num_entries > 1) {
2713 // Need an extra "_%d" suffix.
2714 max_keylen += 1 + log10(num_entries);
2715 }
2716 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2717 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002718 goto out;
2719 }
2720
Rubin Xu85c01f92014-10-13 12:49:54 +01002721 // Make sure we have enough space to write the new value
2722 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2723 persist_get_max_entries(encrypted)) {
2724 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2725 goto out;
2726 }
2727
2728 // Now that we know persist_data has enough space for value, let's delete the old field first
2729 // to make up space.
2730 persist_del_keys(fieldname, 0);
2731
2732 if (persist_set_key(fieldname, value, encrypted)) {
2733 // fail to set key, should not happen as we have already checked the available space
2734 SLOGE("persist_set_key() error during setfield()");
2735 goto out;
2736 }
2737
2738 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002739 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002740
2741 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2742 // fail to set key, should not happen as we have already checked the available space.
2743 SLOGE("persist_set_key() error during setfield()");
2744 goto out;
2745 }
2746 }
2747
Ken Sumrall160b4d62013-04-22 12:15:39 -07002748 /* If we are running encrypted, save the persistent data now */
2749 if (encrypted) {
2750 if (save_persistent_data()) {
2751 SLOGE("Setfield error, cannot save persistent data");
2752 goto out;
2753 }
2754 }
2755
Rubin Xu85c01f92014-10-13 12:49:54 +01002756 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002757
2758out:
2759 return rc;
2760}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002761
2762/* Checks userdata. Attempt to mount the volume if default-
2763 * encrypted.
2764 * On success trigger next init phase and return 0.
2765 * Currently do not handle failure - see TODO below.
2766 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002767int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002768 int crypt_type = cryptfs_get_password_type();
2769 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2770 SLOGE("Bad crypt type - error");
2771 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002772 SLOGD(
2773 "Password is not default - "
2774 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002775 property_set("vold.decrypt", "trigger_restart_min_framework");
2776 return 0;
2777 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2778 SLOGD("Password is default - restarting filesystem");
2779 cryptfs_restart_internal(0);
2780 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002781 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002782 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002783 }
2784
Paul Lawrence6bfed202014-07-28 12:47:22 -07002785 /** Corrupt. Allow us to boot into framework, which will detect bad
2786 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002787 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002788 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002789 return 0;
2790}
2791
2792/* Returns type of the password, default, pattern, pin or password.
2793 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002794int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002795 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002796 SLOGE("cryptfs_get_password_type not valid for file encryption");
2797 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002798 }
2799
Paul Lawrencef4faa572014-01-29 13:31:03 -08002800 struct crypt_mnt_ftr crypt_ftr;
2801
2802 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2803 SLOGE("Error getting crypt footer and key\n");
2804 return -1;
2805 }
2806
Paul Lawrence6bfed202014-07-28 12:47:22 -07002807 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2808 return -1;
2809 }
2810
Paul Lawrencef4faa572014-01-29 13:31:03 -08002811 return crypt_ftr.crypt_type;
2812}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002813
Paul Crowley14c8c072018-09-18 13:30:21 -07002814const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002815 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002816 SLOGE("cryptfs_get_password not valid for file encryption");
2817 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002818 }
2819
Paul Lawrence399317e2014-03-10 13:20:50 -07002820 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002821 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002822 if (now.tv_sec < password_expiry_time) {
2823 return password;
2824 } else {
2825 cryptfs_clear_password();
2826 return 0;
2827 }
2828}
2829
Paul Crowley14c8c072018-09-18 13:30:21 -07002830void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002831 if (password) {
2832 size_t len = strlen(password);
2833 memset(password, 0, len);
2834 free(password);
2835 password = 0;
2836 password_expiry_time = 0;
2837 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002838}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002839
Paul Crowley14c8c072018-09-18 13:30:21 -07002840int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002841 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2842 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002843}