blob: 38661f3bc73391667486aed5051747ff50ba0637 [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;
David Andersonb9224732019-05-13 13:02:54 -070077using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070078using namespace std::chrono_literals;
79
Paul Crowley73be12d2020-02-03 12:22:03 -080080/* The current cryptfs version */
81#define CURRENT_MAJOR_VERSION 1
82#define CURRENT_MINOR_VERSION 3
83
84#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
85#define CRYPT_PERSIST_DATA_SIZE 0x1000
86
87#define MAX_CRYPTO_TYPE_NAME_LEN 64
88
89#define MAX_KEY_LEN 48
90#define SALT_LEN 16
91#define SCRYPT_LEN 32
92
93/* definitions of flags in the structure below */
94#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
95#define CRYPT_ENCRYPTION_IN_PROGRESS \
96 0x2 /* Encryption partially completed, \
97 encrypted_upto valid*/
98#define CRYPT_INCONSISTENT_STATE \
99 0x4 /* Set when starting encryption, clear when \
100 exit cleanly, either through success or \
101 correctly marked partial encryption */
102#define CRYPT_DATA_CORRUPT \
103 0x8 /* Set when encryption is fine, but the \
104 underlying volume is corrupt */
105#define CRYPT_FORCE_ENCRYPTION \
106 0x10 /* Set when it is time to encrypt this \
107 volume on boot. Everything in this \
108 structure is set up correctly as \
109 though device is encrypted except \
110 that the master key is encrypted with the \
111 default password. */
112#define CRYPT_FORCE_COMPLETE \
113 0x20 /* Set when the above encryption cycle is \
114 complete. On next cryptkeeper entry, match \
115 the password. If it matches fix the master \
116 key and remove this flag. */
117
118/* Allowed values for type in the structure below */
119#define CRYPT_TYPE_PASSWORD \
120 0 /* master_key is encrypted with a password \
121 * Must be zero to be compatible with pre-L \
122 * devices where type is always password.*/
123#define CRYPT_TYPE_DEFAULT \
124 1 /* master_key is encrypted with default \
125 * password */
126#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
127#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
128#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
129
130#define CRYPT_MNT_MAGIC 0xD0B5B1C4
131#define PERSIST_DATA_MAGIC 0xE950CD44
132
133/* Key Derivation Function algorithms */
134#define KDF_PBKDF2 1
135#define KDF_SCRYPT 2
136/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
137#define KDF_SCRYPT_KEYMASTER 5
138
139/* Maximum allowed keymaster blob size. */
140#define KEYMASTER_BLOB_SIZE 2048
141
142/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
143#define __le8 unsigned char
144
145#if !defined(SHA256_DIGEST_LENGTH)
146#define SHA256_DIGEST_LENGTH 32
147#endif
148
149/* This structure starts 16,384 bytes before the end of a hardware
150 * partition that is encrypted, or in a separate partition. It's location
151 * is specified by a property set in init.<device>.rc.
152 * The structure allocates 48 bytes for a key, but the real key size is
153 * specified in the struct. Currently, the code is hardcoded to use 128
154 * bit keys.
155 * The fields after salt are only valid in rev 1.1 and later stuctures.
156 * Obviously, the filesystem does not include the last 16 kbytes
157 * of the partition if the crypt_mnt_ftr lives at the end of the
158 * partition.
159 */
160
161struct crypt_mnt_ftr {
162 __le32 magic; /* See above */
163 __le16 major_version;
164 __le16 minor_version;
165 __le32 ftr_size; /* in bytes, not including key following */
166 __le32 flags; /* See above */
167 __le32 keysize; /* in bytes */
168 __le32 crypt_type; /* how master_key is encrypted. Must be a
169 * CRYPT_TYPE_XXX value */
170 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
171 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
172 mount, set to 0 on successful mount */
173 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
174 needed to decrypt this
175 partition, null terminated */
176 __le32 spare2; /* ignored */
177 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
178 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
179 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
180 * on device with that info, either the footer of the
181 * real_blkdevice or the metadata partition. */
182
183 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
184 * persistent data table*/
185
186 __le8 kdf_type; /* The key derivation function used. */
187
188 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
189 __le8 N_factor; /* (1 << N) */
190 __le8 r_factor; /* (1 << r) */
191 __le8 p_factor; /* (1 << p) */
192 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
193 we have to stop (e.g. power low) this is the last
194 encrypted 512 byte sector.*/
195 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
196 set, hash of first block, used
197 to validate before continuing*/
198
199 /* key_master key, used to sign the derived key which is then used to generate
200 * the intermediate key
201 * This key should be used for no other purposes! We use this key to sign unpadded
202 * data, which is acceptable but only if the key is not reused elsewhere. */
203 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
204 __le32 keymaster_blob_size;
205
206 /* Store scrypt of salted intermediate key. When decryption fails, we can
207 check if this matches, and if it does, we know that the problem is with the
208 drive, and there is no point in asking the user for more passwords.
209
210 Note that if any part of this structure is corrupt, this will not match and
211 we will continue to believe the user entered the wrong password. In that
212 case the only solution is for the user to enter a password enough times to
213 force a wipe.
214
215 Note also that there is no need to worry about migration. If this data is
216 wrong, we simply won't recognise a right password, and will continue to
217 prompt. On the first password change, this value will be populated and
218 then we will be OK.
219 */
220 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
221
222 /* sha of this structure with this element set to zero
223 Used when encrypting on reboot to validate structure before doing something
224 fatal
225 */
226 unsigned char sha256[SHA256_DIGEST_LENGTH];
227};
228
229/* Persistant data that should be available before decryption.
230 * Things like airplane mode, locale and timezone are kept
231 * here and can be retrieved by the CryptKeeper UI to properly
232 * configure the phone before asking for the password
233 * This is only valid if the major and minor version above
234 * is set to 1.1 or higher.
235 *
236 * This is a 4K structure. There are 2 copies, and the code alternates
237 * writing one and then clearing the previous one. The reading
238 * code reads the first valid copy it finds, based on the magic number.
239 * The absolute offset to the first of the two copies is kept in rev 1.1
240 * and higher crypt_mnt_ftr structures.
241 */
242struct crypt_persist_entry {
243 char key[PROPERTY_KEY_MAX];
244 char val[PROPERTY_VALUE_MAX];
245};
246
247/* Should be exactly 4K in size */
248struct crypt_persist_data {
249 __le32 persist_magic;
250 __le32 persist_valid_entries;
251 __le32 persist_spare[30];
252 struct crypt_persist_entry persist_entry[0];
253};
254
255static int wait_and_unmount(const char* mountpoint, bool kill);
256
257typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
258 void* params);
259
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800260#define UNUSED __attribute__((unused))
261
Jason parks70a4b3f2011-01-28 10:10:47 -0600262#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800263
264constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
265constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700266constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800267
268// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700269static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600270
Paul Crowley14c8c072018-09-18 13:30:21 -0700271#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700272
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700273#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800274
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800275#define CRYPTO_BLOCK_DEVICE "userdata"
276
277#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
278
Ken Sumrall29d8da82011-05-18 17:20:07 -0700279#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700280#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700281
Ken Sumralle919efe2012-09-29 17:07:41 -0700282#define TABLE_LOAD_RETRIES 10
283
Shawn Willden47ba10d2014-09-03 17:07:06 -0600284#define RSA_KEY_SIZE 2048
285#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
286#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600287#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700288
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700289#define RETRY_MOUNT_ATTEMPTS 10
290#define RETRY_MOUNT_DELAY_SECONDS 1
291
Paul Crowley5afbc622017-11-27 09:42:17 -0800292#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
293
Paul Crowley73473332017-11-21 15:43:51 -0800294static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
295
Greg Kaiser59ad0182018-02-16 13:01:36 -0800296static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700297static char* saved_mount_point;
298static int master_key_saved = 0;
299static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800300
Paul Crowley220567c2020-02-07 12:45:20 -0800301constexpr CryptoType aes_128_cbc = CryptoType()
302 .set_config_name("AES-128-CBC")
303 .set_kernel_name("aes-cbc-essiv:sha256")
304 .set_keysize(16);
305
306constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
307
308static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
309 array_length(supported_crypto_types)),
310 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
311 "incompletely constructed.");
312
313static const CryptoType& get_crypto_type() {
314 // We only want to parse this read-only property once. But we need to wait
315 // until the system is initialized before we can read it. So we use a static
316 // scoped within this function to get it only once.
317 static CryptoType crypto_type =
318 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
319 aes_128_cbc, "ro.crypto.fde_algorithm");
320 return crypto_type;
321}
322
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700323/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700324static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000325 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700326}
327
328/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700329static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800330 if (ftr->keymaster_blob_size) {
331 SLOGI("Already have key");
332 return 0;
333 }
334
Paul Crowley14c8c072018-09-18 13:30:21 -0700335 int rc = keymaster_create_key_for_cryptfs_scrypt(
336 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
337 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000338 if (rc) {
339 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800340 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000341 ftr->keymaster_blob_size = 0;
342 }
343 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700344 return -1;
345 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000346 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700347}
348
Shawn Willdene17a9c42014-09-08 13:04:08 -0600349/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700350static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
351 const size_t object_size, unsigned char** signature,
352 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600353 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600354 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600355 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600356
Shawn Willdene17a9c42014-09-08 13:04:08 -0600357 // To sign a message with RSA, the message must satisfy two
358 // constraints:
359 //
360 // 1. The message, when interpreted as a big-endian numeric value, must
361 // be strictly less than the public modulus of the RSA key. Note
362 // that because the most significant bit of the public modulus is
363 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
364 // key), an n-bit message with most significant bit 0 always
365 // satisfies this requirement.
366 //
367 // 2. The message must have the same length in bits as the public
368 // modulus of the RSA key. This requirement isn't mathematically
369 // necessary, but is necessary to ensure consistency in
370 // implementations.
371 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600372 case KDF_SCRYPT_KEYMASTER:
373 // This ensures the most significant byte of the signed message
374 // is zero. We could have zero-padded to the left instead, but
375 // this approach is slightly more robust against changes in
376 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600377 // so) because we really should be using a proper deterministic
378 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800379 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600380 SLOGI("Signing safely-padded object");
381 break;
382 default:
383 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000384 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600385 }
Paul Crowley73473332017-11-21 15:43:51 -0800386 for (;;) {
387 auto result = keymaster_sign_object_for_cryptfs_scrypt(
388 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
389 to_sign_size, signature, signature_size);
390 switch (result) {
391 case KeymasterSignResult::ok:
392 return 0;
393 case KeymasterSignResult::upgrade:
394 break;
395 default:
396 return -1;
397 }
398 SLOGD("Upgrading key");
399 if (keymaster_upgrade_key_for_cryptfs_scrypt(
400 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
401 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
402 &ftr->keymaster_blob_size) != 0) {
403 SLOGE("Failed to upgrade key");
404 return -1;
405 }
406 if (put_crypt_ftr_and_key(ftr) != 0) {
407 SLOGE("Failed to write upgraded key to disk");
408 }
409 SLOGD("Key upgraded successfully");
410 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600411}
412
Paul Lawrence399317e2014-03-10 13:20:50 -0700413/* Store password when userdata is successfully decrypted and mounted.
414 * Cleared by cryptfs_clear_password
415 *
416 * To avoid a double prompt at boot, we need to store the CryptKeeper
417 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
418 * Since the entire framework is torn down and rebuilt after encryption,
419 * we have to use a daemon or similar to store the password. Since vold
420 * is secured against IPC except from system processes, it seems a reasonable
421 * place to store this.
422 *
423 * password should be cleared once it has been used.
424 *
425 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800426 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700427static char* password = 0;
428static int password_expiry_time = 0;
429static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800430
Paul Crowley14c8c072018-09-18 13:30:21 -0700431enum class RebootType { reboot, recovery, shutdown };
432static void cryptfs_reboot(RebootType rt) {
433 switch (rt) {
434 case RebootType::reboot:
435 property_set(ANDROID_RB_PROPERTY, "reboot");
436 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800437
Paul Crowley14c8c072018-09-18 13:30:21 -0700438 case RebootType::recovery:
439 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
440 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800441
Paul Crowley14c8c072018-09-18 13:30:21 -0700442 case RebootType::shutdown:
443 property_set(ANDROID_RB_PROPERTY, "shutdown");
444 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700445 }
Paul Lawrence87999172014-02-20 12:21:31 -0800446
Ken Sumralladfba362013-06-04 16:37:52 -0700447 sleep(20);
448
449 /* Shouldn't get here, reboot should happen before sleep times out */
450 return;
451}
452
Kenny Rootc4c70f12013-06-14 12:11:38 -0700453/**
454 * Gets the default device scrypt parameters for key derivation time tuning.
455 * The parameters should lead to about one second derivation time for the
456 * given device.
457 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700458static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700459 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000460 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700461
Paul Crowley63c18d32016-02-10 14:02:47 +0000462 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
463 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
464 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
465 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700466 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000467 ftr->N_factor = Nf;
468 ftr->r_factor = rf;
469 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700470}
471
Paul Crowleya661fb62020-02-11 16:21:54 -0800472size_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800473 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800474}
475
Tom Cherry4c5bde22019-01-29 14:34:01 -0800476static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800477 int fd, block_size;
478 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200479 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800480
Paul Crowley14c8c072018-09-18 13:30:21 -0700481 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800482 SLOGE("Cannot open device to get filesystem size ");
483 return 0;
484 }
485
486 if (lseek64(fd, 1024, SEEK_SET) < 0) {
487 SLOGE("Cannot seek to superblock");
488 return 0;
489 }
490
491 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
492 SLOGE("Cannot read superblock");
493 return 0;
494 }
495
496 close(fd);
497
Daniel Rosenberge82df162014-08-15 22:19:23 +0000498 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
499 SLOGE("Not a valid ext4 superblock");
500 return 0;
501 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800502 block_size = 1024 << sb.s_log_block_size;
503 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200504 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800505
506 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200507 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800508}
509
Tom Cherry4c5bde22019-01-29 14:34:01 -0800510static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
511 for (const auto& entry : fstab_default) {
512 if (!entry.fs_mgr_flags.vold_managed &&
513 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
514 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
515 if (key_loc != nullptr) {
516 *key_loc = entry.key_loc;
517 }
518 if (real_blk_device != nullptr) {
519 *real_blk_device = entry.blk_device;
520 }
521 return;
522 }
523 }
524}
525
Paul Crowley14c8c072018-09-18 13:30:21 -0700526static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
527 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200528 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700529 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700530 char key_loc[PROPERTY_VALUE_MAX];
531 char real_blkdev[PROPERTY_VALUE_MAX];
532 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533
Paul Crowley14c8c072018-09-18 13:30:21 -0700534 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800535 std::string key_loc;
536 std::string real_blkdev;
537 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700538
Tom Cherry4c5bde22019-01-29 14:34:01 -0800539 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200540 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700541 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
542 * encryption info footer and key, and plenty of bytes to spare for future
543 * growth.
544 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800545 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200546 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700547 cached_data = 1;
548 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800549 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700550 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700551 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800552 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700553 cached_off = 0;
554 cached_data = 1;
555 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557
Paul Crowley14c8c072018-09-18 13:30:21 -0700558 if (cached_data) {
559 if (metadata_fname) {
560 *metadata_fname = cached_metadata_fname;
561 }
562 if (off) {
563 *off = cached_off;
564 }
565 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700566 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700567
Paul Crowley14c8c072018-09-18 13:30:21 -0700568 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700569}
570
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800571/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700572static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800573 SHA256_CTX c;
574 SHA256_Init(&c);
575 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
576 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
577 SHA256_Final(crypt_ftr->sha256, &c);
578}
579
Ken Sumralle8744072011-01-18 22:01:55 -0800580/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800581 * update the failed mount count but not change the key.
582 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700583static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
584 int fd;
585 unsigned int cnt;
586 /* starting_off is set to the SEEK_SET offset
587 * where the crypto structure starts
588 */
589 off64_t starting_off;
590 int rc = -1;
591 char* fname = NULL;
592 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800593
Paul Crowley14c8c072018-09-18 13:30:21 -0700594 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800595
Paul Crowley14c8c072018-09-18 13:30:21 -0700596 if (get_crypt_ftr_info(&fname, &starting_off)) {
597 SLOGE("Unable to get crypt_ftr_info\n");
598 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800599 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700600 if (fname[0] != '/') {
601 SLOGE("Unexpected value for crypto key location\n");
602 return -1;
603 }
604 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
605 SLOGE("Cannot open footer file %s for put\n", fname);
606 return -1;
607 }
Ken Sumralle8744072011-01-18 22:01:55 -0800608
Paul Crowley14c8c072018-09-18 13:30:21 -0700609 /* Seek to the start of the crypt footer */
610 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
611 SLOGE("Cannot seek to real block device footer\n");
612 goto errout;
613 }
614
615 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
616 SLOGE("Cannot write real block device footer\n");
617 goto errout;
618 }
619
620 fstat(fd, &statbuf);
621 /* If the keys are kept on a raw block device, do not try to truncate it. */
622 if (S_ISREG(statbuf.st_mode)) {
623 if (ftruncate(fd, 0x4000)) {
624 SLOGE("Cannot set footer file size\n");
625 goto errout;
626 }
627 }
628
629 /* Success! */
630 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800631
632errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700633 close(fd);
634 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800635}
636
Paul Crowley14c8c072018-09-18 13:30:21 -0700637static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800638 struct crypt_mnt_ftr copy;
639 memcpy(&copy, crypt_ftr, sizeof(copy));
640 set_ftr_sha(&copy);
641 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
642}
643
Paul Crowley14c8c072018-09-18 13:30:21 -0700644static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700645 return TEMP_FAILURE_RETRY(read(fd, buff, len));
646}
647
Paul Crowley14c8c072018-09-18 13:30:21 -0700648static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700649 return TEMP_FAILURE_RETRY(write(fd, buff, len));
650}
651
Paul Crowley14c8c072018-09-18 13:30:21 -0700652static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700653 memset(pdata, 0, len);
654 pdata->persist_magic = PERSIST_DATA_MAGIC;
655 pdata->persist_valid_entries = 0;
656}
657
658/* A routine to update the passed in crypt_ftr to the lastest version.
659 * fd is open read/write on the device that holds the crypto footer and persistent
660 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
661 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
662 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700663static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700664 int orig_major = crypt_ftr->major_version;
665 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700666
Kenny Root7434b312013-06-14 11:29:53 -0700667 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700668 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700669 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670
Kenny Rootc4c70f12013-06-14 12:11:38 -0700671 SLOGW("upgrading crypto footer to 1.1");
672
Paul Crowley14c8c072018-09-18 13:30:21 -0700673 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700674 if (pdata == NULL) {
675 SLOGE("Cannot allocate persisent data\n");
676 return;
677 }
678 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
679
680 /* Need to initialize the persistent data area */
681 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
682 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100683 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700684 return;
685 }
686 /* Write all zeros to the first copy, making it invalid */
687 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
688
689 /* Write a valid but empty structure to the second copy */
690 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
691 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
692
693 /* Update the footer */
694 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
695 crypt_ftr->persist_data_offset[0] = pdata_offset;
696 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
697 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100698 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700699 }
700
Paul Lawrencef4faa572014-01-29 13:31:03 -0800701 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700702 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800703 /* But keep the old kdf_type.
704 * It will get updated later to KDF_SCRYPT after the password has been verified.
705 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700706 crypt_ftr->kdf_type = KDF_PBKDF2;
707 get_device_scrypt_params(crypt_ftr);
708 crypt_ftr->minor_version = 2;
709 }
710
Paul Lawrencef4faa572014-01-29 13:31:03 -0800711 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
712 SLOGW("upgrading crypto footer to 1.3");
713 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
714 crypt_ftr->minor_version = 3;
715 }
716
Kenny Root7434b312013-06-14 11:29:53 -0700717 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
718 if (lseek64(fd, offset, SEEK_SET) == -1) {
719 SLOGE("Cannot seek to crypt footer\n");
720 return;
721 }
722 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700724}
725
Paul Crowley14c8c072018-09-18 13:30:21 -0700726static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
727 int fd;
728 unsigned int cnt;
729 off64_t starting_off;
730 int rc = -1;
731 char* fname = NULL;
732 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700733
Paul Crowley14c8c072018-09-18 13:30:21 -0700734 if (get_crypt_ftr_info(&fname, &starting_off)) {
735 SLOGE("Unable to get crypt_ftr_info\n");
736 return -1;
737 }
738 if (fname[0] != '/') {
739 SLOGE("Unexpected value for crypto key location\n");
740 return -1;
741 }
742 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
743 SLOGE("Cannot open footer file %s for get\n", fname);
744 return -1;
745 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800746
Paul Crowley14c8c072018-09-18 13:30:21 -0700747 /* Make sure it's 16 Kbytes in length */
748 fstat(fd, &statbuf);
749 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
750 SLOGE("footer file %s is not the expected size!\n", fname);
751 goto errout;
752 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700753
Paul Crowley14c8c072018-09-18 13:30:21 -0700754 /* Seek to the start of the crypt footer */
755 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
756 SLOGE("Cannot seek to real block device footer\n");
757 goto errout;
758 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759
Paul Crowley14c8c072018-09-18 13:30:21 -0700760 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
761 SLOGE("Cannot read real block device footer\n");
762 goto errout;
763 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800764
Paul Crowley14c8c072018-09-18 13:30:21 -0700765 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
766 SLOGE("Bad magic for real block device %s\n", fname);
767 goto errout;
768 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800769
Paul Crowley14c8c072018-09-18 13:30:21 -0700770 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
771 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
772 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
773 goto errout;
774 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800775
Paul Crowley14c8c072018-09-18 13:30:21 -0700776 // We risk buffer overflows with oversized keys, so we just reject them.
777 // 0-sized keys are problematic (essentially by-passing encryption), and
778 // AES-CBC key wrapping only works for multiples of 16 bytes.
779 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
780 (crypt_ftr->keysize > MAX_KEY_LEN)) {
781 SLOGE(
782 "Invalid keysize (%u) for block device %s; Must be non-zero, "
783 "divisible by 16, and <= %d\n",
784 crypt_ftr->keysize, fname, MAX_KEY_LEN);
785 goto errout;
786 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800787
Paul Crowley14c8c072018-09-18 13:30:21 -0700788 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
789 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
790 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
791 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800792
Paul Crowley14c8c072018-09-18 13:30:21 -0700793 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
794 * copy on disk before returning.
795 */
796 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
797 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
798 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800799
Paul Crowley14c8c072018-09-18 13:30:21 -0700800 /* Success! */
801 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800802
803errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700804 close(fd);
805 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800806}
807
Paul Crowley14c8c072018-09-18 13:30:21 -0700808static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700809 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
810 crypt_ftr->persist_data_offset[1]) {
811 SLOGE("Crypt_ftr persist data regions overlap");
812 return -1;
813 }
814
815 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
816 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
817 return -1;
818 }
819
820 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700821 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700822 CRYPT_FOOTER_OFFSET) {
823 SLOGE("Persistent data extends past crypto footer");
824 return -1;
825 }
826
827 return 0;
828}
829
Paul Crowley14c8c072018-09-18 13:30:21 -0700830static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700831 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700832 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700833 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700834 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835 int found = 0;
836 int fd;
837 int ret;
838 int i;
839
840 if (persist_data) {
841 /* Nothing to do, we've already loaded or initialized it */
842 return 0;
843 }
844
Ken Sumrall160b4d62013-04-22 12:15:39 -0700845 /* If not encrypted, just allocate an empty table and initialize it */
846 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700847 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800848 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700849 if (pdata) {
850 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
851 persist_data = pdata;
852 return 0;
853 }
854 return -1;
855 }
856
Paul Crowley14c8c072018-09-18 13:30:21 -0700857 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700858 return -1;
859 }
860
Paul Crowley14c8c072018-09-18 13:30:21 -0700861 if ((crypt_ftr.major_version < 1) ||
862 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700863 SLOGE("Crypt_ftr version doesn't support persistent data");
864 return -1;
865 }
866
867 if (get_crypt_ftr_info(&fname, NULL)) {
868 return -1;
869 }
870
871 ret = validate_persistent_data_storage(&crypt_ftr);
872 if (ret) {
873 return -1;
874 }
875
Paul Crowley14c8c072018-09-18 13:30:21 -0700876 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700877 if (fd < 0) {
878 SLOGE("Cannot open %s metadata file", fname);
879 return -1;
880 }
881
Wei Wang4375f1b2017-02-24 17:43:01 -0800882 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800883 if (pdata == NULL) {
884 SLOGE("Cannot allocate memory for persistent data");
885 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700886 }
887
888 for (i = 0; i < 2; i++) {
889 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
890 SLOGE("Cannot seek to read persistent data on %s", fname);
891 goto err2;
892 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700893 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700894 SLOGE("Error reading persistent data on iteration %d", i);
895 goto err2;
896 }
897 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
898 found = 1;
899 break;
900 }
901 }
902
903 if (!found) {
904 SLOGI("Could not find valid persistent data, creating");
905 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
906 }
907
908 /* Success */
909 persist_data = pdata;
910 close(fd);
911 return 0;
912
913err2:
914 free(pdata);
915
916err:
917 close(fd);
918 return -1;
919}
920
Paul Crowley14c8c072018-09-18 13:30:21 -0700921static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700922 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700923 struct crypt_persist_data* pdata;
924 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700925 off64_t write_offset;
926 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700927 int fd;
928 int ret;
929
930 if (persist_data == NULL) {
931 SLOGE("No persistent data to save");
932 return -1;
933 }
934
Paul Crowley14c8c072018-09-18 13:30:21 -0700935 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700936 return -1;
937 }
938
Paul Crowley14c8c072018-09-18 13:30:21 -0700939 if ((crypt_ftr.major_version < 1) ||
940 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700941 SLOGE("Crypt_ftr version doesn't support persistent data");
942 return -1;
943 }
944
945 ret = validate_persistent_data_storage(&crypt_ftr);
946 if (ret) {
947 return -1;
948 }
949
950 if (get_crypt_ftr_info(&fname, NULL)) {
951 return -1;
952 }
953
Paul Crowley14c8c072018-09-18 13:30:21 -0700954 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700955 if (fd < 0) {
956 SLOGE("Cannot open %s metadata file", fname);
957 return -1;
958 }
959
Wei Wang4375f1b2017-02-24 17:43:01 -0800960 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700961 if (pdata == NULL) {
962 SLOGE("Cannot allocate persistant data");
963 goto err;
964 }
965
966 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
967 SLOGE("Cannot seek to read persistent data on %s", fname);
968 goto err2;
969 }
970
971 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700972 SLOGE("Error reading persistent data before save");
973 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700974 }
975
976 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
977 /* The first copy is the curent valid copy, so write to
978 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700979 write_offset = crypt_ftr.persist_data_offset[1];
980 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700981 } else {
982 /* The second copy must be the valid copy, so write to
983 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700984 write_offset = crypt_ftr.persist_data_offset[0];
985 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700986 }
987
988 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100989 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700990 SLOGE("Cannot seek to write persistent data");
991 goto err2;
992 }
993 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700994 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100995 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700996 SLOGE("Cannot seek to erase previous persistent data");
997 goto err2;
998 }
999 fsync(fd);
1000 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001001 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001002 SLOGE("Cannot write to erase previous persistent data");
1003 goto err2;
1004 }
1005 fsync(fd);
1006 } else {
1007 SLOGE("Cannot write to save persistent data");
1008 goto err2;
1009 }
1010
1011 /* Success */
1012 free(pdata);
1013 close(fd);
1014 return 0;
1015
1016err2:
1017 free(pdata);
1018err:
1019 close(fd);
1020 return -1;
1021}
1022
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001023/* Convert a binary key of specified length into an ascii hex string equivalent,
1024 * without the leading 0x and with null termination
1025 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001026static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1027 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001028 unsigned int i, a;
1029 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001030
Paul Crowley14c8c072018-09-18 13:30:21 -07001031 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001032 /* For each byte, write out two ascii hex digits */
1033 nibble = (master_key[i] >> 4) & 0xf;
1034 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001035
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001036 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001037 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001038 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001039
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001040 /* Add the null termination */
1041 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001042}
1043
Eric Biggersed45ec32019-01-25 10:47:55 -08001044/*
1045 * If the ro.crypto.fde_sector_size system property is set, append the
1046 * parameters to make dm-crypt use the specified crypto sector size and round
1047 * the crypto device size down to a crypto sector boundary.
1048 */
David Andersonb9224732019-05-13 13:02:54 -07001049static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001050 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001051 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001052
Eric Biggersed45ec32019-01-25 10:47:55 -08001053 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1054 unsigned int sector_size;
1055
1056 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1057 (sector_size & (sector_size - 1)) != 0) {
1058 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1059 DM_CRYPT_SECTOR_SIZE, value);
1060 return -1;
1061 }
1062
David Andersonb9224732019-05-13 13:02:54 -07001063 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001064
1065 // With this option, IVs will match the sector numbering, instead
1066 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001067 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001068
1069 // Round the crypto device size down to a crypto sector boundary.
1070 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001071 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001072 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001073}
1074
Paul Crowley5afbc622017-11-27 09:42:17 -08001075static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001076 const char* real_blk_name, std::string* crypto_blk_name,
1077 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001078 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001079
David Andersonb9224732019-05-13 13:02:54 -07001080 // We need two ASCII characters to represent each byte, and need space for
1081 // the '\0' terminator.
1082 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1083 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001084
David Andersonb9224732019-05-13 13:02:54 -07001085 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1086 (const char*)crypt_ftr->crypto_type_name,
1087 master_key_ascii, 0, real_blk_name, 0);
1088 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001089
Paul Crowley5afbc622017-11-27 09:42:17 -08001090 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001091 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001092 }
David Andersonb9224732019-05-13 13:02:54 -07001093 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001094 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001095 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001096 }
David Andersonb9224732019-05-13 13:02:54 -07001097
1098 DmTable table;
1099 table.AddTarget(std::move(target));
1100
1101 int load_count = 1;
1102 while (load_count < TABLE_LOAD_RETRIES) {
1103 if (dm.CreateDevice(name, table)) {
1104 break;
1105 }
1106 load_count++;
1107 }
1108
1109 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001110 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001111 return -1;
1112 }
1113 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001114 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1115 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001116
Paul Crowley81796e92020-02-07 11:27:49 -08001117 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001118 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1119 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001120 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121
Paul Crowleycfe39722018-10-30 15:59:24 -07001122 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001123 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001124 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001125 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001126 }
David Andersonb9224732019-05-13 13:02:54 -07001127 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001128}
1129
David Andersonb9224732019-05-13 13:02:54 -07001130static int delete_crypto_blk_dev(const std::string& name) {
1131 auto& dm = DeviceMapper::Instance();
1132 if (!dm.DeleteDevice(name)) {
1133 SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1134 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001135 }
David Andersonb9224732019-05-13 13:02:54 -07001136 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001137}
1138
Paul Crowley14c8c072018-09-18 13:30:21 -07001139static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1140 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001141 SLOGI("Using pbkdf2 for cryptfs KDF");
1142
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001143 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001144 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1145 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001146}
1147
Paul Crowley14c8c072018-09-18 13:30:21 -07001148static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001149 SLOGI("Using scrypt for cryptfs KDF");
1150
Paul Crowley14c8c072018-09-18 13:30:21 -07001151 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001152
1153 int N = 1 << ftr->N_factor;
1154 int r = 1 << ftr->r_factor;
1155 int p = 1 << ftr->p_factor;
1156
1157 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001158 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001159 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001160
Paul Crowley14c8c072018-09-18 13:30:21 -07001161 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001162}
1163
Paul Crowley14c8c072018-09-18 13:30:21 -07001164static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1165 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001166 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1167
1168 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001169 size_t signature_size;
1170 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001171 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001172
1173 int N = 1 << ftr->N_factor;
1174 int r = 1 << ftr->r_factor;
1175 int p = 1 << ftr->p_factor;
1176
Paul Crowley14c8c072018-09-18 13:30:21 -07001177 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001178 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001179
1180 if (rc) {
1181 SLOGE("scrypt failed");
1182 return -1;
1183 }
1184
Paul Crowley14c8c072018-09-18 13:30:21 -07001185 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001186 SLOGE("Signing failed");
1187 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001188 }
1189
Paul Crowley14c8c072018-09-18 13:30:21 -07001190 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1191 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001192 free(signature);
1193
1194 if (rc) {
1195 SLOGE("scrypt failed");
1196 return -1;
1197 }
1198
1199 return 0;
1200}
1201
Paul Crowley14c8c072018-09-18 13:30:21 -07001202static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1203 const unsigned char* decrypted_master_key,
1204 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1205 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001206 EVP_CIPHER_CTX e_ctx;
1207 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001208 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001209
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001210 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001211 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001212
1213 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001214 case KDF_SCRYPT_KEYMASTER:
1215 if (keymaster_create_key(crypt_ftr)) {
1216 SLOGE("keymaster_create_key failed");
1217 return -1;
1218 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001219
Paul Crowley14c8c072018-09-18 13:30:21 -07001220 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1221 SLOGE("scrypt failed");
1222 return -1;
1223 }
1224 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001225
Paul Crowley14c8c072018-09-18 13:30:21 -07001226 case KDF_SCRYPT:
1227 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1228 SLOGE("scrypt failed");
1229 return -1;
1230 }
1231 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001232
Paul Crowley14c8c072018-09-18 13:30:21 -07001233 default:
1234 SLOGE("Invalid kdf_type");
1235 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001236 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001237
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001238 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001239 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001240 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1241 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242 SLOGE("EVP_EncryptInit failed\n");
1243 return -1;
1244 }
1245 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001246
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001247 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001248 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1249 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250 SLOGE("EVP_EncryptUpdate failed\n");
1251 return -1;
1252 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001253 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001254 SLOGE("EVP_EncryptFinal failed\n");
1255 return -1;
1256 }
1257
Greg Kaiser59ad0182018-02-16 13:01:36 -08001258 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1260 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001261 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001262
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001263 /* Store the scrypt of the intermediate key, so we can validate if it's a
1264 password error or mount error when things go wrong.
1265 Note there's no need to check for errors, since if this is incorrect, we
1266 simply won't wipe userdata, which is the correct default behavior
1267 */
1268 int N = 1 << crypt_ftr->N_factor;
1269 int r = 1 << crypt_ftr->r_factor;
1270 int p = 1 << crypt_ftr->p_factor;
1271
Paul Crowley14c8c072018-09-18 13:30:21 -07001272 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1273 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001274 sizeof(crypt_ftr->scrypted_intermediate_key));
1275
1276 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001277 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001278 }
1279
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001280 EVP_CIPHER_CTX_cleanup(&e_ctx);
1281
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001282 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001283}
1284
Paul Crowley14c8c072018-09-18 13:30:21 -07001285static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1286 const unsigned char* encrypted_master_key, size_t keysize,
1287 unsigned char* decrypted_master_key, kdf_func kdf,
1288 void* kdf_params, unsigned char** intermediate_key,
1289 size_t* intermediate_key_size) {
1290 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1291 EVP_CIPHER_CTX d_ctx;
1292 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001293
Paul Crowley14c8c072018-09-18 13:30:21 -07001294 /* Turn the password into an intermediate key and IV that can decrypt the
1295 master key */
1296 if (kdf(passwd, salt, ikey, kdf_params)) {
1297 SLOGE("kdf failed");
1298 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001299 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001300
Paul Crowley14c8c072018-09-18 13:30:21 -07001301 /* Initialize the decryption engine */
1302 EVP_CIPHER_CTX_init(&d_ctx);
1303 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1304 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1305 return -1;
1306 }
1307 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1308 /* Decrypt the master key */
1309 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1310 keysize)) {
1311 return -1;
1312 }
1313 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1314 return -1;
1315 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001316
Paul Crowley14c8c072018-09-18 13:30:21 -07001317 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1318 return -1;
1319 }
1320
1321 /* Copy intermediate key if needed by params */
1322 if (intermediate_key && intermediate_key_size) {
1323 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1324 if (*intermediate_key) {
1325 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1326 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1327 }
1328 }
1329
1330 EVP_CIPHER_CTX_cleanup(&d_ctx);
1331
1332 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001333}
1334
Paul Crowley14c8c072018-09-18 13:30:21 -07001335static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001336 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001337 *kdf = scrypt_keymaster;
1338 *kdf_params = ftr;
1339 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001340 *kdf = scrypt;
1341 *kdf_params = ftr;
1342 } else {
1343 *kdf = pbkdf2;
1344 *kdf_params = NULL;
1345 }
1346}
1347
Paul Crowley14c8c072018-09-18 13:30:21 -07001348static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1349 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1350 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001351 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001352 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001353 int ret;
1354
1355 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001356 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1357 decrypted_master_key, kdf, kdf_params, intermediate_key,
1358 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001359 if (ret != 0) {
1360 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001361 }
1362
1363 return ret;
1364}
1365
Paul Crowley14c8c072018-09-18 13:30:21 -07001366static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1367 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001368 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001369
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001370 /* Get some random bits for a key and salt */
1371 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1372 return -1;
1373 }
1374 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1375 return -1;
1376 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001377
1378 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001379 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001380}
1381
Paul Crowley73be12d2020-02-03 12:22:03 -08001382static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001383 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001384#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001385
1386 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001387 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001388 if (umount(mountpoint) == 0) {
1389 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001390 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001391
1392 if (errno == EINVAL) {
1393 /* EINVAL is returned if the directory is not a mountpoint,
1394 * i.e. there is no filesystem mounted there. So just get out.
1395 */
1396 break;
1397 }
1398
1399 err = errno;
1400
1401 /* If allowed, be increasingly aggressive before the last two retries */
1402 if (kill) {
1403 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1404 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001405 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001406 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1407 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001408 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001409 }
1410 }
1411
1412 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413 }
1414
1415 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001416 SLOGD("unmounting %s succeeded\n", mountpoint);
1417 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001419 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1420 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1421 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001422 }
1423
1424 return rc;
1425}
1426
Paul Crowley14c8c072018-09-18 13:30:21 -07001427static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001428 // NOTE: post_fs_data results in init calling back around to vold, so all
1429 // callers to this method must be async
1430
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001431 /* Do the prep of the /data filesystem */
1432 property_set("vold.post_fs_data_done", "0");
1433 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001434 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001435
Ken Sumrallc5872692013-05-14 15:26:31 -07001436 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001437 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001438 /* We timed out to prep /data in time. Continue wait. */
1439 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001440 }
Wei Wang42e38102017-06-07 10:46:12 -07001441 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001442}
1443
Paul Crowley14c8c072018-09-18 13:30:21 -07001444static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001445 // Mark the footer as bad
1446 struct crypt_mnt_ftr crypt_ftr;
1447 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1448 SLOGE("Failed to get crypto footer - panic");
1449 return;
1450 }
1451
1452 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1453 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1454 SLOGE("Failed to set crypto footer - panic");
1455 return;
1456 }
1457}
1458
Paul Crowley14c8c072018-09-18 13:30:21 -07001459static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001460 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001461 SLOGE("Failed to mount tmpfs on data - panic");
1462 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001463 }
1464
1465 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1466 SLOGE("Failed to trigger post fs data - panic");
1467 return;
1468 }
1469
1470 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1471 SLOGE("Failed to trigger restart min framework - panic");
1472 return;
1473 }
1474}
1475
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001476/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001477static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001478 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001479 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001480 static int restart_successful = 0;
1481
1482 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001483 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001484 SLOGE("Encrypted filesystem not validated, aborting");
1485 return -1;
1486 }
1487
1488 if (restart_successful) {
1489 SLOGE("System already restarted with encrypted disk, aborting");
1490 return -1;
1491 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001492
Paul Lawrencef4faa572014-01-29 13:31:03 -08001493 if (restart_main) {
1494 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001495 * start all services in one of these classes: core, early_hal, hal,
1496 * main and late_start. To get to the minimal UI for PIN entry, we
1497 * need to start core, early_hal, hal and main. When we want to
1498 * shutdown the framework again, we need to stop most of the services in
1499 * these classes, but only those services that were started after
1500 * /data was mounted. This excludes critical services like vold and
1501 * ueventd, which need to keep running. We could possible stop
1502 * even fewer services, but because we want services to pick up APEX
1503 * libraries from the real /data, restarting is better, as it makes
1504 * these devices consistent with FBE devices and lets them use the
1505 * most recent code.
1506 *
1507 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001508 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001509 * We then restart the class core, hal, main, and also the class
1510 * late_start.
1511 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001512 * At the moment, I've only put a few things in late_start that I know
1513 * are not needed to bring up the framework, and that also cause problems
1514 * with unmounting the tmpfs /data, but I hope to add add more services
1515 * to the late_start class as we optimize this to decrease the delay
1516 * till the user is asked for the password to the filesystem.
1517 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001518
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001519 /* The init files are setup to stop the right set of services when
1520 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001521 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001522 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001523 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001524
Paul Lawrencef4faa572014-01-29 13:31:03 -08001525 /* Ugh, shutting down the framework is not synchronous, so until it
1526 * can be fixed, this horrible hack will wait a moment for it all to
1527 * shut down before proceeding. Without it, some devices cannot
1528 * restart the graphics services.
1529 */
1530 sleep(2);
1531 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001532
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001533 /* Now that the framework is shutdown, we should be able to umount()
1534 * the tmpfs filesystem, and mount the real one.
1535 */
1536
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001537 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1538 if (strlen(crypto_blkdev) == 0) {
1539 SLOGE("fs_crypto_blkdev not set\n");
1540 return -1;
1541 }
1542
Paul Crowley14c8c072018-09-18 13:30:21 -07001543 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001544 /* If ro.crypto.readonly is set to 1, mount the decrypted
1545 * filesystem readonly. This is used when /data is mounted by
1546 * recovery mode.
1547 */
1548 char ro_prop[PROPERTY_VALUE_MAX];
1549 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001550 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001551 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1552 if (entry != nullptr) {
1553 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001554 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001555 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001556
Ken Sumralle5032c42012-04-01 23:58:44 -07001557 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001558 int retries = RETRY_MOUNT_ATTEMPTS;
1559 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001560
1561 /*
1562 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1563 * partitions in the fsck domain.
1564 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001565 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001566 SLOGE("Failed to setexeccon");
1567 return -1;
1568 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001569 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001570 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001571 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001572 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1573 /* TODO: invoke something similar to
1574 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1575 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001576 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001577 if (--retries) {
1578 sleep(RETRY_MOUNT_DELAY_SECONDS);
1579 } else {
1580 /* Let's hope that a reboot clears away whatever is keeping
1581 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001582 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001583 }
1584 } else {
1585 SLOGE("Failed to mount decrypted data");
1586 cryptfs_set_corrupt();
1587 cryptfs_trigger_restart_min_framework();
1588 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001589 if (setexeccon(NULL)) {
1590 SLOGE("Failed to setexeccon");
1591 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001592 return -1;
1593 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001594 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001595 if (setexeccon(NULL)) {
1596 SLOGE("Failed to setexeccon");
1597 return -1;
1598 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001599
Ken Sumralle5032c42012-04-01 23:58:44 -07001600 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001601 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001602 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001603
1604 /* startup service classes main and late_start */
1605 property_set("vold.decrypt", "trigger_restart_framework");
1606 SLOGD("Just triggered restart_framework\n");
1607
1608 /* Give it a few moments to get started */
1609 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610 }
1611
Ken Sumrall0cc16632011-01-18 20:32:26 -08001612 if (rc == 0) {
1613 restart_successful = 1;
1614 }
1615
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616 return rc;
1617}
1618
Paul Crowley14c8c072018-09-18 13:30:21 -07001619int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001620 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001621 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001622 SLOGE("cryptfs_restart not valid for file encryption:");
1623 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001624 }
1625
Paul Lawrencef4faa572014-01-29 13:31:03 -08001626 /* Call internal implementation forcing a restart of main service group */
1627 return cryptfs_restart_internal(1);
1628}
1629
Paul Crowley14c8c072018-09-18 13:30:21 -07001630static int do_crypto_complete(const char* mount_point) {
1631 struct crypt_mnt_ftr crypt_ftr;
1632 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001633
Paul Crowley14c8c072018-09-18 13:30:21 -07001634 property_get("ro.crypto.state", encrypted_state, "");
1635 if (strcmp(encrypted_state, "encrypted")) {
1636 SLOGE("not running with encryption, aborting");
1637 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001638 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001639
Paul Crowley14c8c072018-09-18 13:30:21 -07001640 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001641 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001642 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1643 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001644
Paul Crowley14c8c072018-09-18 13:30:21 -07001645 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001646 std::string key_loc;
1647 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001648
Paul Crowley14c8c072018-09-18 13:30:21 -07001649 /*
1650 * Only report this error if key_loc is a file and it exists.
1651 * If the device was never encrypted, and /data is not mountable for
1652 * some reason, returning 1 should prevent the UI from presenting the
1653 * a "enter password" screen, or worse, a "press button to wipe the
1654 * device" screen.
1655 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001656 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001657 SLOGE("master key file does not exist, aborting");
1658 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1659 } else {
1660 SLOGE("Error getting crypt footer and key\n");
1661 return CRYPTO_COMPLETE_BAD_METADATA;
1662 }
1663 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001664
Paul Crowley14c8c072018-09-18 13:30:21 -07001665 // Test for possible error flags
1666 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1667 SLOGE("Encryption process is partway completed\n");
1668 return CRYPTO_COMPLETE_PARTIAL;
1669 }
1670
1671 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1672 SLOGE("Encryption process was interrupted but cannot continue\n");
1673 return CRYPTO_COMPLETE_INCONSISTENT;
1674 }
1675
1676 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1677 SLOGE("Encryption is successful but data is corrupt\n");
1678 return CRYPTO_COMPLETE_CORRUPT;
1679 }
1680
1681 /* We passed the test! We shall diminish, and return to the west */
1682 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001683}
1684
Paul Crowley14c8c072018-09-18 13:30:21 -07001685static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1686 const char* mount_point, const char* label) {
1687 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001688 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001689 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001690 char tmp_mount_point[64];
1691 unsigned int orig_failed_decrypt_count;
1692 int rc;
1693 int use_keymaster = 0;
1694 int upgrade = 0;
1695 unsigned char* intermediate_key = 0;
1696 size_t intermediate_key_size = 0;
1697 int N = 1 << crypt_ftr->N_factor;
1698 int r = 1 << crypt_ftr->r_factor;
1699 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001700
Paul Crowley14c8c072018-09-18 13:30:21 -07001701 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1702 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001703
Paul Crowley14c8c072018-09-18 13:30:21 -07001704 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1705 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1706 &intermediate_key_size)) {
1707 SLOGE("Failed to decrypt master key\n");
1708 rc = -1;
1709 goto errout;
1710 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001711 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001712
Tom Cherry4c5bde22019-01-29 14:34:01 -08001713 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001714
Paul Crowley14c8c072018-09-18 13:30:21 -07001715 // Create crypto block device - all (non fatal) code paths
1716 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001717 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001718 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001719 SLOGE("Error creating decrypted block device\n");
1720 rc = -1;
1721 goto errout;
1722 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001723
Paul Crowley14c8c072018-09-18 13:30:21 -07001724 /* Work out if the problem is the password or the data */
1725 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001726
Paul Crowley14c8c072018-09-18 13:30:21 -07001727 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1728 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1729 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001730
Paul Crowley14c8c072018-09-18 13:30:21 -07001731 // Does the key match the crypto footer?
1732 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1733 sizeof(scrypted_intermediate_key)) == 0) {
1734 SLOGI("Password matches");
1735 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001736 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001737 /* Try mounting the file system anyway, just in case the problem's with
1738 * the footer, not the key. */
1739 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1740 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001741 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1742 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001743 SLOGE("Error temp mounting decrypted block device\n");
1744 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001745
Paul Crowley14c8c072018-09-18 13:30:21 -07001746 rc = ++crypt_ftr->failed_decrypt_count;
1747 put_crypt_ftr_and_key(crypt_ftr);
1748 } else {
1749 /* Success! */
1750 SLOGI("Password did not match but decrypted drive mounted - continue");
1751 umount(tmp_mount_point);
1752 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001753 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001754 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001755
Paul Crowley14c8c072018-09-18 13:30:21 -07001756 if (rc == 0) {
1757 crypt_ftr->failed_decrypt_count = 0;
1758 if (orig_failed_decrypt_count != 0) {
1759 put_crypt_ftr_and_key(crypt_ftr);
1760 }
1761
1762 /* Save the name of the crypto block device
1763 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001764 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001765
1766 /* Also save a the master key so we can reencrypted the key
1767 * the key when we want to change the password on it. */
1768 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1769 saved_mount_point = strdup(mount_point);
1770 master_key_saved = 1;
1771 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1772 rc = 0;
1773
1774 // Upgrade if we're not using the latest KDF.
1775 use_keymaster = keymaster_check_compatibility();
1776 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1777 // Don't allow downgrade
1778 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1779 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1780 upgrade = 1;
1781 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1782 crypt_ftr->kdf_type = KDF_SCRYPT;
1783 upgrade = 1;
1784 }
1785
1786 if (upgrade) {
1787 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1788 crypt_ftr->master_key, crypt_ftr);
1789 if (!rc) {
1790 rc = put_crypt_ftr_and_key(crypt_ftr);
1791 }
1792 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1793
1794 // Do not fail even if upgrade failed - machine is bootable
1795 // Note that if this code is ever hit, there is a *serious* problem
1796 // since KDFs should never fail. You *must* fix the kdf before
1797 // proceeding!
1798 if (rc) {
1799 SLOGW(
1800 "Upgrade failed with error %d,"
1801 " but continuing with previous state",
1802 rc);
1803 rc = 0;
1804 }
1805 }
1806 }
1807
1808errout:
1809 if (intermediate_key) {
1810 memset(intermediate_key, 0, intermediate_key_size);
1811 free(intermediate_key);
1812 }
1813 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001814}
1815
Ken Sumrall29d8da82011-05-18 17:20:07 -07001816/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001817 * Called by vold when it's asked to mount an encrypted external
1818 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001819 * as any metadata is been stored in a separate, small partition. We
1820 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001821 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001822int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001823 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001824 auto crypto_type = get_crypto_type();
1825 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001826 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001827 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001828 return -1;
1829 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001830 uint64_t nr_sec = 0;
1831 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001832 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001833 return -1;
1834 }
1835
Jeff Sharkey9c484982015-03-31 10:35:33 -07001836 struct crypt_mnt_ftr ext_crypt_ftr;
1837 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1838 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001839 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1840 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001841 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001842 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001843 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001844 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1845 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001846
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001847 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1848 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001849}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001850
Paul Crowley14c8c072018-09-18 13:30:21 -07001851int cryptfs_crypto_complete(void) {
1852 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001853}
1854
Paul Crowley14c8c072018-09-18 13:30:21 -07001855int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001856 char encrypted_state[PROPERTY_VALUE_MAX];
1857 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001858 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1859 SLOGE(
1860 "encrypted fs already validated or not running with encryption,"
1861 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001862 return -1;
1863 }
1864
1865 if (get_crypt_ftr_and_key(crypt_ftr)) {
1866 SLOGE("Error getting crypt footer and key");
1867 return -1;
1868 }
1869
1870 return 0;
1871}
1872
Paul Crowley14c8c072018-09-18 13:30:21 -07001873int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001874 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001875 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001876 SLOGE("cryptfs_check_passwd not valid for file encryption");
1877 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001878 }
1879
Paul Lawrencef4faa572014-01-29 13:31:03 -08001880 struct crypt_mnt_ftr crypt_ftr;
1881 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001882
Paul Lawrencef4faa572014-01-29 13:31:03 -08001883 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001884 if (rc) {
1885 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001886 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001887 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001888
Paul Crowley14c8c072018-09-18 13:30:21 -07001889 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001890 if (rc) {
1891 SLOGE("Password did not match");
1892 return rc;
1893 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001894
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001895 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1896 // Here we have a default actual password but a real password
1897 // we must test against the scrypted value
1898 // First, we must delete the crypto block device that
1899 // test_mount_encrypted_fs leaves behind as a side effect
1900 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001901 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1902 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001903 if (rc) {
1904 SLOGE("Default password did not match on reboot encryption");
1905 return rc;
1906 }
1907
1908 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1909 put_crypt_ftr_and_key(&crypt_ftr);
1910 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1911 if (rc) {
1912 SLOGE("Could not change password on reboot encryption");
1913 return rc;
1914 }
1915 }
1916
1917 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001918 cryptfs_clear_password();
1919 password = strdup(passwd);
1920 struct timespec now;
1921 clock_gettime(CLOCK_BOOTTIME, &now);
1922 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001923 }
1924
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001925 return rc;
1926}
1927
Paul Crowley14c8c072018-09-18 13:30:21 -07001928int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001929 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001930 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001931 char encrypted_state[PROPERTY_VALUE_MAX];
1932 int rc;
1933
1934 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001935 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001936 SLOGE("device not encrypted, aborting");
1937 return -2;
1938 }
1939
1940 if (!master_key_saved) {
1941 SLOGE("encrypted fs not yet mounted, aborting");
1942 return -1;
1943 }
1944
1945 if (!saved_mount_point) {
1946 SLOGE("encrypted fs failed to save mount point, aborting");
1947 return -1;
1948 }
1949
Ken Sumrall160b4d62013-04-22 12:15:39 -07001950 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001951 SLOGE("Error getting crypt footer and key\n");
1952 return -1;
1953 }
1954
1955 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1956 /* If the device has no password, then just say the password is valid */
1957 rc = 0;
1958 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001959 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001960 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1961 /* They match, the password is correct */
1962 rc = 0;
1963 } else {
1964 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1965 sleep(1);
1966 rc = 1;
1967 }
1968 }
1969
1970 return rc;
1971}
1972
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001973/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08001974 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001975 * Presumably, at a minimum, the caller will update the
1976 * filesystem size and crypto_type_name after calling this function.
1977 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001978static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001979 off64_t off;
1980
1981 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001982 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001983 ftr->major_version = CURRENT_MAJOR_VERSION;
1984 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001985 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08001986 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001987
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001988 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001989 case 1:
1990 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1991 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001992
Paul Crowley14c8c072018-09-18 13:30:21 -07001993 case 0:
1994 ftr->kdf_type = KDF_SCRYPT;
1995 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001996
Paul Crowley14c8c072018-09-18 13:30:21 -07001997 default:
1998 SLOGE("keymaster_check_compatibility failed");
1999 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002000 }
2001
Kenny Rootc4c70f12013-06-14 12:11:38 -07002002 get_device_scrypt_params(ftr);
2003
Ken Sumrall160b4d62013-04-22 12:15:39 -07002004 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2005 if (get_crypt_ftr_info(NULL, &off) == 0) {
2006 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002007 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002008 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002009
2010 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002011}
2012
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002013#define FRAMEWORK_BOOT_WAIT 60
2014
Paul Crowley14c8c072018-09-18 13:30:21 -07002015static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2016 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002017 if (fd == -1) {
2018 SLOGE("Error opening file %s", filename);
2019 return -1;
2020 }
2021
2022 char block[CRYPT_INPLACE_BUFSIZE];
2023 memset(block, 0, sizeof(block));
2024 if (unix_read(fd, block, sizeof(block)) < 0) {
2025 SLOGE("Error reading file %s", filename);
2026 close(fd);
2027 return -1;
2028 }
2029
2030 close(fd);
2031
2032 SHA256_CTX c;
2033 SHA256_Init(&c);
2034 SHA256_Update(&c, block, sizeof(block));
2035 SHA256_Final(buf, &c);
2036
2037 return 0;
2038}
2039
Paul Crowley81796e92020-02-07 11:27:49 -08002040static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2041 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002042 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002043 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002044
Paul Lawrence87999172014-02-20 12:21:31 -08002045 /* The size of the userdata partition, and add in the vold volumes below */
2046 tot_encryption_size = crypt_ftr->fs_size;
2047
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002048 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002049 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002050
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002051 if (rc == ENABLE_INPLACE_ERR_DEV) {
2052 /* Hack for b/17898962 */
2053 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2054 cryptfs_reboot(RebootType::reboot);
2055 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002056
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002057 if (!rc) {
2058 crypt_ftr->encrypted_upto = cur_encryption_done;
2059 }
Paul Lawrence87999172014-02-20 12:21:31 -08002060
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002061 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2062 /* The inplace routine never actually sets the progress to 100% due
2063 * to the round down nature of integer division, so set it here */
2064 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002065 }
2066
2067 return rc;
2068}
2069
Paul Crowleyb64933a2017-10-31 08:25:55 -07002070static int vold_unmountAll(void) {
2071 VolumeManager* vm = VolumeManager::Instance();
2072 return vm->unmountAll();
2073}
2074
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002075int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002076 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002077 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002078 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002079 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002080 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002081 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002082 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002083 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002084 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002085 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002086 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002087 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002088 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002089 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002090
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002091 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002092 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2093 /* An encryption was underway and was interrupted */
2094 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2095 crypt_ftr.encrypted_upto = 0;
2096 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002097
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002098 /* At this point, we are in an inconsistent state. Until we successfully
2099 complete encryption, a reboot will leave us broken. So mark the
2100 encryption failed in case that happens.
2101 On successfully completing encryption, remove this flag */
2102 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002103
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002104 put_crypt_ftr_and_key(&crypt_ftr);
2105 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2106 if (!check_ftr_sha(&crypt_ftr)) {
2107 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2108 put_crypt_ftr_and_key(&crypt_ftr);
2109 goto error_unencrypted;
2110 }
2111
2112 /* Doing a reboot-encryption*/
2113 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2114 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2115 rebootEncryption = true;
2116 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002117 } else {
2118 // We don't want to accidentally reference invalid data.
2119 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002120 }
2121
2122 property_get("ro.crypto.state", encrypted_state, "");
2123 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2124 SLOGE("Device is already running encrypted, aborting");
2125 goto error_unencrypted;
2126 }
2127
Tom Cherry4c5bde22019-01-29 14:34:01 -08002128 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002129
Ken Sumrall3ed82362011-01-28 23:31:16 -08002130 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002131 uint64_t nr_sec;
2132 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002133 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002134 goto error_unencrypted;
2135 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002136
2137 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002138 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002139 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002140 fs_size_sec = get_fs_size(real_blkdev.c_str());
2141 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002142
Paul Lawrence87999172014-02-20 12:21:31 -08002143 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002144
2145 if (fs_size_sec > max_fs_size_sec) {
2146 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2147 goto error_unencrypted;
2148 }
2149 }
2150
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002151 /* Get a wakelock as this may take a while, and we don't want the
2152 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2153 * wants to keep the screen on, it can grab a full wakelock.
2154 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002155 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002156 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002157
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002158 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002159 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002160 */
2161 property_set("vold.decrypt", "trigger_shutdown_framework");
2162 SLOGD("Just asked init to shut down class main\n");
2163
Jeff Sharkey9c484982015-03-31 10:35:33 -07002164 /* Ask vold to unmount all devices that it manages */
2165 if (vold_unmountAll()) {
2166 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002167 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002168
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002169 /* no_ui means we are being called from init, not settings.
2170 Now we always reboot from settings, so !no_ui means reboot
2171 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002172 if (!no_ui) {
2173 /* Try fallback, which is to reboot and try there */
2174 onlyCreateHeader = true;
2175 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2176 if (breadcrumb == 0) {
2177 SLOGE("Failed to create breadcrumb file");
2178 goto error_shutting_down;
2179 }
2180 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002181 }
2182
2183 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002184 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002185 /* Now that /data is unmounted, we need to mount a tmpfs
2186 * /data, set a property saying we're doing inplace encryption,
2187 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002188 */
xzj7e38a3a2018-10-12 10:17:11 +08002189 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002190 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002191 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002192 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002193 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002194 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002195
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002196 /* restart the framework. */
2197 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002198 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002199
Ken Sumrall92736ef2012-10-17 20:57:14 -07002200 /* Ugh, shutting down the framework is not synchronous, so until it
2201 * can be fixed, this horrible hack will wait a moment for it all to
2202 * shut down before proceeding. Without it, some devices cannot
2203 * restart the graphics services.
2204 */
2205 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002206 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002207
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002208 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002209 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002210 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002211 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2212 goto error_shutting_down;
2213 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002214
Tom Cherry4c5bde22019-01-29 14:34:01 -08002215 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002216 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002217 } else {
2218 crypt_ftr.fs_size = nr_sec;
2219 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002220 /* At this point, we are in an inconsistent state. Until we successfully
2221 complete encryption, a reboot will leave us broken. So mark the
2222 encryption failed in case that happens.
2223 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002224 if (onlyCreateHeader) {
2225 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2226 } else {
2227 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2228 }
Paul Lawrence87999172014-02-20 12:21:31 -08002229 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002230 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002231 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002232
Paul Lawrence87999172014-02-20 12:21:31 -08002233 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002234 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2235 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002236 SLOGE("Cannot create encrypted master key\n");
2237 goto error_shutting_down;
2238 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002239
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002240 /* Replace scrypted intermediate key if we are preparing for a reboot */
2241 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002242 unsigned char fake_master_key[MAX_KEY_LEN];
2243 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002244 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002245 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2246 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002247 }
2248
Paul Lawrence87999172014-02-20 12:21:31 -08002249 /* Write the key to the end of the partition */
2250 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002251
Paul Lawrence87999172014-02-20 12:21:31 -08002252 /* If any persistent data has been remembered, save it.
2253 * If none, create a valid empty table and save that.
2254 */
2255 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002256 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2257 if (pdata) {
2258 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2259 persist_data = pdata;
2260 }
Paul Lawrence87999172014-02-20 12:21:31 -08002261 }
2262 if (persist_data) {
2263 save_persistent_data();
2264 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002265 }
2266
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002267 if (onlyCreateHeader) {
2268 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002269 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002270 }
2271
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002272 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002273 /* startup service classes main and late_start */
2274 property_set("vold.decrypt", "trigger_restart_min_framework");
2275 SLOGD("Just triggered restart_min_framework\n");
2276
2277 /* OK, the framework is restarted and will soon be showing a
2278 * progress bar. Time to setup an encrypted mapping, and
2279 * either write a new filesystem, or encrypt in place updating
2280 * the progress bar as we work.
2281 */
2282 }
2283
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002284 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002285 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002286 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002287
Paul Lawrence87999172014-02-20 12:21:31 -08002288 /* If we are continuing, check checksums match */
2289 rc = 0;
2290 if (previously_encrypted_upto) {
2291 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002292 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002293
Paul Crowley14c8c072018-09-18 13:30:21 -07002294 if (!rc &&
2295 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002296 SLOGE("Checksums do not match - trigger wipe");
2297 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002298 }
2299 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002300
Paul Lawrence87999172014-02-20 12:21:31 -08002301 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002302 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002303 previously_encrypted_upto);
2304 }
2305
2306 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002307 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002308 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002309 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002310 SLOGE("Error calculating checksum for continuing encryption");
2311 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002312 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002313 }
2314
2315 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002316 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002317
Paul Crowley14c8c072018-09-18 13:30:21 -07002318 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002319 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002320 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002321
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002322 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002323 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2324 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002325 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002326 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002327
Paul Lawrence6bfed202014-07-28 12:47:22 -07002328 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002329
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002330 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2331 char value[PROPERTY_VALUE_MAX];
2332 property_get("ro.crypto.state", value, "");
2333 if (!strcmp(value, "")) {
2334 /* default encryption - continue first boot sequence */
2335 property_set("ro.crypto.state", "encrypted");
2336 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002337 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002338 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2339 // Bring up cryptkeeper that will check the password and set it
2340 property_set("vold.decrypt", "trigger_shutdown_framework");
2341 sleep(2);
2342 property_set("vold.encrypt_progress", "");
2343 cryptfs_trigger_restart_min_framework();
2344 } else {
2345 cryptfs_check_passwd(DEFAULT_PASSWORD);
2346 cryptfs_restart_internal(1);
2347 }
2348 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002349 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002350 sleep(2); /* Give the UI a chance to show 100% progress */
2351 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002352 }
Paul Lawrence87999172014-02-20 12:21:31 -08002353 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002354 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002355 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002356 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002357 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002358 char value[PROPERTY_VALUE_MAX];
2359
Ken Sumrall319369a2012-06-27 16:30:18 -07002360 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002361 if (!strcmp(value, "1")) {
2362 /* wipe data if encryption failed */
2363 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002364 std::string err;
2365 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002366 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002367 if (!write_bootloader_message(options, &err)) {
2368 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002369 }
Josh Gaofec44372017-08-28 13:22:55 -07002370 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002371 } else {
2372 /* set property to trigger dialog */
2373 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002374 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002375 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002376 }
2377
Ken Sumrall3ed82362011-01-28 23:31:16 -08002378 /* hrm, the encrypt step claims success, but the reboot failed.
2379 * This should not happen.
2380 * Set the property and return. Hope the framework can deal with it.
2381 */
2382 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002383 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002384
2385error_unencrypted:
2386 property_set("vold.encrypt_progress", "error_not_encrypted");
2387 return -1;
2388
2389error_shutting_down:
2390 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2391 * but the framework is stopped and not restarted to show the error, so it's up to
2392 * vold to restart the system.
2393 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002394 SLOGE(
2395 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2396 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002397 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002398
2399 /* shouldn't get here */
2400 property_set("vold.encrypt_progress", "error_shutting_down");
2401 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002402}
2403
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002404int cryptfs_enable(int type, const char* passwd, int no_ui) {
2405 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002406}
2407
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002408int cryptfs_enable_default(int no_ui) {
2409 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002410}
2411
Paul Crowley14c8c072018-09-18 13:30:21 -07002412int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002413 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002414 SLOGE("cryptfs_changepw not valid for file encryption");
2415 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002416 }
2417
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002418 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002419 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002420
2421 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002422 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002423 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002424 return -1;
2425 }
2426
Paul Lawrencef4faa572014-01-29 13:31:03 -08002427 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2428 SLOGE("Invalid crypt_type %d", crypt_type);
2429 return -1;
2430 }
2431
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002432 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002433 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002434 SLOGE("Error getting crypt footer and key");
2435 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002436 }
2437
Paul Lawrencef4faa572014-01-29 13:31:03 -08002438 crypt_ftr.crypt_type = crypt_type;
2439
Paul Crowley14c8c072018-09-18 13:30:21 -07002440 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2441 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002442 if (rc) {
2443 SLOGE("Encrypt master key failed: %d", rc);
2444 return -1;
2445 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002446 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002447 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002448
2449 return 0;
2450}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002451
Rubin Xu85c01f92014-10-13 12:49:54 +01002452static unsigned int persist_get_max_entries(int encrypted) {
2453 struct crypt_mnt_ftr crypt_ftr;
2454 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002455
2456 /* If encrypted, use the values from the crypt_ftr, otherwise
2457 * use the values for the current spec.
2458 */
2459 if (encrypted) {
2460 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002461 /* Something is wrong, assume no space for entries */
2462 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002463 }
2464 dsize = crypt_ftr.persist_data_size;
2465 } else {
2466 dsize = CRYPT_PERSIST_DATA_SIZE;
2467 }
2468
Rubin Xuf83cc612018-10-09 16:13:38 +01002469 if (dsize > sizeof(struct crypt_persist_data)) {
2470 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2471 } else {
2472 return 0;
2473 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002474}
2475
Paul Crowley14c8c072018-09-18 13:30:21 -07002476static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002477 unsigned int i;
2478
2479 if (persist_data == NULL) {
2480 return -1;
2481 }
2482 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2483 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2484 /* We found it! */
2485 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2486 return 0;
2487 }
2488 }
2489
2490 return -1;
2491}
2492
Paul Crowley14c8c072018-09-18 13:30:21 -07002493static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002494 unsigned int i;
2495 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002496 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002497
2498 if (persist_data == NULL) {
2499 return -1;
2500 }
2501
Rubin Xu85c01f92014-10-13 12:49:54 +01002502 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002503
2504 num = persist_data->persist_valid_entries;
2505
2506 for (i = 0; i < num; i++) {
2507 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2508 /* We found an existing entry, update it! */
2509 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2510 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2511 return 0;
2512 }
2513 }
2514
2515 /* We didn't find it, add it to the end, if there is room */
2516 if (persist_data->persist_valid_entries < max_persistent_entries) {
2517 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2518 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2519 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2520 persist_data->persist_valid_entries++;
2521 return 0;
2522 }
2523
2524 return -1;
2525}
2526
Rubin Xu85c01f92014-10-13 12:49:54 +01002527/**
2528 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2529 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2530 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002531int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002532 std::string key_ = key;
2533 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002534
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002535 std::string parsed_field;
2536 unsigned parsed_index;
2537
2538 std::string::size_type split = key_.find_last_of('_');
2539 if (split == std::string::npos) {
2540 parsed_field = key_;
2541 parsed_index = 0;
2542 } else {
2543 parsed_field = key_.substr(0, split);
2544 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002545 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002546
2547 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002548}
2549
2550/*
2551 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2552 * remaining entries starting from index will be deleted.
2553 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2554 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2555 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2556 *
2557 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002558static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002559 unsigned int i;
2560 unsigned int j;
2561 unsigned int num;
2562
2563 if (persist_data == NULL) {
2564 return PERSIST_DEL_KEY_ERROR_OTHER;
2565 }
2566
2567 num = persist_data->persist_valid_entries;
2568
Paul Crowley14c8c072018-09-18 13:30:21 -07002569 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002570 // Filter out to-be-deleted entries in place.
2571 for (i = 0; i < num; i++) {
2572 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2573 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2574 j++;
2575 }
2576 }
2577
2578 if (j < num) {
2579 persist_data->persist_valid_entries = j;
2580 // Zeroise the remaining entries
2581 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2582 return PERSIST_DEL_KEY_OK;
2583 } else {
2584 // Did not find an entry matching the given fieldname
2585 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2586 }
2587}
2588
Paul Crowley14c8c072018-09-18 13:30:21 -07002589static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002590 unsigned int i;
2591 unsigned int count;
2592
2593 if (persist_data == NULL) {
2594 return -1;
2595 }
2596
2597 count = 0;
2598 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2599 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2600 count++;
2601 }
2602 }
2603
2604 return count;
2605}
2606
Ken Sumrall160b4d62013-04-22 12:15:39 -07002607/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002608int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002609 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002610 SLOGE("Cannot get field when file encrypted");
2611 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002612 }
2613
Ken Sumrall160b4d62013-04-22 12:15:39 -07002614 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002615 /* CRYPTO_GETFIELD_OK is success,
2616 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2617 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2618 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002619 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002620 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2621 int i;
2622 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002623
2624 if (persist_data == NULL) {
2625 load_persistent_data();
2626 if (persist_data == NULL) {
2627 SLOGE("Getfield error, cannot load persistent data");
2628 goto out;
2629 }
2630 }
2631
Rubin Xu85c01f92014-10-13 12:49:54 +01002632 // Read value from persistent entries. If the original value is split into multiple entries,
2633 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002634 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002635 // 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 -07002636 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002637 // value too small
2638 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2639 goto out;
2640 }
2641 rc = CRYPTO_GETFIELD_OK;
2642
2643 for (i = 1; /* break explicitly */; i++) {
2644 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002645 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002646 // If the fieldname is very long, we stop as soon as it begins to overflow the
2647 // maximum field length. At this point we have in fact fully read out the original
2648 // value because cryptfs_setfield would not allow fields with longer names to be
2649 // written in the first place.
2650 break;
2651 }
2652 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002653 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2654 // value too small.
2655 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2656 goto out;
2657 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002658 } else {
2659 // Exhaust all entries.
2660 break;
2661 }
2662 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002663 } else {
2664 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002665 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002666 }
2667
2668out:
2669 return rc;
2670}
2671
2672/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002673int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002674 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002675 SLOGE("Cannot set field when file encrypted");
2676 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002677 }
2678
Ken Sumrall160b4d62013-04-22 12:15:39 -07002679 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002680 /* 0 is success, negative values are error */
2681 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002682 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002683 unsigned int field_id;
2684 char temp_field[PROPERTY_KEY_MAX];
2685 unsigned int num_entries;
2686 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002687
2688 if (persist_data == NULL) {
2689 load_persistent_data();
2690 if (persist_data == NULL) {
2691 SLOGE("Setfield error, cannot load persistent data");
2692 goto out;
2693 }
2694 }
2695
2696 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002697 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002698 encrypted = 1;
2699 }
2700
Rubin Xu85c01f92014-10-13 12:49:54 +01002701 // Compute the number of entries required to store value, each entry can store up to
2702 // (PROPERTY_VALUE_MAX - 1) chars
2703 if (strlen(value) == 0) {
2704 // Empty value also needs one entry to store.
2705 num_entries = 1;
2706 } else {
2707 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2708 }
2709
2710 max_keylen = strlen(fieldname);
2711 if (num_entries > 1) {
2712 // Need an extra "_%d" suffix.
2713 max_keylen += 1 + log10(num_entries);
2714 }
2715 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2716 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002717 goto out;
2718 }
2719
Rubin Xu85c01f92014-10-13 12:49:54 +01002720 // Make sure we have enough space to write the new value
2721 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2722 persist_get_max_entries(encrypted)) {
2723 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2724 goto out;
2725 }
2726
2727 // Now that we know persist_data has enough space for value, let's delete the old field first
2728 // to make up space.
2729 persist_del_keys(fieldname, 0);
2730
2731 if (persist_set_key(fieldname, value, encrypted)) {
2732 // fail to set key, should not happen as we have already checked the available space
2733 SLOGE("persist_set_key() error during setfield()");
2734 goto out;
2735 }
2736
2737 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002738 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002739
2740 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2741 // fail to set key, should not happen as we have already checked the available space.
2742 SLOGE("persist_set_key() error during setfield()");
2743 goto out;
2744 }
2745 }
2746
Ken Sumrall160b4d62013-04-22 12:15:39 -07002747 /* If we are running encrypted, save the persistent data now */
2748 if (encrypted) {
2749 if (save_persistent_data()) {
2750 SLOGE("Setfield error, cannot save persistent data");
2751 goto out;
2752 }
2753 }
2754
Rubin Xu85c01f92014-10-13 12:49:54 +01002755 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002756
2757out:
2758 return rc;
2759}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002760
2761/* Checks userdata. Attempt to mount the volume if default-
2762 * encrypted.
2763 * On success trigger next init phase and return 0.
2764 * Currently do not handle failure - see TODO below.
2765 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002766int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002767 int crypt_type = cryptfs_get_password_type();
2768 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2769 SLOGE("Bad crypt type - error");
2770 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002771 SLOGD(
2772 "Password is not default - "
2773 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002774 property_set("vold.decrypt", "trigger_restart_min_framework");
2775 return 0;
2776 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2777 SLOGD("Password is default - restarting filesystem");
2778 cryptfs_restart_internal(0);
2779 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002780 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002781 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002782 }
2783
Paul Lawrence6bfed202014-07-28 12:47:22 -07002784 /** Corrupt. Allow us to boot into framework, which will detect bad
2785 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002786 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002787 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002788 return 0;
2789}
2790
2791/* Returns type of the password, default, pattern, pin or password.
2792 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002793int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002794 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002795 SLOGE("cryptfs_get_password_type not valid for file encryption");
2796 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002797 }
2798
Paul Lawrencef4faa572014-01-29 13:31:03 -08002799 struct crypt_mnt_ftr crypt_ftr;
2800
2801 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2802 SLOGE("Error getting crypt footer and key\n");
2803 return -1;
2804 }
2805
Paul Lawrence6bfed202014-07-28 12:47:22 -07002806 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2807 return -1;
2808 }
2809
Paul Lawrencef4faa572014-01-29 13:31:03 -08002810 return crypt_ftr.crypt_type;
2811}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002812
Paul Crowley14c8c072018-09-18 13:30:21 -07002813const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002814 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002815 SLOGE("cryptfs_get_password not valid for file encryption");
2816 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002817 }
2818
Paul Lawrence399317e2014-03-10 13:20:50 -07002819 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002820 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002821 if (now.tv_sec < password_expiry_time) {
2822 return password;
2823 } else {
2824 cryptfs_clear_password();
2825 return 0;
2826 }
2827}
2828
Paul Crowley14c8c072018-09-18 13:30:21 -07002829void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002830 if (password) {
2831 size_t len = strlen(password);
2832 memset(password, 0, len);
2833 free(password);
2834 password = 0;
2835 password_expiry_time = 0;
2836 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002837}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002838
Paul Crowley14c8c072018-09-18 13:30:21 -07002839int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002840 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2841 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002842}