blob: 530d78e2c402bb62acf1e75780055bce136774f1 [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
Martijn Coenen26ad7b32020-02-13 16:20:52 +010068#include <chrono>
69#include <thread>
70
Wei Wang4375f1b2017-02-24 17:43:01 -080071extern "C" {
72#include <crypto_scrypt.h>
73}
Mark Salyzyn3e971272014-01-21 13:27:04 -080074
Eric Biggersed45ec32019-01-25 10:47:55 -080075using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080076using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080077using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080078using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080079using android::vold::KeyBuffer;
David Andersonb9224732019-05-13 13:02:54 -070080using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070081using namespace std::chrono_literals;
82
Paul Crowley73be12d2020-02-03 12:22:03 -080083/* The current cryptfs version */
84#define CURRENT_MAJOR_VERSION 1
85#define CURRENT_MINOR_VERSION 3
86
87#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
88#define CRYPT_PERSIST_DATA_SIZE 0x1000
89
90#define MAX_CRYPTO_TYPE_NAME_LEN 64
91
92#define MAX_KEY_LEN 48
93#define SALT_LEN 16
94#define SCRYPT_LEN 32
95
96/* definitions of flags in the structure below */
97#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
98#define CRYPT_ENCRYPTION_IN_PROGRESS \
99 0x2 /* Encryption partially completed, \
100 encrypted_upto valid*/
101#define CRYPT_INCONSISTENT_STATE \
102 0x4 /* Set when starting encryption, clear when \
103 exit cleanly, either through success or \
104 correctly marked partial encryption */
105#define CRYPT_DATA_CORRUPT \
106 0x8 /* Set when encryption is fine, but the \
107 underlying volume is corrupt */
108#define CRYPT_FORCE_ENCRYPTION \
109 0x10 /* Set when it is time to encrypt this \
110 volume on boot. Everything in this \
111 structure is set up correctly as \
112 though device is encrypted except \
113 that the master key is encrypted with the \
114 default password. */
115#define CRYPT_FORCE_COMPLETE \
116 0x20 /* Set when the above encryption cycle is \
117 complete. On next cryptkeeper entry, match \
118 the password. If it matches fix the master \
119 key and remove this flag. */
120
121/* Allowed values for type in the structure below */
122#define CRYPT_TYPE_PASSWORD \
123 0 /* master_key is encrypted with a password \
124 * Must be zero to be compatible with pre-L \
125 * devices where type is always password.*/
126#define CRYPT_TYPE_DEFAULT \
127 1 /* master_key is encrypted with default \
128 * password */
129#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
130#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
131#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
132
133#define CRYPT_MNT_MAGIC 0xD0B5B1C4
134#define PERSIST_DATA_MAGIC 0xE950CD44
135
136/* Key Derivation Function algorithms */
137#define KDF_PBKDF2 1
138#define KDF_SCRYPT 2
139/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
140#define KDF_SCRYPT_KEYMASTER 5
141
142/* Maximum allowed keymaster blob size. */
143#define KEYMASTER_BLOB_SIZE 2048
144
145/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
146#define __le8 unsigned char
147
148#if !defined(SHA256_DIGEST_LENGTH)
149#define SHA256_DIGEST_LENGTH 32
150#endif
151
152/* This structure starts 16,384 bytes before the end of a hardware
153 * partition that is encrypted, or in a separate partition. It's location
154 * is specified by a property set in init.<device>.rc.
155 * The structure allocates 48 bytes for a key, but the real key size is
156 * specified in the struct. Currently, the code is hardcoded to use 128
157 * bit keys.
158 * The fields after salt are only valid in rev 1.1 and later stuctures.
159 * Obviously, the filesystem does not include the last 16 kbytes
160 * of the partition if the crypt_mnt_ftr lives at the end of the
161 * partition.
162 */
163
164struct crypt_mnt_ftr {
165 __le32 magic; /* See above */
166 __le16 major_version;
167 __le16 minor_version;
168 __le32 ftr_size; /* in bytes, not including key following */
169 __le32 flags; /* See above */
170 __le32 keysize; /* in bytes */
171 __le32 crypt_type; /* how master_key is encrypted. Must be a
172 * CRYPT_TYPE_XXX value */
173 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
174 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
175 mount, set to 0 on successful mount */
176 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
177 needed to decrypt this
178 partition, null terminated */
179 __le32 spare2; /* ignored */
180 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
181 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
182 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
183 * on device with that info, either the footer of the
184 * real_blkdevice or the metadata partition. */
185
186 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
187 * persistent data table*/
188
189 __le8 kdf_type; /* The key derivation function used. */
190
191 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
192 __le8 N_factor; /* (1 << N) */
193 __le8 r_factor; /* (1 << r) */
194 __le8 p_factor; /* (1 << p) */
195 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
196 we have to stop (e.g. power low) this is the last
197 encrypted 512 byte sector.*/
198 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
199 set, hash of first block, used
200 to validate before continuing*/
201
202 /* key_master key, used to sign the derived key which is then used to generate
203 * the intermediate key
204 * This key should be used for no other purposes! We use this key to sign unpadded
205 * data, which is acceptable but only if the key is not reused elsewhere. */
206 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
207 __le32 keymaster_blob_size;
208
209 /* Store scrypt of salted intermediate key. When decryption fails, we can
210 check if this matches, and if it does, we know that the problem is with the
211 drive, and there is no point in asking the user for more passwords.
212
213 Note that if any part of this structure is corrupt, this will not match and
214 we will continue to believe the user entered the wrong password. In that
215 case the only solution is for the user to enter a password enough times to
216 force a wipe.
217
218 Note also that there is no need to worry about migration. If this data is
219 wrong, we simply won't recognise a right password, and will continue to
220 prompt. On the first password change, this value will be populated and
221 then we will be OK.
222 */
223 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
224
225 /* sha of this structure with this element set to zero
226 Used when encrypting on reboot to validate structure before doing something
227 fatal
228 */
229 unsigned char sha256[SHA256_DIGEST_LENGTH];
230};
231
232/* Persistant data that should be available before decryption.
233 * Things like airplane mode, locale and timezone are kept
234 * here and can be retrieved by the CryptKeeper UI to properly
235 * configure the phone before asking for the password
236 * This is only valid if the major and minor version above
237 * is set to 1.1 or higher.
238 *
239 * This is a 4K structure. There are 2 copies, and the code alternates
240 * writing one and then clearing the previous one. The reading
241 * code reads the first valid copy it finds, based on the magic number.
242 * The absolute offset to the first of the two copies is kept in rev 1.1
243 * and higher crypt_mnt_ftr structures.
244 */
245struct crypt_persist_entry {
246 char key[PROPERTY_KEY_MAX];
247 char val[PROPERTY_VALUE_MAX];
248};
249
250/* Should be exactly 4K in size */
251struct crypt_persist_data {
252 __le32 persist_magic;
253 __le32 persist_valid_entries;
254 __le32 persist_spare[30];
255 struct crypt_persist_entry persist_entry[0];
256};
257
258static int wait_and_unmount(const char* mountpoint, bool kill);
259
260typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
261 void* params);
262
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800263#define UNUSED __attribute__((unused))
264
Jason parks70a4b3f2011-01-28 10:10:47 -0600265#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800266
267constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
268constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700269constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800270
271// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700272static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600273
Paul Crowley14c8c072018-09-18 13:30:21 -0700274#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700275
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700276#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800277
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800278#define CRYPTO_BLOCK_DEVICE "userdata"
279
280#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
281
Ken Sumrall29d8da82011-05-18 17:20:07 -0700282#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700283#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700284
Ken Sumralle919efe2012-09-29 17:07:41 -0700285#define TABLE_LOAD_RETRIES 10
286
Shawn Willden47ba10d2014-09-03 17:07:06 -0600287#define RSA_KEY_SIZE 2048
288#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
289#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600290#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700291
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700292#define RETRY_MOUNT_ATTEMPTS 10
293#define RETRY_MOUNT_DELAY_SECONDS 1
294
Paul Crowley5afbc622017-11-27 09:42:17 -0800295#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
296
Paul Crowley73473332017-11-21 15:43:51 -0800297static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
298
Greg Kaiser59ad0182018-02-16 13:01:36 -0800299static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700300static char* saved_mount_point;
301static int master_key_saved = 0;
302static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800303
Paul Crowley220567c2020-02-07 12:45:20 -0800304constexpr CryptoType aes_128_cbc = CryptoType()
305 .set_config_name("AES-128-CBC")
306 .set_kernel_name("aes-cbc-essiv:sha256")
307 .set_keysize(16);
308
309constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
310
311static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
312 array_length(supported_crypto_types)),
313 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
314 "incompletely constructed.");
315
316static const CryptoType& get_crypto_type() {
317 // We only want to parse this read-only property once. But we need to wait
318 // until the system is initialized before we can read it. So we use a static
319 // scoped within this function to get it only once.
320 static CryptoType crypto_type =
321 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
322 aes_128_cbc, "ro.crypto.fde_algorithm");
323 return crypto_type;
324}
325
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700326/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700327static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000328 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700329}
330
331/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700332static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800333 if (ftr->keymaster_blob_size) {
334 SLOGI("Already have key");
335 return 0;
336 }
337
Paul Crowley14c8c072018-09-18 13:30:21 -0700338 int rc = keymaster_create_key_for_cryptfs_scrypt(
339 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
340 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000341 if (rc) {
342 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800343 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000344 ftr->keymaster_blob_size = 0;
345 }
346 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700347 return -1;
348 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000349 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700350}
351
Shawn Willdene17a9c42014-09-08 13:04:08 -0600352/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700353static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
354 const size_t object_size, unsigned char** signature,
355 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600356 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600357 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600358 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600359
Shawn Willdene17a9c42014-09-08 13:04:08 -0600360 // To sign a message with RSA, the message must satisfy two
361 // constraints:
362 //
363 // 1. The message, when interpreted as a big-endian numeric value, must
364 // be strictly less than the public modulus of the RSA key. Note
365 // that because the most significant bit of the public modulus is
366 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
367 // key), an n-bit message with most significant bit 0 always
368 // satisfies this requirement.
369 //
370 // 2. The message must have the same length in bits as the public
371 // modulus of the RSA key. This requirement isn't mathematically
372 // necessary, but is necessary to ensure consistency in
373 // implementations.
374 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600375 case KDF_SCRYPT_KEYMASTER:
376 // This ensures the most significant byte of the signed message
377 // is zero. We could have zero-padded to the left instead, but
378 // this approach is slightly more robust against changes in
379 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600380 // so) because we really should be using a proper deterministic
381 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800382 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600383 SLOGI("Signing safely-padded object");
384 break;
385 default:
386 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000387 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600388 }
Paul Crowley73473332017-11-21 15:43:51 -0800389 for (;;) {
390 auto result = keymaster_sign_object_for_cryptfs_scrypt(
391 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
392 to_sign_size, signature, signature_size);
393 switch (result) {
394 case KeymasterSignResult::ok:
395 return 0;
396 case KeymasterSignResult::upgrade:
397 break;
398 default:
399 return -1;
400 }
401 SLOGD("Upgrading key");
402 if (keymaster_upgrade_key_for_cryptfs_scrypt(
403 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
404 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
405 &ftr->keymaster_blob_size) != 0) {
406 SLOGE("Failed to upgrade key");
407 return -1;
408 }
409 if (put_crypt_ftr_and_key(ftr) != 0) {
410 SLOGE("Failed to write upgraded key to disk");
411 }
412 SLOGD("Key upgraded successfully");
413 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600414}
415
Paul Lawrence399317e2014-03-10 13:20:50 -0700416/* Store password when userdata is successfully decrypted and mounted.
417 * Cleared by cryptfs_clear_password
418 *
419 * To avoid a double prompt at boot, we need to store the CryptKeeper
420 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
421 * Since the entire framework is torn down and rebuilt after encryption,
422 * we have to use a daemon or similar to store the password. Since vold
423 * is secured against IPC except from system processes, it seems a reasonable
424 * place to store this.
425 *
426 * password should be cleared once it has been used.
427 *
428 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800429 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700430static char* password = 0;
431static int password_expiry_time = 0;
432static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800433
Paul Crowley14c8c072018-09-18 13:30:21 -0700434enum class RebootType { reboot, recovery, shutdown };
435static void cryptfs_reboot(RebootType rt) {
436 switch (rt) {
437 case RebootType::reboot:
438 property_set(ANDROID_RB_PROPERTY, "reboot");
439 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800440
Paul Crowley14c8c072018-09-18 13:30:21 -0700441 case RebootType::recovery:
442 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
443 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800444
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 case RebootType::shutdown:
446 property_set(ANDROID_RB_PROPERTY, "shutdown");
447 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700448 }
Paul Lawrence87999172014-02-20 12:21:31 -0800449
Ken Sumralladfba362013-06-04 16:37:52 -0700450 sleep(20);
451
452 /* Shouldn't get here, reboot should happen before sleep times out */
453 return;
454}
455
Kenny Rootc4c70f12013-06-14 12:11:38 -0700456/**
457 * Gets the default device scrypt parameters for key derivation time tuning.
458 * The parameters should lead to about one second derivation time for the
459 * given device.
460 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700461static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700462 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000463 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700464
Paul Crowley63c18d32016-02-10 14:02:47 +0000465 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
466 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
467 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
468 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700469 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000470 ftr->N_factor = Nf;
471 ftr->r_factor = rf;
472 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700473}
474
Paul Crowleya661fb62020-02-11 16:21:54 -0800475size_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800476 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800477}
478
Tom Cherry4c5bde22019-01-29 14:34:01 -0800479static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800480 int fd, block_size;
481 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200482 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800483
Paul Crowley14c8c072018-09-18 13:30:21 -0700484 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800485 SLOGE("Cannot open device to get filesystem size ");
486 return 0;
487 }
488
489 if (lseek64(fd, 1024, SEEK_SET) < 0) {
490 SLOGE("Cannot seek to superblock");
491 return 0;
492 }
493
494 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
495 SLOGE("Cannot read superblock");
496 return 0;
497 }
498
499 close(fd);
500
Daniel Rosenberge82df162014-08-15 22:19:23 +0000501 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
502 SLOGE("Not a valid ext4 superblock");
503 return 0;
504 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800505 block_size = 1024 << sb.s_log_block_size;
506 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200507 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800508
509 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200510 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800511}
512
Tom Cherry4c5bde22019-01-29 14:34:01 -0800513static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
514 for (const auto& entry : fstab_default) {
515 if (!entry.fs_mgr_flags.vold_managed &&
516 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
517 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
518 if (key_loc != nullptr) {
519 *key_loc = entry.key_loc;
520 }
521 if (real_blk_device != nullptr) {
522 *real_blk_device = entry.blk_device;
523 }
524 return;
525 }
526 }
527}
528
Paul Crowley14c8c072018-09-18 13:30:21 -0700529static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
530 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200531 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700532 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700533 char key_loc[PROPERTY_VALUE_MAX];
534 char real_blkdev[PROPERTY_VALUE_MAX];
535 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700536
Paul Crowley14c8c072018-09-18 13:30:21 -0700537 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800538 std::string key_loc;
539 std::string real_blkdev;
540 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700541
Tom Cherry4c5bde22019-01-29 14:34:01 -0800542 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200543 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700544 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
545 * encryption info footer and key, and plenty of bytes to spare for future
546 * growth.
547 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800548 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200549 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700550 cached_data = 1;
551 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800552 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700553 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700554 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800555 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700556 cached_off = 0;
557 cached_data = 1;
558 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700560
Paul Crowley14c8c072018-09-18 13:30:21 -0700561 if (cached_data) {
562 if (metadata_fname) {
563 *metadata_fname = cached_metadata_fname;
564 }
565 if (off) {
566 *off = cached_off;
567 }
568 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700569 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700570
Paul Crowley14c8c072018-09-18 13:30:21 -0700571 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700572}
573
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800574/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700575static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800576 SHA256_CTX c;
577 SHA256_Init(&c);
578 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
579 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
580 SHA256_Final(crypt_ftr->sha256, &c);
581}
582
Ken Sumralle8744072011-01-18 22:01:55 -0800583/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800584 * update the failed mount count but not change the key.
585 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700586static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
587 int fd;
588 unsigned int cnt;
589 /* starting_off is set to the SEEK_SET offset
590 * where the crypto structure starts
591 */
592 off64_t starting_off;
593 int rc = -1;
594 char* fname = NULL;
595 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800596
Paul Crowley14c8c072018-09-18 13:30:21 -0700597 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800598
Paul Crowley14c8c072018-09-18 13:30:21 -0700599 if (get_crypt_ftr_info(&fname, &starting_off)) {
600 SLOGE("Unable to get crypt_ftr_info\n");
601 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800602 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700603 if (fname[0] != '/') {
604 SLOGE("Unexpected value for crypto key location\n");
605 return -1;
606 }
607 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
608 SLOGE("Cannot open footer file %s for put\n", fname);
609 return -1;
610 }
Ken Sumralle8744072011-01-18 22:01:55 -0800611
Paul Crowley14c8c072018-09-18 13:30:21 -0700612 /* Seek to the start of the crypt footer */
613 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
614 SLOGE("Cannot seek to real block device footer\n");
615 goto errout;
616 }
617
618 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
619 SLOGE("Cannot write real block device footer\n");
620 goto errout;
621 }
622
623 fstat(fd, &statbuf);
624 /* If the keys are kept on a raw block device, do not try to truncate it. */
625 if (S_ISREG(statbuf.st_mode)) {
626 if (ftruncate(fd, 0x4000)) {
627 SLOGE("Cannot set footer file size\n");
628 goto errout;
629 }
630 }
631
632 /* Success! */
633 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800634
635errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700636 close(fd);
637 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800638}
639
Paul Crowley14c8c072018-09-18 13:30:21 -0700640static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800641 struct crypt_mnt_ftr copy;
642 memcpy(&copy, crypt_ftr, sizeof(copy));
643 set_ftr_sha(&copy);
644 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
645}
646
Paul Crowley14c8c072018-09-18 13:30:21 -0700647static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700648 return TEMP_FAILURE_RETRY(read(fd, buff, len));
649}
650
Paul Crowley14c8c072018-09-18 13:30:21 -0700651static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700652 return TEMP_FAILURE_RETRY(write(fd, buff, len));
653}
654
Paul Crowley14c8c072018-09-18 13:30:21 -0700655static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700656 memset(pdata, 0, len);
657 pdata->persist_magic = PERSIST_DATA_MAGIC;
658 pdata->persist_valid_entries = 0;
659}
660
661/* A routine to update the passed in crypt_ftr to the lastest version.
662 * fd is open read/write on the device that holds the crypto footer and persistent
663 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
664 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
665 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700666static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700667 int orig_major = crypt_ftr->major_version;
668 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700669
Kenny Root7434b312013-06-14 11:29:53 -0700670 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700671 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700672 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700673
Kenny Rootc4c70f12013-06-14 12:11:38 -0700674 SLOGW("upgrading crypto footer to 1.1");
675
Paul Crowley14c8c072018-09-18 13:30:21 -0700676 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700677 if (pdata == NULL) {
678 SLOGE("Cannot allocate persisent data\n");
679 return;
680 }
681 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
682
683 /* Need to initialize the persistent data area */
684 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
685 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100686 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700687 return;
688 }
689 /* Write all zeros to the first copy, making it invalid */
690 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
691
692 /* Write a valid but empty structure to the second copy */
693 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
694 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
695
696 /* Update the footer */
697 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
698 crypt_ftr->persist_data_offset[0] = pdata_offset;
699 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
700 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100701 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700702 }
703
Paul Lawrencef4faa572014-01-29 13:31:03 -0800704 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700705 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800706 /* But keep the old kdf_type.
707 * It will get updated later to KDF_SCRYPT after the password has been verified.
708 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700709 crypt_ftr->kdf_type = KDF_PBKDF2;
710 get_device_scrypt_params(crypt_ftr);
711 crypt_ftr->minor_version = 2;
712 }
713
Paul Lawrencef4faa572014-01-29 13:31:03 -0800714 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
715 SLOGW("upgrading crypto footer to 1.3");
716 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
717 crypt_ftr->minor_version = 3;
718 }
719
Kenny Root7434b312013-06-14 11:29:53 -0700720 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
721 if (lseek64(fd, offset, SEEK_SET) == -1) {
722 SLOGE("Cannot seek to crypt footer\n");
723 return;
724 }
725 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700726 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700727}
728
Paul Crowley14c8c072018-09-18 13:30:21 -0700729static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
730 int fd;
731 unsigned int cnt;
732 off64_t starting_off;
733 int rc = -1;
734 char* fname = NULL;
735 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700736
Paul Crowley14c8c072018-09-18 13:30:21 -0700737 if (get_crypt_ftr_info(&fname, &starting_off)) {
738 SLOGE("Unable to get crypt_ftr_info\n");
739 return -1;
740 }
741 if (fname[0] != '/') {
742 SLOGE("Unexpected value for crypto key location\n");
743 return -1;
744 }
745 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
746 SLOGE("Cannot open footer file %s for get\n", fname);
747 return -1;
748 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800749
Paul Crowley14c8c072018-09-18 13:30:21 -0700750 /* Make sure it's 16 Kbytes in length */
751 fstat(fd, &statbuf);
752 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
753 SLOGE("footer file %s is not the expected size!\n", fname);
754 goto errout;
755 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700756
Paul Crowley14c8c072018-09-18 13:30:21 -0700757 /* Seek to the start of the crypt footer */
758 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
759 SLOGE("Cannot seek to real block device footer\n");
760 goto errout;
761 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700762
Paul Crowley14c8c072018-09-18 13:30:21 -0700763 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
764 SLOGE("Cannot read real block device footer\n");
765 goto errout;
766 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800767
Paul Crowley14c8c072018-09-18 13:30:21 -0700768 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
769 SLOGE("Bad magic for real block device %s\n", fname);
770 goto errout;
771 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800772
Paul Crowley14c8c072018-09-18 13:30:21 -0700773 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
774 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
775 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
776 goto errout;
777 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800778
Paul Crowley14c8c072018-09-18 13:30:21 -0700779 // We risk buffer overflows with oversized keys, so we just reject them.
780 // 0-sized keys are problematic (essentially by-passing encryption), and
781 // AES-CBC key wrapping only works for multiples of 16 bytes.
782 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
783 (crypt_ftr->keysize > MAX_KEY_LEN)) {
784 SLOGE(
785 "Invalid keysize (%u) for block device %s; Must be non-zero, "
786 "divisible by 16, and <= %d\n",
787 crypt_ftr->keysize, fname, MAX_KEY_LEN);
788 goto errout;
789 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800790
Paul Crowley14c8c072018-09-18 13:30:21 -0700791 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
792 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
793 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
794 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800795
Paul Crowley14c8c072018-09-18 13:30:21 -0700796 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
797 * copy on disk before returning.
798 */
799 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
800 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
801 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800802
Paul Crowley14c8c072018-09-18 13:30:21 -0700803 /* Success! */
804 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800805
806errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700807 close(fd);
808 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800809}
810
Paul Crowley14c8c072018-09-18 13:30:21 -0700811static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700812 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
813 crypt_ftr->persist_data_offset[1]) {
814 SLOGE("Crypt_ftr persist data regions overlap");
815 return -1;
816 }
817
818 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
819 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
820 return -1;
821 }
822
823 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700824 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700825 CRYPT_FOOTER_OFFSET) {
826 SLOGE("Persistent data extends past crypto footer");
827 return -1;
828 }
829
830 return 0;
831}
832
Paul Crowley14c8c072018-09-18 13:30:21 -0700833static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700834 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700835 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700836 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700837 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700838 int found = 0;
839 int fd;
840 int ret;
841 int i;
842
843 if (persist_data) {
844 /* Nothing to do, we've already loaded or initialized it */
845 return 0;
846 }
847
Ken Sumrall160b4d62013-04-22 12:15:39 -0700848 /* If not encrypted, just allocate an empty table and initialize it */
849 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700850 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800851 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700852 if (pdata) {
853 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
854 persist_data = pdata;
855 return 0;
856 }
857 return -1;
858 }
859
Paul Crowley14c8c072018-09-18 13:30:21 -0700860 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700861 return -1;
862 }
863
Paul Crowley14c8c072018-09-18 13:30:21 -0700864 if ((crypt_ftr.major_version < 1) ||
865 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700866 SLOGE("Crypt_ftr version doesn't support persistent data");
867 return -1;
868 }
869
870 if (get_crypt_ftr_info(&fname, NULL)) {
871 return -1;
872 }
873
874 ret = validate_persistent_data_storage(&crypt_ftr);
875 if (ret) {
876 return -1;
877 }
878
Paul Crowley14c8c072018-09-18 13:30:21 -0700879 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700880 if (fd < 0) {
881 SLOGE("Cannot open %s metadata file", fname);
882 return -1;
883 }
884
Wei Wang4375f1b2017-02-24 17:43:01 -0800885 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800886 if (pdata == NULL) {
887 SLOGE("Cannot allocate memory for persistent data");
888 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700889 }
890
891 for (i = 0; i < 2; i++) {
892 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
893 SLOGE("Cannot seek to read persistent data on %s", fname);
894 goto err2;
895 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700896 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700897 SLOGE("Error reading persistent data on iteration %d", i);
898 goto err2;
899 }
900 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
901 found = 1;
902 break;
903 }
904 }
905
906 if (!found) {
907 SLOGI("Could not find valid persistent data, creating");
908 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
909 }
910
911 /* Success */
912 persist_data = pdata;
913 close(fd);
914 return 0;
915
916err2:
917 free(pdata);
918
919err:
920 close(fd);
921 return -1;
922}
923
Paul Crowley14c8c072018-09-18 13:30:21 -0700924static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700925 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700926 struct crypt_persist_data* pdata;
927 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700928 off64_t write_offset;
929 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700930 int fd;
931 int ret;
932
933 if (persist_data == NULL) {
934 SLOGE("No persistent data to save");
935 return -1;
936 }
937
Paul Crowley14c8c072018-09-18 13:30:21 -0700938 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700939 return -1;
940 }
941
Paul Crowley14c8c072018-09-18 13:30:21 -0700942 if ((crypt_ftr.major_version < 1) ||
943 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700944 SLOGE("Crypt_ftr version doesn't support persistent data");
945 return -1;
946 }
947
948 ret = validate_persistent_data_storage(&crypt_ftr);
949 if (ret) {
950 return -1;
951 }
952
953 if (get_crypt_ftr_info(&fname, NULL)) {
954 return -1;
955 }
956
Paul Crowley14c8c072018-09-18 13:30:21 -0700957 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700958 if (fd < 0) {
959 SLOGE("Cannot open %s metadata file", fname);
960 return -1;
961 }
962
Wei Wang4375f1b2017-02-24 17:43:01 -0800963 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700964 if (pdata == NULL) {
965 SLOGE("Cannot allocate persistant data");
966 goto err;
967 }
968
969 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
970 SLOGE("Cannot seek to read persistent data on %s", fname);
971 goto err2;
972 }
973
974 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700975 SLOGE("Error reading persistent data before save");
976 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700977 }
978
979 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
980 /* The first copy is the curent valid copy, so write to
981 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700982 write_offset = crypt_ftr.persist_data_offset[1];
983 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700984 } else {
985 /* The second copy must be the valid copy, so write to
986 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700987 write_offset = crypt_ftr.persist_data_offset[0];
988 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700989 }
990
991 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100992 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700993 SLOGE("Cannot seek to write persistent data");
994 goto err2;
995 }
996 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700997 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100998 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700999 SLOGE("Cannot seek to erase previous persistent data");
1000 goto err2;
1001 }
1002 fsync(fd);
1003 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001004 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001005 SLOGE("Cannot write to erase previous persistent data");
1006 goto err2;
1007 }
1008 fsync(fd);
1009 } else {
1010 SLOGE("Cannot write to save persistent data");
1011 goto err2;
1012 }
1013
1014 /* Success */
1015 free(pdata);
1016 close(fd);
1017 return 0;
1018
1019err2:
1020 free(pdata);
1021err:
1022 close(fd);
1023 return -1;
1024}
1025
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001026/* Convert a binary key of specified length into an ascii hex string equivalent,
1027 * without the leading 0x and with null termination
1028 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001029static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1030 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001031 unsigned int i, a;
1032 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001033
Paul Crowley14c8c072018-09-18 13:30:21 -07001034 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001035 /* For each byte, write out two ascii hex digits */
1036 nibble = (master_key[i] >> 4) & 0xf;
1037 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001038
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001039 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001040 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001041 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001042
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001043 /* Add the null termination */
1044 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001045}
1046
Eric Biggersed45ec32019-01-25 10:47:55 -08001047/*
1048 * If the ro.crypto.fde_sector_size system property is set, append the
1049 * parameters to make dm-crypt use the specified crypto sector size and round
1050 * the crypto device size down to a crypto sector boundary.
1051 */
David Andersonb9224732019-05-13 13:02:54 -07001052static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001053 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001054 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001055
Eric Biggersed45ec32019-01-25 10:47:55 -08001056 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1057 unsigned int sector_size;
1058
1059 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1060 (sector_size & (sector_size - 1)) != 0) {
1061 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1062 DM_CRYPT_SECTOR_SIZE, value);
1063 return -1;
1064 }
1065
David Andersonb9224732019-05-13 13:02:54 -07001066 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001067
1068 // With this option, IVs will match the sector numbering, instead
1069 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001070 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001071
1072 // Round the crypto device size down to a crypto sector boundary.
1073 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001074 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001075 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001076}
1077
Paul Crowley5afbc622017-11-27 09:42:17 -08001078static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001079 const char* real_blk_name, std::string* crypto_blk_name,
1080 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001081 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001082
David Andersonb9224732019-05-13 13:02:54 -07001083 // We need two ASCII characters to represent each byte, and need space for
1084 // the '\0' terminator.
1085 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1086 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001087
David Andersonb9224732019-05-13 13:02:54 -07001088 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1089 (const char*)crypt_ftr->crypto_type_name,
1090 master_key_ascii, 0, real_blk_name, 0);
1091 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092
Paul Crowley5afbc622017-11-27 09:42:17 -08001093 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001094 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001095 }
David Andersonb9224732019-05-13 13:02:54 -07001096 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001097 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001098 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001099 }
David Andersonb9224732019-05-13 13:02:54 -07001100
1101 DmTable table;
1102 table.AddTarget(std::move(target));
1103
1104 int load_count = 1;
1105 while (load_count < TABLE_LOAD_RETRIES) {
1106 if (dm.CreateDevice(name, table)) {
1107 break;
1108 }
1109 load_count++;
1110 }
1111
1112 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001113 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001114 return -1;
1115 }
1116 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001117 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1118 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001119
Paul Crowley81796e92020-02-07 11:27:49 -08001120 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001121 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1122 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001123 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001124
Paul Crowleycfe39722018-10-30 15:59:24 -07001125 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001126 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001127 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001128 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001129 }
David Andersonb9224732019-05-13 13:02:54 -07001130 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131}
1132
David Andersonb9224732019-05-13 13:02:54 -07001133static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001134 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001135 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001136 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1137 // to delete the device fails with EBUSY; for now, work around this by retrying.
1138 int tries = 5;
1139 while (tries-- > 0) {
1140 ret = dm.DeleteDevice(name);
1141 if (ret || errno != EBUSY) {
1142 break;
1143 }
1144 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1145 strerror(errno));
1146 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1147 }
1148 if (!ret) {
1149 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001150 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001151 }
David Andersonb9224732019-05-13 13:02:54 -07001152 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001153}
1154
Paul Crowley14c8c072018-09-18 13:30:21 -07001155static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1156 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001157 SLOGI("Using pbkdf2 for cryptfs KDF");
1158
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001159 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001160 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1161 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001162}
1163
Paul Crowley14c8c072018-09-18 13:30:21 -07001164static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001165 SLOGI("Using scrypt for cryptfs KDF");
1166
Paul Crowley14c8c072018-09-18 13:30:21 -07001167 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001168
1169 int N = 1 << ftr->N_factor;
1170 int r = 1 << ftr->r_factor;
1171 int p = 1 << ftr->p_factor;
1172
1173 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001174 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001175 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001176
Paul Crowley14c8c072018-09-18 13:30:21 -07001177 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001178}
1179
Paul Crowley14c8c072018-09-18 13:30:21 -07001180static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1181 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001182 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1183
1184 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001185 size_t signature_size;
1186 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001187 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001188
1189 int N = 1 << ftr->N_factor;
1190 int r = 1 << ftr->r_factor;
1191 int p = 1 << ftr->p_factor;
1192
Paul Crowley14c8c072018-09-18 13:30:21 -07001193 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001194 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001195
1196 if (rc) {
1197 SLOGE("scrypt failed");
1198 return -1;
1199 }
1200
Paul Crowley14c8c072018-09-18 13:30:21 -07001201 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001202 SLOGE("Signing failed");
1203 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001204 }
1205
Paul Crowley14c8c072018-09-18 13:30:21 -07001206 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1207 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001208 free(signature);
1209
1210 if (rc) {
1211 SLOGE("scrypt failed");
1212 return -1;
1213 }
1214
1215 return 0;
1216}
1217
Paul Crowley14c8c072018-09-18 13:30:21 -07001218static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1219 const unsigned char* decrypted_master_key,
1220 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1221 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001222 EVP_CIPHER_CTX e_ctx;
1223 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001224 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001225
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001226 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001227 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001228
1229 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001230 case KDF_SCRYPT_KEYMASTER:
1231 if (keymaster_create_key(crypt_ftr)) {
1232 SLOGE("keymaster_create_key failed");
1233 return -1;
1234 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001235
Paul Crowley14c8c072018-09-18 13:30:21 -07001236 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1237 SLOGE("scrypt failed");
1238 return -1;
1239 }
1240 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001241
Paul Crowley14c8c072018-09-18 13:30:21 -07001242 case KDF_SCRYPT:
1243 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1244 SLOGE("scrypt failed");
1245 return -1;
1246 }
1247 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001248
Paul Crowley14c8c072018-09-18 13:30:21 -07001249 default:
1250 SLOGE("Invalid kdf_type");
1251 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001252 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001253
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001254 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001255 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001256 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1257 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258 SLOGE("EVP_EncryptInit failed\n");
1259 return -1;
1260 }
1261 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001262
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001264 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1265 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001266 SLOGE("EVP_EncryptUpdate failed\n");
1267 return -1;
1268 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001269 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001270 SLOGE("EVP_EncryptFinal failed\n");
1271 return -1;
1272 }
1273
Greg Kaiser59ad0182018-02-16 13:01:36 -08001274 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001275 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1276 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001277 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001278
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001279 /* Store the scrypt of the intermediate key, so we can validate if it's a
1280 password error or mount error when things go wrong.
1281 Note there's no need to check for errors, since if this is incorrect, we
1282 simply won't wipe userdata, which is the correct default behavior
1283 */
1284 int N = 1 << crypt_ftr->N_factor;
1285 int r = 1 << crypt_ftr->r_factor;
1286 int p = 1 << crypt_ftr->p_factor;
1287
Paul Crowley14c8c072018-09-18 13:30:21 -07001288 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1289 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001290 sizeof(crypt_ftr->scrypted_intermediate_key));
1291
1292 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001293 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001294 }
1295
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001296 EVP_CIPHER_CTX_cleanup(&e_ctx);
1297
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001298 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299}
1300
Paul Crowley14c8c072018-09-18 13:30:21 -07001301static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1302 const unsigned char* encrypted_master_key, size_t keysize,
1303 unsigned char* decrypted_master_key, kdf_func kdf,
1304 void* kdf_params, unsigned char** intermediate_key,
1305 size_t* intermediate_key_size) {
1306 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1307 EVP_CIPHER_CTX d_ctx;
1308 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001309
Paul Crowley14c8c072018-09-18 13:30:21 -07001310 /* Turn the password into an intermediate key and IV that can decrypt the
1311 master key */
1312 if (kdf(passwd, salt, ikey, kdf_params)) {
1313 SLOGE("kdf failed");
1314 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001315 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001316
Paul Crowley14c8c072018-09-18 13:30:21 -07001317 /* Initialize the decryption engine */
1318 EVP_CIPHER_CTX_init(&d_ctx);
1319 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1320 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1321 return -1;
1322 }
1323 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1324 /* Decrypt the master key */
1325 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1326 keysize)) {
1327 return -1;
1328 }
1329 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1330 return -1;
1331 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001332
Paul Crowley14c8c072018-09-18 13:30:21 -07001333 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1334 return -1;
1335 }
1336
1337 /* Copy intermediate key if needed by params */
1338 if (intermediate_key && intermediate_key_size) {
1339 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1340 if (*intermediate_key) {
1341 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1342 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1343 }
1344 }
1345
1346 EVP_CIPHER_CTX_cleanup(&d_ctx);
1347
1348 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349}
1350
Paul Crowley14c8c072018-09-18 13:30:21 -07001351static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001352 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001353 *kdf = scrypt_keymaster;
1354 *kdf_params = ftr;
1355 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001356 *kdf = scrypt;
1357 *kdf_params = ftr;
1358 } else {
1359 *kdf = pbkdf2;
1360 *kdf_params = NULL;
1361 }
1362}
1363
Paul Crowley14c8c072018-09-18 13:30:21 -07001364static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1365 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1366 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001367 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001368 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001369 int ret;
1370
1371 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001372 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1373 decrypted_master_key, kdf, kdf_params, intermediate_key,
1374 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001375 if (ret != 0) {
1376 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001377 }
1378
1379 return ret;
1380}
1381
Paul Crowley14c8c072018-09-18 13:30:21 -07001382static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1383 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001384 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001385
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001386 /* Get some random bits for a key and salt */
1387 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1388 return -1;
1389 }
1390 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1391 return -1;
1392 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001393
1394 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001395 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001396}
1397
Paul Crowley73be12d2020-02-03 12:22:03 -08001398static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001399 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001400#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001401
1402 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001403 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001404 if (umount(mountpoint) == 0) {
1405 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001406 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001407
1408 if (errno == EINVAL) {
1409 /* EINVAL is returned if the directory is not a mountpoint,
1410 * i.e. there is no filesystem mounted there. So just get out.
1411 */
1412 break;
1413 }
1414
1415 err = errno;
1416
1417 /* If allowed, be increasingly aggressive before the last two retries */
1418 if (kill) {
1419 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1420 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001421 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001422 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1423 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001424 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001425 }
1426 }
1427
1428 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001429 }
1430
1431 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001432 SLOGD("unmounting %s succeeded\n", mountpoint);
1433 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001434 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001435 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1436 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1437 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001438 }
1439
1440 return rc;
1441}
1442
Paul Crowley14c8c072018-09-18 13:30:21 -07001443static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001444 // NOTE: post_fs_data results in init calling back around to vold, so all
1445 // callers to this method must be async
1446
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001447 /* Do the prep of the /data filesystem */
1448 property_set("vold.post_fs_data_done", "0");
1449 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001450 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001451
Ken Sumrallc5872692013-05-14 15:26:31 -07001452 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001453 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001454 /* We timed out to prep /data in time. Continue wait. */
1455 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001456 }
Wei Wang42e38102017-06-07 10:46:12 -07001457 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001458}
1459
Paul Crowley14c8c072018-09-18 13:30:21 -07001460static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001461 // Mark the footer as bad
1462 struct crypt_mnt_ftr crypt_ftr;
1463 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1464 SLOGE("Failed to get crypto footer - panic");
1465 return;
1466 }
1467
1468 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1469 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1470 SLOGE("Failed to set crypto footer - panic");
1471 return;
1472 }
1473}
1474
Paul Crowley14c8c072018-09-18 13:30:21 -07001475static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001476 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001477 SLOGE("Failed to mount tmpfs on data - panic");
1478 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001479 }
1480
1481 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1482 SLOGE("Failed to trigger post fs data - panic");
1483 return;
1484 }
1485
1486 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1487 SLOGE("Failed to trigger restart min framework - panic");
1488 return;
1489 }
1490}
1491
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001492/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001493static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001494 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001495 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001496 static int restart_successful = 0;
1497
1498 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001499 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001500 SLOGE("Encrypted filesystem not validated, aborting");
1501 return -1;
1502 }
1503
1504 if (restart_successful) {
1505 SLOGE("System already restarted with encrypted disk, aborting");
1506 return -1;
1507 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001508
Paul Lawrencef4faa572014-01-29 13:31:03 -08001509 if (restart_main) {
1510 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001511 * start all services in one of these classes: core, early_hal, hal,
1512 * main and late_start. To get to the minimal UI for PIN entry, we
1513 * need to start core, early_hal, hal and main. When we want to
1514 * shutdown the framework again, we need to stop most of the services in
1515 * these classes, but only those services that were started after
1516 * /data was mounted. This excludes critical services like vold and
1517 * ueventd, which need to keep running. We could possible stop
1518 * even fewer services, but because we want services to pick up APEX
1519 * libraries from the real /data, restarting is better, as it makes
1520 * these devices consistent with FBE devices and lets them use the
1521 * most recent code.
1522 *
1523 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001524 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001525 * We then restart the class core, hal, main, and also the class
1526 * late_start.
1527 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001528 * At the moment, I've only put a few things in late_start that I know
1529 * are not needed to bring up the framework, and that also cause problems
1530 * with unmounting the tmpfs /data, but I hope to add add more services
1531 * to the late_start class as we optimize this to decrease the delay
1532 * till the user is asked for the password to the filesystem.
1533 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001535 /* The init files are setup to stop the right set of services when
1536 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001537 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001538 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001539 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540
Paul Lawrencef4faa572014-01-29 13:31:03 -08001541 /* Ugh, shutting down the framework is not synchronous, so until it
1542 * can be fixed, this horrible hack will wait a moment for it all to
1543 * shut down before proceeding. Without it, some devices cannot
1544 * restart the graphics services.
1545 */
1546 sleep(2);
1547 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001548
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001549 /* Now that the framework is shutdown, we should be able to umount()
1550 * the tmpfs filesystem, and mount the real one.
1551 */
1552
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001553 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1554 if (strlen(crypto_blkdev) == 0) {
1555 SLOGE("fs_crypto_blkdev not set\n");
1556 return -1;
1557 }
1558
Paul Crowley14c8c072018-09-18 13:30:21 -07001559 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001560 /* If ro.crypto.readonly is set to 1, mount the decrypted
1561 * filesystem readonly. This is used when /data is mounted by
1562 * recovery mode.
1563 */
1564 char ro_prop[PROPERTY_VALUE_MAX];
1565 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001566 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001567 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1568 if (entry != nullptr) {
1569 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001570 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001571 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001572
Ken Sumralle5032c42012-04-01 23:58:44 -07001573 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001574 int retries = RETRY_MOUNT_ATTEMPTS;
1575 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001576
1577 /*
1578 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1579 * partitions in the fsck domain.
1580 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001581 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001582 SLOGE("Failed to setexeccon");
1583 return -1;
1584 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001585 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001586 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001587 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001588 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1589 /* TODO: invoke something similar to
1590 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1591 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001592 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001593 if (--retries) {
1594 sleep(RETRY_MOUNT_DELAY_SECONDS);
1595 } else {
1596 /* Let's hope that a reboot clears away whatever is keeping
1597 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001598 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001599 }
1600 } else {
1601 SLOGE("Failed to mount decrypted data");
1602 cryptfs_set_corrupt();
1603 cryptfs_trigger_restart_min_framework();
1604 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001605 if (setexeccon(NULL)) {
1606 SLOGE("Failed to setexeccon");
1607 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001608 return -1;
1609 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001610 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001611 if (setexeccon(NULL)) {
1612 SLOGE("Failed to setexeccon");
1613 return -1;
1614 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001615
Ken Sumralle5032c42012-04-01 23:58:44 -07001616 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001617 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001618 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001619
1620 /* startup service classes main and late_start */
1621 property_set("vold.decrypt", "trigger_restart_framework");
1622 SLOGD("Just triggered restart_framework\n");
1623
1624 /* Give it a few moments to get started */
1625 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001626 }
1627
Ken Sumrall0cc16632011-01-18 20:32:26 -08001628 if (rc == 0) {
1629 restart_successful = 1;
1630 }
1631
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632 return rc;
1633}
1634
Paul Crowley14c8c072018-09-18 13:30:21 -07001635int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001636 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001637 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001638 SLOGE("cryptfs_restart not valid for file encryption:");
1639 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001640 }
1641
Paul Lawrencef4faa572014-01-29 13:31:03 -08001642 /* Call internal implementation forcing a restart of main service group */
1643 return cryptfs_restart_internal(1);
1644}
1645
Paul Crowley14c8c072018-09-18 13:30:21 -07001646static int do_crypto_complete(const char* mount_point) {
1647 struct crypt_mnt_ftr crypt_ftr;
1648 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001649
Paul Crowley14c8c072018-09-18 13:30:21 -07001650 property_get("ro.crypto.state", encrypted_state, "");
1651 if (strcmp(encrypted_state, "encrypted")) {
1652 SLOGE("not running with encryption, aborting");
1653 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001654 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001655
Paul Crowley14c8c072018-09-18 13:30:21 -07001656 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001657 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001658 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1659 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001660
Paul Crowley14c8c072018-09-18 13:30:21 -07001661 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001662 std::string key_loc;
1663 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001664
Paul Crowley14c8c072018-09-18 13:30:21 -07001665 /*
1666 * Only report this error if key_loc is a file and it exists.
1667 * If the device was never encrypted, and /data is not mountable for
1668 * some reason, returning 1 should prevent the UI from presenting the
1669 * a "enter password" screen, or worse, a "press button to wipe the
1670 * device" screen.
1671 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001672 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001673 SLOGE("master key file does not exist, aborting");
1674 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1675 } else {
1676 SLOGE("Error getting crypt footer and key\n");
1677 return CRYPTO_COMPLETE_BAD_METADATA;
1678 }
1679 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680
Paul Crowley14c8c072018-09-18 13:30:21 -07001681 // Test for possible error flags
1682 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1683 SLOGE("Encryption process is partway completed\n");
1684 return CRYPTO_COMPLETE_PARTIAL;
1685 }
1686
1687 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1688 SLOGE("Encryption process was interrupted but cannot continue\n");
1689 return CRYPTO_COMPLETE_INCONSISTENT;
1690 }
1691
1692 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1693 SLOGE("Encryption is successful but data is corrupt\n");
1694 return CRYPTO_COMPLETE_CORRUPT;
1695 }
1696
1697 /* We passed the test! We shall diminish, and return to the west */
1698 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001699}
1700
Paul Crowley14c8c072018-09-18 13:30:21 -07001701static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1702 const char* mount_point, const char* label) {
1703 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001704 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001705 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001706 char tmp_mount_point[64];
1707 unsigned int orig_failed_decrypt_count;
1708 int rc;
1709 int use_keymaster = 0;
1710 int upgrade = 0;
1711 unsigned char* intermediate_key = 0;
1712 size_t intermediate_key_size = 0;
1713 int N = 1 << crypt_ftr->N_factor;
1714 int r = 1 << crypt_ftr->r_factor;
1715 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001716
Paul Crowley14c8c072018-09-18 13:30:21 -07001717 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1718 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001719
Paul Crowley14c8c072018-09-18 13:30:21 -07001720 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1721 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1722 &intermediate_key_size)) {
1723 SLOGE("Failed to decrypt master key\n");
1724 rc = -1;
1725 goto errout;
1726 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001727 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001728
Tom Cherry4c5bde22019-01-29 14:34:01 -08001729 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001730
Paul Crowley14c8c072018-09-18 13:30:21 -07001731 // Create crypto block device - all (non fatal) code paths
1732 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001733 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001734 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001735 SLOGE("Error creating decrypted block device\n");
1736 rc = -1;
1737 goto errout;
1738 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001739
Paul Crowley14c8c072018-09-18 13:30:21 -07001740 /* Work out if the problem is the password or the data */
1741 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001742
Paul Crowley14c8c072018-09-18 13:30:21 -07001743 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1744 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1745 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001746
Paul Crowley14c8c072018-09-18 13:30:21 -07001747 // Does the key match the crypto footer?
1748 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1749 sizeof(scrypted_intermediate_key)) == 0) {
1750 SLOGI("Password matches");
1751 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001752 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001753 /* Try mounting the file system anyway, just in case the problem's with
1754 * the footer, not the key. */
1755 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1756 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001757 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1758 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001759 SLOGE("Error temp mounting decrypted block device\n");
1760 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001761
Paul Crowley14c8c072018-09-18 13:30:21 -07001762 rc = ++crypt_ftr->failed_decrypt_count;
1763 put_crypt_ftr_and_key(crypt_ftr);
1764 } else {
1765 /* Success! */
1766 SLOGI("Password did not match but decrypted drive mounted - continue");
1767 umount(tmp_mount_point);
1768 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001769 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001770 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001771
Paul Crowley14c8c072018-09-18 13:30:21 -07001772 if (rc == 0) {
1773 crypt_ftr->failed_decrypt_count = 0;
1774 if (orig_failed_decrypt_count != 0) {
1775 put_crypt_ftr_and_key(crypt_ftr);
1776 }
1777
1778 /* Save the name of the crypto block device
1779 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001780 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001781
1782 /* Also save a the master key so we can reencrypted the key
1783 * the key when we want to change the password on it. */
1784 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1785 saved_mount_point = strdup(mount_point);
1786 master_key_saved = 1;
1787 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1788 rc = 0;
1789
1790 // Upgrade if we're not using the latest KDF.
1791 use_keymaster = keymaster_check_compatibility();
1792 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1793 // Don't allow downgrade
1794 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1795 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1796 upgrade = 1;
1797 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1798 crypt_ftr->kdf_type = KDF_SCRYPT;
1799 upgrade = 1;
1800 }
1801
1802 if (upgrade) {
1803 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1804 crypt_ftr->master_key, crypt_ftr);
1805 if (!rc) {
1806 rc = put_crypt_ftr_and_key(crypt_ftr);
1807 }
1808 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1809
1810 // Do not fail even if upgrade failed - machine is bootable
1811 // Note that if this code is ever hit, there is a *serious* problem
1812 // since KDFs should never fail. You *must* fix the kdf before
1813 // proceeding!
1814 if (rc) {
1815 SLOGW(
1816 "Upgrade failed with error %d,"
1817 " but continuing with previous state",
1818 rc);
1819 rc = 0;
1820 }
1821 }
1822 }
1823
1824errout:
1825 if (intermediate_key) {
1826 memset(intermediate_key, 0, intermediate_key_size);
1827 free(intermediate_key);
1828 }
1829 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001830}
1831
Ken Sumrall29d8da82011-05-18 17:20:07 -07001832/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001833 * Called by vold when it's asked to mount an encrypted external
1834 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001835 * as any metadata is been stored in a separate, small partition. We
1836 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001837 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001838int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001839 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001840 auto crypto_type = get_crypto_type();
1841 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001842 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001843 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001844 return -1;
1845 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001846 uint64_t nr_sec = 0;
1847 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001848 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001849 return -1;
1850 }
1851
Jeff Sharkey9c484982015-03-31 10:35:33 -07001852 struct crypt_mnt_ftr ext_crypt_ftr;
1853 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1854 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001855 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1856 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001857 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001858 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001859 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001860 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1861 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001862
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001863 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1864 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001865}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001866
Paul Crowley14c8c072018-09-18 13:30:21 -07001867int cryptfs_crypto_complete(void) {
1868 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001869}
1870
Paul Crowley14c8c072018-09-18 13:30:21 -07001871int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001872 char encrypted_state[PROPERTY_VALUE_MAX];
1873 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001874 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1875 SLOGE(
1876 "encrypted fs already validated or not running with encryption,"
1877 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001878 return -1;
1879 }
1880
1881 if (get_crypt_ftr_and_key(crypt_ftr)) {
1882 SLOGE("Error getting crypt footer and key");
1883 return -1;
1884 }
1885
1886 return 0;
1887}
1888
Paul Crowley14c8c072018-09-18 13:30:21 -07001889int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001890 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001891 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001892 SLOGE("cryptfs_check_passwd not valid for file encryption");
1893 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001894 }
1895
Paul Lawrencef4faa572014-01-29 13:31:03 -08001896 struct crypt_mnt_ftr crypt_ftr;
1897 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001898
Paul Lawrencef4faa572014-01-29 13:31:03 -08001899 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001900 if (rc) {
1901 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001902 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001903 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001904
Paul Crowley14c8c072018-09-18 13:30:21 -07001905 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001906 if (rc) {
1907 SLOGE("Password did not match");
1908 return rc;
1909 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001910
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001911 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1912 // Here we have a default actual password but a real password
1913 // we must test against the scrypted value
1914 // First, we must delete the crypto block device that
1915 // test_mount_encrypted_fs leaves behind as a side effect
1916 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001917 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1918 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001919 if (rc) {
1920 SLOGE("Default password did not match on reboot encryption");
1921 return rc;
1922 }
1923
1924 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1925 put_crypt_ftr_and_key(&crypt_ftr);
1926 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1927 if (rc) {
1928 SLOGE("Could not change password on reboot encryption");
1929 return rc;
1930 }
1931 }
1932
1933 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001934 cryptfs_clear_password();
1935 password = strdup(passwd);
1936 struct timespec now;
1937 clock_gettime(CLOCK_BOOTTIME, &now);
1938 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001939 }
1940
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001941 return rc;
1942}
1943
Paul Crowley14c8c072018-09-18 13:30:21 -07001944int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001945 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001946 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001947 char encrypted_state[PROPERTY_VALUE_MAX];
1948 int rc;
1949
1950 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001951 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001952 SLOGE("device not encrypted, aborting");
1953 return -2;
1954 }
1955
1956 if (!master_key_saved) {
1957 SLOGE("encrypted fs not yet mounted, aborting");
1958 return -1;
1959 }
1960
1961 if (!saved_mount_point) {
1962 SLOGE("encrypted fs failed to save mount point, aborting");
1963 return -1;
1964 }
1965
Ken Sumrall160b4d62013-04-22 12:15:39 -07001966 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001967 SLOGE("Error getting crypt footer and key\n");
1968 return -1;
1969 }
1970
1971 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1972 /* If the device has no password, then just say the password is valid */
1973 rc = 0;
1974 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001975 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001976 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1977 /* They match, the password is correct */
1978 rc = 0;
1979 } else {
1980 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1981 sleep(1);
1982 rc = 1;
1983 }
1984 }
1985
1986 return rc;
1987}
1988
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001989/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08001990 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001991 * Presumably, at a minimum, the caller will update the
1992 * filesystem size and crypto_type_name after calling this function.
1993 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001994static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001995 off64_t off;
1996
1997 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001998 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001999 ftr->major_version = CURRENT_MAJOR_VERSION;
2000 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002001 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002002 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002003
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002004 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002005 case 1:
2006 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2007 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002008
Paul Crowley14c8c072018-09-18 13:30:21 -07002009 case 0:
2010 ftr->kdf_type = KDF_SCRYPT;
2011 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002012
Paul Crowley14c8c072018-09-18 13:30:21 -07002013 default:
2014 SLOGE("keymaster_check_compatibility failed");
2015 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002016 }
2017
Kenny Rootc4c70f12013-06-14 12:11:38 -07002018 get_device_scrypt_params(ftr);
2019
Ken Sumrall160b4d62013-04-22 12:15:39 -07002020 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2021 if (get_crypt_ftr_info(NULL, &off) == 0) {
2022 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002023 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002024 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002025
2026 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002027}
2028
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002029#define FRAMEWORK_BOOT_WAIT 60
2030
Paul Crowley14c8c072018-09-18 13:30:21 -07002031static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2032 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002033 if (fd == -1) {
2034 SLOGE("Error opening file %s", filename);
2035 return -1;
2036 }
2037
2038 char block[CRYPT_INPLACE_BUFSIZE];
2039 memset(block, 0, sizeof(block));
2040 if (unix_read(fd, block, sizeof(block)) < 0) {
2041 SLOGE("Error reading file %s", filename);
2042 close(fd);
2043 return -1;
2044 }
2045
2046 close(fd);
2047
2048 SHA256_CTX c;
2049 SHA256_Init(&c);
2050 SHA256_Update(&c, block, sizeof(block));
2051 SHA256_Final(buf, &c);
2052
2053 return 0;
2054}
2055
Paul Crowley81796e92020-02-07 11:27:49 -08002056static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2057 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002058 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002059 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002060
Paul Lawrence87999172014-02-20 12:21:31 -08002061 /* The size of the userdata partition, and add in the vold volumes below */
2062 tot_encryption_size = crypt_ftr->fs_size;
2063
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002064 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002065 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002066
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002067 if (rc == ENABLE_INPLACE_ERR_DEV) {
2068 /* Hack for b/17898962 */
2069 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2070 cryptfs_reboot(RebootType::reboot);
2071 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002072
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002073 if (!rc) {
2074 crypt_ftr->encrypted_upto = cur_encryption_done;
2075 }
Paul Lawrence87999172014-02-20 12:21:31 -08002076
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002077 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2078 /* The inplace routine never actually sets the progress to 100% due
2079 * to the round down nature of integer division, so set it here */
2080 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002081 }
2082
2083 return rc;
2084}
2085
Paul Crowleyb64933a2017-10-31 08:25:55 -07002086static int vold_unmountAll(void) {
2087 VolumeManager* vm = VolumeManager::Instance();
2088 return vm->unmountAll();
2089}
2090
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002091int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002092 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002093 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002094 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002095 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002096 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002097 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002098 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002099 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002100 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002101 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002102 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002103 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002104 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002105 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002106
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002107 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002108 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2109 /* An encryption was underway and was interrupted */
2110 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2111 crypt_ftr.encrypted_upto = 0;
2112 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002113
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002114 /* At this point, we are in an inconsistent state. Until we successfully
2115 complete encryption, a reboot will leave us broken. So mark the
2116 encryption failed in case that happens.
2117 On successfully completing encryption, remove this flag */
2118 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002119
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002120 put_crypt_ftr_and_key(&crypt_ftr);
2121 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2122 if (!check_ftr_sha(&crypt_ftr)) {
2123 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2124 put_crypt_ftr_and_key(&crypt_ftr);
2125 goto error_unencrypted;
2126 }
2127
2128 /* Doing a reboot-encryption*/
2129 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2130 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2131 rebootEncryption = true;
2132 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002133 } else {
2134 // We don't want to accidentally reference invalid data.
2135 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002136 }
2137
2138 property_get("ro.crypto.state", encrypted_state, "");
2139 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2140 SLOGE("Device is already running encrypted, aborting");
2141 goto error_unencrypted;
2142 }
2143
Tom Cherry4c5bde22019-01-29 14:34:01 -08002144 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002145
Ken Sumrall3ed82362011-01-28 23:31:16 -08002146 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002147 uint64_t nr_sec;
2148 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002149 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002150 goto error_unencrypted;
2151 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002152
2153 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002154 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002155 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002156 fs_size_sec = get_fs_size(real_blkdev.c_str());
2157 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002158
Paul Lawrence87999172014-02-20 12:21:31 -08002159 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002160
2161 if (fs_size_sec > max_fs_size_sec) {
2162 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2163 goto error_unencrypted;
2164 }
2165 }
2166
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002167 /* Get a wakelock as this may take a while, and we don't want the
2168 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2169 * wants to keep the screen on, it can grab a full wakelock.
2170 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002171 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002172 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002173
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002174 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002175 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002176 */
2177 property_set("vold.decrypt", "trigger_shutdown_framework");
2178 SLOGD("Just asked init to shut down class main\n");
2179
Jeff Sharkey9c484982015-03-31 10:35:33 -07002180 /* Ask vold to unmount all devices that it manages */
2181 if (vold_unmountAll()) {
2182 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002183 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002184
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002185 /* no_ui means we are being called from init, not settings.
2186 Now we always reboot from settings, so !no_ui means reboot
2187 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002188 if (!no_ui) {
2189 /* Try fallback, which is to reboot and try there */
2190 onlyCreateHeader = true;
2191 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2192 if (breadcrumb == 0) {
2193 SLOGE("Failed to create breadcrumb file");
2194 goto error_shutting_down;
2195 }
2196 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002197 }
2198
2199 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002200 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002201 /* Now that /data is unmounted, we need to mount a tmpfs
2202 * /data, set a property saying we're doing inplace encryption,
2203 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002204 */
xzj7e38a3a2018-10-12 10:17:11 +08002205 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002206 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002207 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002208 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002209 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002210 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002211
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002212 /* restart the framework. */
2213 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002214 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002215
Ken Sumrall92736ef2012-10-17 20:57:14 -07002216 /* Ugh, shutting down the framework is not synchronous, so until it
2217 * can be fixed, this horrible hack will wait a moment for it all to
2218 * shut down before proceeding. Without it, some devices cannot
2219 * restart the graphics services.
2220 */
2221 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002222 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002223
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002224 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002225 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002226 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002227 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2228 goto error_shutting_down;
2229 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002230
Tom Cherry4c5bde22019-01-29 14:34:01 -08002231 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002232 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002233 } else {
2234 crypt_ftr.fs_size = nr_sec;
2235 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002236 /* At this point, we are in an inconsistent state. Until we successfully
2237 complete encryption, a reboot will leave us broken. So mark the
2238 encryption failed in case that happens.
2239 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002240 if (onlyCreateHeader) {
2241 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2242 } else {
2243 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2244 }
Paul Lawrence87999172014-02-20 12:21:31 -08002245 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002246 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002247 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002248
Paul Lawrence87999172014-02-20 12:21:31 -08002249 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002250 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2251 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002252 SLOGE("Cannot create encrypted master key\n");
2253 goto error_shutting_down;
2254 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002255
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002256 /* Replace scrypted intermediate key if we are preparing for a reboot */
2257 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002258 unsigned char fake_master_key[MAX_KEY_LEN];
2259 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002260 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002261 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2262 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002263 }
2264
Paul Lawrence87999172014-02-20 12:21:31 -08002265 /* Write the key to the end of the partition */
2266 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002267
Paul Lawrence87999172014-02-20 12:21:31 -08002268 /* If any persistent data has been remembered, save it.
2269 * If none, create a valid empty table and save that.
2270 */
2271 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002272 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2273 if (pdata) {
2274 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2275 persist_data = pdata;
2276 }
Paul Lawrence87999172014-02-20 12:21:31 -08002277 }
2278 if (persist_data) {
2279 save_persistent_data();
2280 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002281 }
2282
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002283 if (onlyCreateHeader) {
2284 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002285 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002286 }
2287
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002288 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002289 /* startup service classes main and late_start */
2290 property_set("vold.decrypt", "trigger_restart_min_framework");
2291 SLOGD("Just triggered restart_min_framework\n");
2292
2293 /* OK, the framework is restarted and will soon be showing a
2294 * progress bar. Time to setup an encrypted mapping, and
2295 * either write a new filesystem, or encrypt in place updating
2296 * the progress bar as we work.
2297 */
2298 }
2299
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002300 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002301 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002302 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002303
Paul Lawrence87999172014-02-20 12:21:31 -08002304 /* If we are continuing, check checksums match */
2305 rc = 0;
2306 if (previously_encrypted_upto) {
2307 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002308 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002309
Paul Crowley14c8c072018-09-18 13:30:21 -07002310 if (!rc &&
2311 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002312 SLOGE("Checksums do not match - trigger wipe");
2313 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002314 }
2315 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002316
Paul Lawrence87999172014-02-20 12:21:31 -08002317 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002318 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002319 previously_encrypted_upto);
2320 }
2321
2322 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002323 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002324 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002325 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002326 SLOGE("Error calculating checksum for continuing encryption");
2327 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002328 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002329 }
2330
2331 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002332 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002333
Paul Crowley14c8c072018-09-18 13:30:21 -07002334 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002335 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002336 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002337
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002338 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002339 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2340 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002341 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002342 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002343
Paul Lawrence6bfed202014-07-28 12:47:22 -07002344 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002345
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002346 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2347 char value[PROPERTY_VALUE_MAX];
2348 property_get("ro.crypto.state", value, "");
2349 if (!strcmp(value, "")) {
2350 /* default encryption - continue first boot sequence */
2351 property_set("ro.crypto.state", "encrypted");
2352 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002353 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002354 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2355 // Bring up cryptkeeper that will check the password and set it
2356 property_set("vold.decrypt", "trigger_shutdown_framework");
2357 sleep(2);
2358 property_set("vold.encrypt_progress", "");
2359 cryptfs_trigger_restart_min_framework();
2360 } else {
2361 cryptfs_check_passwd(DEFAULT_PASSWORD);
2362 cryptfs_restart_internal(1);
2363 }
2364 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002365 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002366 sleep(2); /* Give the UI a chance to show 100% progress */
2367 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002368 }
Paul Lawrence87999172014-02-20 12:21:31 -08002369 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002370 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002371 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002372 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002373 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002374 char value[PROPERTY_VALUE_MAX];
2375
Ken Sumrall319369a2012-06-27 16:30:18 -07002376 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002377 if (!strcmp(value, "1")) {
2378 /* wipe data if encryption failed */
2379 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002380 std::string err;
2381 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002382 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002383 if (!write_bootloader_message(options, &err)) {
2384 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002385 }
Josh Gaofec44372017-08-28 13:22:55 -07002386 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002387 } else {
2388 /* set property to trigger dialog */
2389 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002390 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002391 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002392 }
2393
Ken Sumrall3ed82362011-01-28 23:31:16 -08002394 /* hrm, the encrypt step claims success, but the reboot failed.
2395 * This should not happen.
2396 * Set the property and return. Hope the framework can deal with it.
2397 */
2398 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002399 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002400
2401error_unencrypted:
2402 property_set("vold.encrypt_progress", "error_not_encrypted");
2403 return -1;
2404
2405error_shutting_down:
2406 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2407 * but the framework is stopped and not restarted to show the error, so it's up to
2408 * vold to restart the system.
2409 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002410 SLOGE(
2411 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2412 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002413 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002414
2415 /* shouldn't get here */
2416 property_set("vold.encrypt_progress", "error_shutting_down");
2417 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002418}
2419
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002420int cryptfs_enable(int type, const char* passwd, int no_ui) {
2421 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002422}
2423
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002424int cryptfs_enable_default(int no_ui) {
2425 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002426}
2427
Paul Crowley14c8c072018-09-18 13:30:21 -07002428int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002429 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002430 SLOGE("cryptfs_changepw not valid for file encryption");
2431 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002432 }
2433
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002434 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002435 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002436
2437 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002438 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002439 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002440 return -1;
2441 }
2442
Paul Lawrencef4faa572014-01-29 13:31:03 -08002443 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2444 SLOGE("Invalid crypt_type %d", crypt_type);
2445 return -1;
2446 }
2447
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002448 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002449 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002450 SLOGE("Error getting crypt footer and key");
2451 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002452 }
2453
Paul Lawrencef4faa572014-01-29 13:31:03 -08002454 crypt_ftr.crypt_type = crypt_type;
2455
Paul Crowley14c8c072018-09-18 13:30:21 -07002456 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2457 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002458 if (rc) {
2459 SLOGE("Encrypt master key failed: %d", rc);
2460 return -1;
2461 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002462 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002463 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002464
2465 return 0;
2466}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002467
Rubin Xu85c01f92014-10-13 12:49:54 +01002468static unsigned int persist_get_max_entries(int encrypted) {
2469 struct crypt_mnt_ftr crypt_ftr;
2470 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002471
2472 /* If encrypted, use the values from the crypt_ftr, otherwise
2473 * use the values for the current spec.
2474 */
2475 if (encrypted) {
2476 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002477 /* Something is wrong, assume no space for entries */
2478 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002479 }
2480 dsize = crypt_ftr.persist_data_size;
2481 } else {
2482 dsize = CRYPT_PERSIST_DATA_SIZE;
2483 }
2484
Rubin Xuf83cc612018-10-09 16:13:38 +01002485 if (dsize > sizeof(struct crypt_persist_data)) {
2486 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2487 } else {
2488 return 0;
2489 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002490}
2491
Paul Crowley14c8c072018-09-18 13:30:21 -07002492static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002493 unsigned int i;
2494
2495 if (persist_data == NULL) {
2496 return -1;
2497 }
2498 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2499 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2500 /* We found it! */
2501 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2502 return 0;
2503 }
2504 }
2505
2506 return -1;
2507}
2508
Paul Crowley14c8c072018-09-18 13:30:21 -07002509static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002510 unsigned int i;
2511 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002512 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002513
2514 if (persist_data == NULL) {
2515 return -1;
2516 }
2517
Rubin Xu85c01f92014-10-13 12:49:54 +01002518 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002519
2520 num = persist_data->persist_valid_entries;
2521
2522 for (i = 0; i < num; i++) {
2523 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2524 /* We found an existing entry, update it! */
2525 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2526 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2527 return 0;
2528 }
2529 }
2530
2531 /* We didn't find it, add it to the end, if there is room */
2532 if (persist_data->persist_valid_entries < max_persistent_entries) {
2533 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2534 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2535 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2536 persist_data->persist_valid_entries++;
2537 return 0;
2538 }
2539
2540 return -1;
2541}
2542
Rubin Xu85c01f92014-10-13 12:49:54 +01002543/**
2544 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2545 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2546 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002547int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002548 std::string key_ = key;
2549 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002550
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002551 std::string parsed_field;
2552 unsigned parsed_index;
2553
2554 std::string::size_type split = key_.find_last_of('_');
2555 if (split == std::string::npos) {
2556 parsed_field = key_;
2557 parsed_index = 0;
2558 } else {
2559 parsed_field = key_.substr(0, split);
2560 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002561 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002562
2563 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002564}
2565
2566/*
2567 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2568 * remaining entries starting from index will be deleted.
2569 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2570 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2571 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2572 *
2573 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002574static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002575 unsigned int i;
2576 unsigned int j;
2577 unsigned int num;
2578
2579 if (persist_data == NULL) {
2580 return PERSIST_DEL_KEY_ERROR_OTHER;
2581 }
2582
2583 num = persist_data->persist_valid_entries;
2584
Paul Crowley14c8c072018-09-18 13:30:21 -07002585 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002586 // Filter out to-be-deleted entries in place.
2587 for (i = 0; i < num; i++) {
2588 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2589 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2590 j++;
2591 }
2592 }
2593
2594 if (j < num) {
2595 persist_data->persist_valid_entries = j;
2596 // Zeroise the remaining entries
2597 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2598 return PERSIST_DEL_KEY_OK;
2599 } else {
2600 // Did not find an entry matching the given fieldname
2601 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2602 }
2603}
2604
Paul Crowley14c8c072018-09-18 13:30:21 -07002605static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002606 unsigned int i;
2607 unsigned int count;
2608
2609 if (persist_data == NULL) {
2610 return -1;
2611 }
2612
2613 count = 0;
2614 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2615 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2616 count++;
2617 }
2618 }
2619
2620 return count;
2621}
2622
Ken Sumrall160b4d62013-04-22 12:15:39 -07002623/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002624int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002625 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002626 SLOGE("Cannot get field when file encrypted");
2627 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002628 }
2629
Ken Sumrall160b4d62013-04-22 12:15:39 -07002630 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002631 /* CRYPTO_GETFIELD_OK is success,
2632 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2633 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2634 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002635 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002636 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2637 int i;
2638 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002639
2640 if (persist_data == NULL) {
2641 load_persistent_data();
2642 if (persist_data == NULL) {
2643 SLOGE("Getfield error, cannot load persistent data");
2644 goto out;
2645 }
2646 }
2647
Rubin Xu85c01f92014-10-13 12:49:54 +01002648 // Read value from persistent entries. If the original value is split into multiple entries,
2649 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002650 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002651 // 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 -07002652 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002653 // value too small
2654 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2655 goto out;
2656 }
2657 rc = CRYPTO_GETFIELD_OK;
2658
2659 for (i = 1; /* break explicitly */; i++) {
2660 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002661 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002662 // If the fieldname is very long, we stop as soon as it begins to overflow the
2663 // maximum field length. At this point we have in fact fully read out the original
2664 // value because cryptfs_setfield would not allow fields with longer names to be
2665 // written in the first place.
2666 break;
2667 }
2668 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002669 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2670 // value too small.
2671 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2672 goto out;
2673 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002674 } else {
2675 // Exhaust all entries.
2676 break;
2677 }
2678 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002679 } else {
2680 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002681 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002682 }
2683
2684out:
2685 return rc;
2686}
2687
2688/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002689int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002690 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002691 SLOGE("Cannot set field when file encrypted");
2692 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002693 }
2694
Ken Sumrall160b4d62013-04-22 12:15:39 -07002695 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002696 /* 0 is success, negative values are error */
2697 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002698 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002699 unsigned int field_id;
2700 char temp_field[PROPERTY_KEY_MAX];
2701 unsigned int num_entries;
2702 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002703
2704 if (persist_data == NULL) {
2705 load_persistent_data();
2706 if (persist_data == NULL) {
2707 SLOGE("Setfield error, cannot load persistent data");
2708 goto out;
2709 }
2710 }
2711
2712 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002713 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002714 encrypted = 1;
2715 }
2716
Rubin Xu85c01f92014-10-13 12:49:54 +01002717 // Compute the number of entries required to store value, each entry can store up to
2718 // (PROPERTY_VALUE_MAX - 1) chars
2719 if (strlen(value) == 0) {
2720 // Empty value also needs one entry to store.
2721 num_entries = 1;
2722 } else {
2723 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2724 }
2725
2726 max_keylen = strlen(fieldname);
2727 if (num_entries > 1) {
2728 // Need an extra "_%d" suffix.
2729 max_keylen += 1 + log10(num_entries);
2730 }
2731 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2732 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002733 goto out;
2734 }
2735
Rubin Xu85c01f92014-10-13 12:49:54 +01002736 // Make sure we have enough space to write the new value
2737 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2738 persist_get_max_entries(encrypted)) {
2739 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2740 goto out;
2741 }
2742
2743 // Now that we know persist_data has enough space for value, let's delete the old field first
2744 // to make up space.
2745 persist_del_keys(fieldname, 0);
2746
2747 if (persist_set_key(fieldname, value, encrypted)) {
2748 // fail to set key, should not happen as we have already checked the available space
2749 SLOGE("persist_set_key() error during setfield()");
2750 goto out;
2751 }
2752
2753 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002754 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002755
2756 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2757 // fail to set key, should not happen as we have already checked the available space.
2758 SLOGE("persist_set_key() error during setfield()");
2759 goto out;
2760 }
2761 }
2762
Ken Sumrall160b4d62013-04-22 12:15:39 -07002763 /* If we are running encrypted, save the persistent data now */
2764 if (encrypted) {
2765 if (save_persistent_data()) {
2766 SLOGE("Setfield error, cannot save persistent data");
2767 goto out;
2768 }
2769 }
2770
Rubin Xu85c01f92014-10-13 12:49:54 +01002771 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002772
2773out:
2774 return rc;
2775}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002776
2777/* Checks userdata. Attempt to mount the volume if default-
2778 * encrypted.
2779 * On success trigger next init phase and return 0.
2780 * Currently do not handle failure - see TODO below.
2781 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002782int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002783 int crypt_type = cryptfs_get_password_type();
2784 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2785 SLOGE("Bad crypt type - error");
2786 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002787 SLOGD(
2788 "Password is not default - "
2789 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002790 property_set("vold.decrypt", "trigger_restart_min_framework");
2791 return 0;
2792 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2793 SLOGD("Password is default - restarting filesystem");
2794 cryptfs_restart_internal(0);
2795 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002796 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002797 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002798 }
2799
Paul Lawrence6bfed202014-07-28 12:47:22 -07002800 /** Corrupt. Allow us to boot into framework, which will detect bad
2801 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002802 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002803 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002804 return 0;
2805}
2806
2807/* Returns type of the password, default, pattern, pin or password.
2808 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002809int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002810 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002811 SLOGE("cryptfs_get_password_type not valid for file encryption");
2812 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002813 }
2814
Paul Lawrencef4faa572014-01-29 13:31:03 -08002815 struct crypt_mnt_ftr crypt_ftr;
2816
2817 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2818 SLOGE("Error getting crypt footer and key\n");
2819 return -1;
2820 }
2821
Paul Lawrence6bfed202014-07-28 12:47:22 -07002822 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2823 return -1;
2824 }
2825
Paul Lawrencef4faa572014-01-29 13:31:03 -08002826 return crypt_ftr.crypt_type;
2827}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002828
Paul Crowley14c8c072018-09-18 13:30:21 -07002829const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002830 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002831 SLOGE("cryptfs_get_password not valid for file encryption");
2832 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002833 }
2834
Paul Lawrence399317e2014-03-10 13:20:50 -07002835 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002836 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002837 if (now.tv_sec < password_expiry_time) {
2838 return password;
2839 } else {
2840 cryptfs_clear_password();
2841 return 0;
2842 }
2843}
2844
Paul Crowley14c8c072018-09-18 13:30:21 -07002845void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002846 if (password) {
2847 size_t len = strlen(password);
2848 memset(password, 0, len);
2849 free(password);
2850 password = 0;
2851 password_expiry_time = 0;
2852 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002853}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002854
Paul Crowley14c8c072018-09-18 13:30:21 -07002855int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002856 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2857 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002858}