blob: c2c593634eb4032af9e6a9066352c70714c7e777 [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>
Hyangseok Chae3cf32332020-02-27 18:21:50 +090035#include <android-base/strings.h>
Logan Chiend557d762018-05-02 11:36:45 +080036#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080037#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070039#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080040#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070042#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070043#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080044#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080045#include <logwrap/logwrap.h>
46#include <openssl/evp.h>
47#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070049#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080050
51#include <ctype.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <inttypes.h>
55#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080056#include <linux/kdev_t.h>
57#include <math.h>
Hyangseok Chae3cf32332020-02-27 18:21:50 +090058#include <mntent.h>
Logan Chiend557d762018-05-02 11:36:45 +080059#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080062#include <sys/mount.h>
63#include <sys/param.h>
64#include <sys/stat.h>
65#include <sys/types.h>
66#include <sys/wait.h>
67#include <time.h>
68#include <unistd.h>
69
Wei Wang4375f1b2017-02-24 17:43:01 -080070extern "C" {
71#include <crypto_scrypt.h>
72}
Mark Salyzyn3e971272014-01-21 13:27:04 -080073
Eric Biggersed45ec32019-01-25 10:47:55 -080074using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080075using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080076using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080077using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080078using android::vold::KeyBuffer;
Paul Crowley4eac2642020-02-12 11:04:05 -080079using android::vold::KeyGeneration;
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 Crowley4eac2642020-02-12 11:04:05 -0800326const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800327 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowley4eac2642020-02-12 11:04:05 -0800328}
329
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700330/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700331static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000332 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700333}
334
335/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700336static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800337 if (ftr->keymaster_blob_size) {
338 SLOGI("Already have key");
339 return 0;
340 }
341
Paul Crowley14c8c072018-09-18 13:30:21 -0700342 int rc = keymaster_create_key_for_cryptfs_scrypt(
343 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
344 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000345 if (rc) {
346 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800347 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000348 ftr->keymaster_blob_size = 0;
349 }
350 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700351 return -1;
352 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000353 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700354}
355
Shawn Willdene17a9c42014-09-08 13:04:08 -0600356/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700357static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
358 const size_t object_size, unsigned char** signature,
359 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600360 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600361 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600362 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600363
Shawn Willdene17a9c42014-09-08 13:04:08 -0600364 // To sign a message with RSA, the message must satisfy two
365 // constraints:
366 //
367 // 1. The message, when interpreted as a big-endian numeric value, must
368 // be strictly less than the public modulus of the RSA key. Note
369 // that because the most significant bit of the public modulus is
370 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
371 // key), an n-bit message with most significant bit 0 always
372 // satisfies this requirement.
373 //
374 // 2. The message must have the same length in bits as the public
375 // modulus of the RSA key. This requirement isn't mathematically
376 // necessary, but is necessary to ensure consistency in
377 // implementations.
378 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600379 case KDF_SCRYPT_KEYMASTER:
380 // This ensures the most significant byte of the signed message
381 // is zero. We could have zero-padded to the left instead, but
382 // this approach is slightly more robust against changes in
383 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600384 // so) because we really should be using a proper deterministic
385 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800386 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600387 SLOGI("Signing safely-padded object");
388 break;
389 default:
390 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000391 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600392 }
Paul Crowley73473332017-11-21 15:43:51 -0800393 for (;;) {
394 auto result = keymaster_sign_object_for_cryptfs_scrypt(
395 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
396 to_sign_size, signature, signature_size);
397 switch (result) {
398 case KeymasterSignResult::ok:
399 return 0;
400 case KeymasterSignResult::upgrade:
401 break;
402 default:
403 return -1;
404 }
405 SLOGD("Upgrading key");
406 if (keymaster_upgrade_key_for_cryptfs_scrypt(
407 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
408 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
409 &ftr->keymaster_blob_size) != 0) {
410 SLOGE("Failed to upgrade key");
411 return -1;
412 }
413 if (put_crypt_ftr_and_key(ftr) != 0) {
414 SLOGE("Failed to write upgraded key to disk");
415 }
416 SLOGD("Key upgraded successfully");
417 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600418}
419
Paul Lawrence399317e2014-03-10 13:20:50 -0700420/* Store password when userdata is successfully decrypted and mounted.
421 * Cleared by cryptfs_clear_password
422 *
423 * To avoid a double prompt at boot, we need to store the CryptKeeper
424 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
425 * Since the entire framework is torn down and rebuilt after encryption,
426 * we have to use a daemon or similar to store the password. Since vold
427 * is secured against IPC except from system processes, it seems a reasonable
428 * place to store this.
429 *
430 * password should be cleared once it has been used.
431 *
432 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800433 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700434static char* password = 0;
435static int password_expiry_time = 0;
436static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800437
Paul Crowley14c8c072018-09-18 13:30:21 -0700438enum class RebootType { reboot, recovery, shutdown };
439static void cryptfs_reboot(RebootType rt) {
440 switch (rt) {
441 case RebootType::reboot:
442 property_set(ANDROID_RB_PROPERTY, "reboot");
443 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800444
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 case RebootType::recovery:
446 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
447 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800448
Paul Crowley14c8c072018-09-18 13:30:21 -0700449 case RebootType::shutdown:
450 property_set(ANDROID_RB_PROPERTY, "shutdown");
451 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700452 }
Paul Lawrence87999172014-02-20 12:21:31 -0800453
Ken Sumralladfba362013-06-04 16:37:52 -0700454 sleep(20);
455
456 /* Shouldn't get here, reboot should happen before sleep times out */
457 return;
458}
459
Kenny Rootc4c70f12013-06-14 12:11:38 -0700460/**
461 * Gets the default device scrypt parameters for key derivation time tuning.
462 * The parameters should lead to about one second derivation time for the
463 * given device.
464 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700465static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700466 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000467 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700468
Paul Crowley63c18d32016-02-10 14:02:47 +0000469 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
470 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
471 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
472 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700473 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000474 ftr->N_factor = Nf;
475 ftr->r_factor = rf;
476 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700477}
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) {
1134 auto& dm = DeviceMapper::Instance();
1135 if (!dm.DeleteDevice(name)) {
1136 SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1137 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001138 }
David Andersonb9224732019-05-13 13:02:54 -07001139 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001140}
1141
Paul Crowley14c8c072018-09-18 13:30:21 -07001142static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1143 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001144 SLOGI("Using pbkdf2 for cryptfs KDF");
1145
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001147 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1148 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001149}
1150
Paul Crowley14c8c072018-09-18 13:30:21 -07001151static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001152 SLOGI("Using scrypt for cryptfs KDF");
1153
Paul Crowley14c8c072018-09-18 13:30:21 -07001154 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001155
1156 int N = 1 << ftr->N_factor;
1157 int r = 1 << ftr->r_factor;
1158 int p = 1 << ftr->p_factor;
1159
1160 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001161 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001162 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001163
Paul Crowley14c8c072018-09-18 13:30:21 -07001164 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001165}
1166
Paul Crowley14c8c072018-09-18 13:30:21 -07001167static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1168 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001169 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1170
1171 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001172 size_t signature_size;
1173 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001174 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001175
1176 int N = 1 << ftr->N_factor;
1177 int r = 1 << ftr->r_factor;
1178 int p = 1 << ftr->p_factor;
1179
Paul Crowley14c8c072018-09-18 13:30:21 -07001180 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001181 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001182
1183 if (rc) {
1184 SLOGE("scrypt failed");
1185 return -1;
1186 }
1187
Paul Crowley14c8c072018-09-18 13:30:21 -07001188 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001189 SLOGE("Signing failed");
1190 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001191 }
1192
Paul Crowley14c8c072018-09-18 13:30:21 -07001193 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1194 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001195 free(signature);
1196
1197 if (rc) {
1198 SLOGE("scrypt failed");
1199 return -1;
1200 }
1201
1202 return 0;
1203}
1204
Paul Crowley14c8c072018-09-18 13:30:21 -07001205static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1206 const unsigned char* decrypted_master_key,
1207 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1208 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001209 EVP_CIPHER_CTX e_ctx;
1210 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001211 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001212
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001213 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001214 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001215
1216 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001217 case KDF_SCRYPT_KEYMASTER:
1218 if (keymaster_create_key(crypt_ftr)) {
1219 SLOGE("keymaster_create_key failed");
1220 return -1;
1221 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001222
Paul Crowley14c8c072018-09-18 13:30:21 -07001223 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1224 SLOGE("scrypt failed");
1225 return -1;
1226 }
1227 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001228
Paul Crowley14c8c072018-09-18 13:30:21 -07001229 case KDF_SCRYPT:
1230 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1231 SLOGE("scrypt failed");
1232 return -1;
1233 }
1234 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001235
Paul Crowley14c8c072018-09-18 13:30:21 -07001236 default:
1237 SLOGE("Invalid kdf_type");
1238 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001239 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001240
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001241 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001242 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001243 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1244 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001245 SLOGE("EVP_EncryptInit failed\n");
1246 return -1;
1247 }
1248 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001249
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001251 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1252 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001253 SLOGE("EVP_EncryptUpdate failed\n");
1254 return -1;
1255 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001256 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001257 SLOGE("EVP_EncryptFinal failed\n");
1258 return -1;
1259 }
1260
Greg Kaiser59ad0182018-02-16 13:01:36 -08001261 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001262 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1263 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001264 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001265
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001266 /* Store the scrypt of the intermediate key, so we can validate if it's a
1267 password error or mount error when things go wrong.
1268 Note there's no need to check for errors, since if this is incorrect, we
1269 simply won't wipe userdata, which is the correct default behavior
1270 */
1271 int N = 1 << crypt_ftr->N_factor;
1272 int r = 1 << crypt_ftr->r_factor;
1273 int p = 1 << crypt_ftr->p_factor;
1274
Paul Crowley14c8c072018-09-18 13:30:21 -07001275 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1276 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001277 sizeof(crypt_ftr->scrypted_intermediate_key));
1278
1279 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001280 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001281 }
1282
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001283 EVP_CIPHER_CTX_cleanup(&e_ctx);
1284
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001285 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001286}
1287
Paul Crowley14c8c072018-09-18 13:30:21 -07001288static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1289 const unsigned char* encrypted_master_key, size_t keysize,
1290 unsigned char* decrypted_master_key, kdf_func kdf,
1291 void* kdf_params, unsigned char** intermediate_key,
1292 size_t* intermediate_key_size) {
1293 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1294 EVP_CIPHER_CTX d_ctx;
1295 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296
Paul Crowley14c8c072018-09-18 13:30:21 -07001297 /* Turn the password into an intermediate key and IV that can decrypt the
1298 master key */
1299 if (kdf(passwd, salt, ikey, kdf_params)) {
1300 SLOGE("kdf failed");
1301 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001302 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001303
Paul Crowley14c8c072018-09-18 13:30:21 -07001304 /* Initialize the decryption engine */
1305 EVP_CIPHER_CTX_init(&d_ctx);
1306 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1307 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1308 return -1;
1309 }
1310 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1311 /* Decrypt the master key */
1312 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1313 keysize)) {
1314 return -1;
1315 }
1316 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1317 return -1;
1318 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001319
Paul Crowley14c8c072018-09-18 13:30:21 -07001320 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1321 return -1;
1322 }
1323
1324 /* Copy intermediate key if needed by params */
1325 if (intermediate_key && intermediate_key_size) {
1326 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1327 if (*intermediate_key) {
1328 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1329 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1330 }
1331 }
1332
1333 EVP_CIPHER_CTX_cleanup(&d_ctx);
1334
1335 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001336}
1337
Paul Crowley14c8c072018-09-18 13:30:21 -07001338static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001339 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001340 *kdf = scrypt_keymaster;
1341 *kdf_params = ftr;
1342 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001343 *kdf = scrypt;
1344 *kdf_params = ftr;
1345 } else {
1346 *kdf = pbkdf2;
1347 *kdf_params = NULL;
1348 }
1349}
1350
Paul Crowley14c8c072018-09-18 13:30:21 -07001351static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1352 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1353 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001354 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001355 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001356 int ret;
1357
1358 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001359 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1360 decrypted_master_key, kdf, kdf_params, intermediate_key,
1361 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001362 if (ret != 0) {
1363 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001364 }
1365
1366 return ret;
1367}
1368
Paul Crowley14c8c072018-09-18 13:30:21 -07001369static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1370 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001371 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001372
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001373 /* Get some random bits for a key and salt */
1374 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1375 return -1;
1376 }
1377 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1378 return -1;
1379 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001380
1381 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001382 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001383}
1384
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001385static void ensure_subdirectory_unmounted(const char *prefix) {
1386 std::vector<std::string> umount_points;
1387 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1388 if (!mnts) {
1389 SLOGW("could not read mount files");
1390 return;
1391 }
1392
1393 //Find sudirectory mount point
1394 mntent* mentry;
1395 std::string top_directory(prefix);
1396 if (!android::base::EndsWith(prefix, "/")) {
1397 top_directory = top_directory + "/";
1398 }
1399 while ((mentry = getmntent(mnts.get())) != nullptr) {
1400 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1401 continue;
1402 }
1403
1404 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1405 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1406 umount_points.push_back(mentry->mnt_dir);
1407 }
1408 }
1409
1410 //Sort by path length to umount longest path first
1411 std::sort(std::begin(umount_points), std::end(umount_points),
1412 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1413
1414 for (std::string& mount_point : umount_points) {
1415 umount(mount_point.c_str());
1416 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1417 }
1418}
1419
Paul Crowley73be12d2020-02-03 12:22:03 -08001420static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001421 int i, err, rc;
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001422
1423 // Subdirectory mount will cause a failure of umount.
1424 ensure_subdirectory_unmounted(mountpoint);
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001425#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426
1427 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001428 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001429 if (umount(mountpoint) == 0) {
1430 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001432
1433 if (errno == EINVAL) {
1434 /* EINVAL is returned if the directory is not a mountpoint,
1435 * i.e. there is no filesystem mounted there. So just get out.
1436 */
1437 break;
1438 }
1439
1440 err = errno;
1441
1442 /* If allowed, be increasingly aggressive before the last two retries */
1443 if (kill) {
1444 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1445 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001446 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001447 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1448 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001449 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001450 }
1451 }
1452
1453 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001454 }
1455
1456 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001457 SLOGD("unmounting %s succeeded\n", mountpoint);
1458 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001459 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001460 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1461 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1462 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001463 }
1464
1465 return rc;
1466}
1467
Paul Crowley14c8c072018-09-18 13:30:21 -07001468static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001469 // NOTE: post_fs_data results in init calling back around to vold, so all
1470 // callers to this method must be async
1471
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001472 /* Do the prep of the /data filesystem */
1473 property_set("vold.post_fs_data_done", "0");
1474 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001475 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001476
Ken Sumrallc5872692013-05-14 15:26:31 -07001477 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001478 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001479 /* We timed out to prep /data in time. Continue wait. */
1480 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001481 }
Wei Wang42e38102017-06-07 10:46:12 -07001482 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001483}
1484
Paul Crowley14c8c072018-09-18 13:30:21 -07001485static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001486 // Mark the footer as bad
1487 struct crypt_mnt_ftr crypt_ftr;
1488 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1489 SLOGE("Failed to get crypto footer - panic");
1490 return;
1491 }
1492
1493 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1494 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1495 SLOGE("Failed to set crypto footer - panic");
1496 return;
1497 }
1498}
1499
Paul Crowley14c8c072018-09-18 13:30:21 -07001500static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001501 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001502 SLOGE("Failed to mount tmpfs on data - panic");
1503 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001504 }
1505
1506 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1507 SLOGE("Failed to trigger post fs data - panic");
1508 return;
1509 }
1510
1511 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1512 SLOGE("Failed to trigger restart min framework - panic");
1513 return;
1514 }
1515}
1516
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001517/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001518static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001519 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001520 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001521 static int restart_successful = 0;
1522
1523 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001524 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001525 SLOGE("Encrypted filesystem not validated, aborting");
1526 return -1;
1527 }
1528
1529 if (restart_successful) {
1530 SLOGE("System already restarted with encrypted disk, aborting");
1531 return -1;
1532 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001533
Paul Lawrencef4faa572014-01-29 13:31:03 -08001534 if (restart_main) {
1535 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001536 * start all services in one of these classes: core, early_hal, hal,
1537 * main and late_start. To get to the minimal UI for PIN entry, we
1538 * need to start core, early_hal, hal and main. When we want to
1539 * shutdown the framework again, we need to stop most of the services in
1540 * these classes, but only those services that were started after
1541 * /data was mounted. This excludes critical services like vold and
1542 * ueventd, which need to keep running. We could possible stop
1543 * even fewer services, but because we want services to pick up APEX
1544 * libraries from the real /data, restarting is better, as it makes
1545 * these devices consistent with FBE devices and lets them use the
1546 * most recent code.
1547 *
1548 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001549 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001550 * We then restart the class core, hal, main, and also the class
1551 * late_start.
1552 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001553 * At the moment, I've only put a few things in late_start that I know
1554 * are not needed to bring up the framework, and that also cause problems
1555 * with unmounting the tmpfs /data, but I hope to add add more services
1556 * to the late_start class as we optimize this to decrease the delay
1557 * till the user is asked for the password to the filesystem.
1558 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001559
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001560 /* The init files are setup to stop the right set of services when
1561 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001562 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001563 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001564 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565
Paul Lawrencef4faa572014-01-29 13:31:03 -08001566 /* Ugh, shutting down the framework is not synchronous, so until it
1567 * can be fixed, this horrible hack will wait a moment for it all to
1568 * shut down before proceeding. Without it, some devices cannot
1569 * restart the graphics services.
1570 */
1571 sleep(2);
1572 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001573
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001574 /* Now that the framework is shutdown, we should be able to umount()
1575 * the tmpfs filesystem, and mount the real one.
1576 */
1577
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001578 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1579 if (strlen(crypto_blkdev) == 0) {
1580 SLOGE("fs_crypto_blkdev not set\n");
1581 return -1;
1582 }
1583
Paul Crowley14c8c072018-09-18 13:30:21 -07001584 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001585 /* If ro.crypto.readonly is set to 1, mount the decrypted
1586 * filesystem readonly. This is used when /data is mounted by
1587 * recovery mode.
1588 */
1589 char ro_prop[PROPERTY_VALUE_MAX];
1590 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001591 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001592 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1593 if (entry != nullptr) {
1594 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001595 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001596 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001597
Ken Sumralle5032c42012-04-01 23:58:44 -07001598 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001599 int retries = RETRY_MOUNT_ATTEMPTS;
1600 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001601
1602 /*
1603 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1604 * partitions in the fsck domain.
1605 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001606 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001607 SLOGE("Failed to setexeccon");
1608 return -1;
1609 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001610 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001611 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Paul Lawrence3fe93112020-06-12 08:12:48 -07001612 needs_cp, false)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001613 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1614 /* TODO: invoke something similar to
1615 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1616 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001617 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001618 if (--retries) {
1619 sleep(RETRY_MOUNT_DELAY_SECONDS);
1620 } else {
1621 /* Let's hope that a reboot clears away whatever is keeping
1622 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001623 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001624 }
1625 } else {
1626 SLOGE("Failed to mount decrypted data");
1627 cryptfs_set_corrupt();
1628 cryptfs_trigger_restart_min_framework();
1629 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001630 if (setexeccon(NULL)) {
1631 SLOGE("Failed to setexeccon");
1632 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001633 return -1;
1634 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001635 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001636 if (setexeccon(NULL)) {
1637 SLOGE("Failed to setexeccon");
1638 return -1;
1639 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001640
Ken Sumralle5032c42012-04-01 23:58:44 -07001641 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001642 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001643 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001644
1645 /* startup service classes main and late_start */
1646 property_set("vold.decrypt", "trigger_restart_framework");
1647 SLOGD("Just triggered restart_framework\n");
1648
1649 /* Give it a few moments to get started */
1650 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001651 }
1652
Ken Sumrall0cc16632011-01-18 20:32:26 -08001653 if (rc == 0) {
1654 restart_successful = 1;
1655 }
1656
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001657 return rc;
1658}
1659
Paul Crowley14c8c072018-09-18 13:30:21 -07001660int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001661 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001662 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001663 SLOGE("cryptfs_restart not valid for file encryption:");
1664 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001665 }
1666
Paul Lawrencef4faa572014-01-29 13:31:03 -08001667 /* Call internal implementation forcing a restart of main service group */
1668 return cryptfs_restart_internal(1);
1669}
1670
Paul Crowley14c8c072018-09-18 13:30:21 -07001671static int do_crypto_complete(const char* mount_point) {
1672 struct crypt_mnt_ftr crypt_ftr;
1673 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001674
Paul Crowley14c8c072018-09-18 13:30:21 -07001675 property_get("ro.crypto.state", encrypted_state, "");
1676 if (strcmp(encrypted_state, "encrypted")) {
1677 SLOGE("not running with encryption, aborting");
1678 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001679 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680
Paul Crowley14c8c072018-09-18 13:30:21 -07001681 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001682 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001683 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1684 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685
Paul Crowley14c8c072018-09-18 13:30:21 -07001686 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001687 std::string key_loc;
1688 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001689
Paul Crowley14c8c072018-09-18 13:30:21 -07001690 /*
1691 * Only report this error if key_loc is a file and it exists.
1692 * If the device was never encrypted, and /data is not mountable for
1693 * some reason, returning 1 should prevent the UI from presenting the
1694 * a "enter password" screen, or worse, a "press button to wipe the
1695 * device" screen.
1696 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001697 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001698 SLOGE("master key file does not exist, aborting");
1699 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1700 } else {
1701 SLOGE("Error getting crypt footer and key\n");
1702 return CRYPTO_COMPLETE_BAD_METADATA;
1703 }
1704 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001705
Paul Crowley14c8c072018-09-18 13:30:21 -07001706 // Test for possible error flags
1707 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1708 SLOGE("Encryption process is partway completed\n");
1709 return CRYPTO_COMPLETE_PARTIAL;
1710 }
1711
1712 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1713 SLOGE("Encryption process was interrupted but cannot continue\n");
1714 return CRYPTO_COMPLETE_INCONSISTENT;
1715 }
1716
1717 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1718 SLOGE("Encryption is successful but data is corrupt\n");
1719 return CRYPTO_COMPLETE_CORRUPT;
1720 }
1721
1722 /* We passed the test! We shall diminish, and return to the west */
1723 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001724}
1725
Paul Crowley14c8c072018-09-18 13:30:21 -07001726static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1727 const char* mount_point, const char* label) {
1728 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001729 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001730 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001731 char tmp_mount_point[64];
1732 unsigned int orig_failed_decrypt_count;
1733 int rc;
1734 int use_keymaster = 0;
1735 int upgrade = 0;
1736 unsigned char* intermediate_key = 0;
1737 size_t intermediate_key_size = 0;
1738 int N = 1 << crypt_ftr->N_factor;
1739 int r = 1 << crypt_ftr->r_factor;
1740 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001741
Paul Crowley14c8c072018-09-18 13:30:21 -07001742 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1743 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001744
Paul Crowley14c8c072018-09-18 13:30:21 -07001745 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1746 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1747 &intermediate_key_size)) {
1748 SLOGE("Failed to decrypt master key\n");
1749 rc = -1;
1750 goto errout;
1751 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001752 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001753
Tom Cherry4c5bde22019-01-29 14:34:01 -08001754 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001755
Paul Crowley14c8c072018-09-18 13:30:21 -07001756 // Create crypto block device - all (non fatal) code paths
1757 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001758 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001759 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001760 SLOGE("Error creating decrypted block device\n");
1761 rc = -1;
1762 goto errout;
1763 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001764
Paul Crowley14c8c072018-09-18 13:30:21 -07001765 /* Work out if the problem is the password or the data */
1766 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001767
Paul Crowley14c8c072018-09-18 13:30:21 -07001768 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1769 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1770 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001771
Paul Crowley14c8c072018-09-18 13:30:21 -07001772 // Does the key match the crypto footer?
1773 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1774 sizeof(scrypted_intermediate_key)) == 0) {
1775 SLOGI("Password matches");
1776 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001777 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001778 /* Try mounting the file system anyway, just in case the problem's with
1779 * the footer, not the key. */
1780 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1781 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001782 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1783 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001784 SLOGE("Error temp mounting decrypted block device\n");
1785 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001786
Paul Crowley14c8c072018-09-18 13:30:21 -07001787 rc = ++crypt_ftr->failed_decrypt_count;
1788 put_crypt_ftr_and_key(crypt_ftr);
1789 } else {
1790 /* Success! */
1791 SLOGI("Password did not match but decrypted drive mounted - continue");
1792 umount(tmp_mount_point);
1793 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001794 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001795 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001796
Paul Crowley14c8c072018-09-18 13:30:21 -07001797 if (rc == 0) {
1798 crypt_ftr->failed_decrypt_count = 0;
1799 if (orig_failed_decrypt_count != 0) {
1800 put_crypt_ftr_and_key(crypt_ftr);
1801 }
1802
1803 /* Save the name of the crypto block device
1804 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001805 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001806
1807 /* Also save a the master key so we can reencrypted the key
1808 * the key when we want to change the password on it. */
1809 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1810 saved_mount_point = strdup(mount_point);
1811 master_key_saved = 1;
1812 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1813 rc = 0;
1814
1815 // Upgrade if we're not using the latest KDF.
1816 use_keymaster = keymaster_check_compatibility();
1817 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1818 // Don't allow downgrade
1819 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1820 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1821 upgrade = 1;
1822 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1823 crypt_ftr->kdf_type = KDF_SCRYPT;
1824 upgrade = 1;
1825 }
1826
1827 if (upgrade) {
1828 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1829 crypt_ftr->master_key, crypt_ftr);
1830 if (!rc) {
1831 rc = put_crypt_ftr_and_key(crypt_ftr);
1832 }
1833 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1834
1835 // Do not fail even if upgrade failed - machine is bootable
1836 // Note that if this code is ever hit, there is a *serious* problem
1837 // since KDFs should never fail. You *must* fix the kdf before
1838 // proceeding!
1839 if (rc) {
1840 SLOGW(
1841 "Upgrade failed with error %d,"
1842 " but continuing with previous state",
1843 rc);
1844 rc = 0;
1845 }
1846 }
1847 }
1848
1849errout:
1850 if (intermediate_key) {
1851 memset(intermediate_key, 0, intermediate_key_size);
1852 free(intermediate_key);
1853 }
1854 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001855}
1856
Ken Sumrall29d8da82011-05-18 17:20:07 -07001857/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001858 * Called by vold when it's asked to mount an encrypted external
1859 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001860 * as any metadata is been stored in a separate, small partition. We
1861 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001862 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001863int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001864 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001865 auto crypto_type = get_crypto_type();
1866 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001867 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001868 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001869 return -1;
1870 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001871 uint64_t nr_sec = 0;
1872 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001873 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001874 return -1;
1875 }
1876
Jeff Sharkey9c484982015-03-31 10:35:33 -07001877 struct crypt_mnt_ftr ext_crypt_ftr;
1878 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1879 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001880 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1881 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001882 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001883 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001884 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001885 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1886 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001887
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001888 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1889 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001890}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001891
Paul Crowley14c8c072018-09-18 13:30:21 -07001892int cryptfs_crypto_complete(void) {
1893 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001894}
1895
Paul Crowley14c8c072018-09-18 13:30:21 -07001896int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001897 char encrypted_state[PROPERTY_VALUE_MAX];
1898 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001899 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1900 SLOGE(
1901 "encrypted fs already validated or not running with encryption,"
1902 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001903 return -1;
1904 }
1905
1906 if (get_crypt_ftr_and_key(crypt_ftr)) {
1907 SLOGE("Error getting crypt footer and key");
1908 return -1;
1909 }
1910
1911 return 0;
1912}
1913
Paul Crowley14c8c072018-09-18 13:30:21 -07001914int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001915 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001916 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001917 SLOGE("cryptfs_check_passwd not valid for file encryption");
1918 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001919 }
1920
Paul Lawrencef4faa572014-01-29 13:31:03 -08001921 struct crypt_mnt_ftr crypt_ftr;
1922 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001923
Paul Lawrencef4faa572014-01-29 13:31:03 -08001924 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001925 if (rc) {
1926 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001927 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001928 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001929
Paul Crowley14c8c072018-09-18 13:30:21 -07001930 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001931 if (rc) {
1932 SLOGE("Password did not match");
1933 return rc;
1934 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001935
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001936 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1937 // Here we have a default actual password but a real password
1938 // we must test against the scrypted value
1939 // First, we must delete the crypto block device that
1940 // test_mount_encrypted_fs leaves behind as a side effect
1941 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001942 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1943 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001944 if (rc) {
1945 SLOGE("Default password did not match on reboot encryption");
1946 return rc;
1947 }
1948
1949 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1950 put_crypt_ftr_and_key(&crypt_ftr);
1951 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1952 if (rc) {
1953 SLOGE("Could not change password on reboot encryption");
1954 return rc;
1955 }
1956 }
1957
1958 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001959 cryptfs_clear_password();
1960 password = strdup(passwd);
1961 struct timespec now;
1962 clock_gettime(CLOCK_BOOTTIME, &now);
1963 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001964 }
1965
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001966 return rc;
1967}
1968
Paul Crowley14c8c072018-09-18 13:30:21 -07001969int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001970 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001971 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001972 char encrypted_state[PROPERTY_VALUE_MAX];
1973 int rc;
1974
1975 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001976 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001977 SLOGE("device not encrypted, aborting");
1978 return -2;
1979 }
1980
1981 if (!master_key_saved) {
1982 SLOGE("encrypted fs not yet mounted, aborting");
1983 return -1;
1984 }
1985
1986 if (!saved_mount_point) {
1987 SLOGE("encrypted fs failed to save mount point, aborting");
1988 return -1;
1989 }
1990
Ken Sumrall160b4d62013-04-22 12:15:39 -07001991 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001992 SLOGE("Error getting crypt footer and key\n");
1993 return -1;
1994 }
1995
1996 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1997 /* If the device has no password, then just say the password is valid */
1998 rc = 0;
1999 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002000 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002001 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2002 /* They match, the password is correct */
2003 rc = 0;
2004 } else {
2005 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2006 sleep(1);
2007 rc = 1;
2008 }
2009 }
2010
2011 return rc;
2012}
2013
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002014/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002015 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002016 * Presumably, at a minimum, the caller will update the
2017 * filesystem size and crypto_type_name after calling this function.
2018 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002019static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002020 off64_t off;
2021
2022 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002023 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002024 ftr->major_version = CURRENT_MAJOR_VERSION;
2025 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002026 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002027 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002028
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002029 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002030 case 1:
2031 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2032 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002033
Paul Crowley14c8c072018-09-18 13:30:21 -07002034 case 0:
2035 ftr->kdf_type = KDF_SCRYPT;
2036 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002037
Paul Crowley14c8c072018-09-18 13:30:21 -07002038 default:
2039 SLOGE("keymaster_check_compatibility failed");
2040 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002041 }
2042
Kenny Rootc4c70f12013-06-14 12:11:38 -07002043 get_device_scrypt_params(ftr);
2044
Ken Sumrall160b4d62013-04-22 12:15:39 -07002045 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2046 if (get_crypt_ftr_info(NULL, &off) == 0) {
2047 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002048 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002049 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002050
2051 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002052}
2053
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002054#define FRAMEWORK_BOOT_WAIT 60
2055
Paul Crowley14c8c072018-09-18 13:30:21 -07002056static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2057 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002058 if (fd == -1) {
2059 SLOGE("Error opening file %s", filename);
2060 return -1;
2061 }
2062
2063 char block[CRYPT_INPLACE_BUFSIZE];
2064 memset(block, 0, sizeof(block));
2065 if (unix_read(fd, block, sizeof(block)) < 0) {
2066 SLOGE("Error reading file %s", filename);
2067 close(fd);
2068 return -1;
2069 }
2070
2071 close(fd);
2072
2073 SHA256_CTX c;
2074 SHA256_Init(&c);
2075 SHA256_Update(&c, block, sizeof(block));
2076 SHA256_Final(buf, &c);
2077
2078 return 0;
2079}
2080
Paul Crowley81796e92020-02-07 11:27:49 -08002081static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2082 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002083 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002084 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002085
Paul Lawrence87999172014-02-20 12:21:31 -08002086 /* The size of the userdata partition, and add in the vold volumes below */
2087 tot_encryption_size = crypt_ftr->fs_size;
2088
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002089 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002090 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002091
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002092 if (rc == ENABLE_INPLACE_ERR_DEV) {
2093 /* Hack for b/17898962 */
2094 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2095 cryptfs_reboot(RebootType::reboot);
2096 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002097
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002098 if (!rc) {
2099 crypt_ftr->encrypted_upto = cur_encryption_done;
2100 }
Paul Lawrence87999172014-02-20 12:21:31 -08002101
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002102 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2103 /* The inplace routine never actually sets the progress to 100% due
2104 * to the round down nature of integer division, so set it here */
2105 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002106 }
2107
2108 return rc;
2109}
2110
Paul Crowleyb64933a2017-10-31 08:25:55 -07002111static int vold_unmountAll(void) {
2112 VolumeManager* vm = VolumeManager::Instance();
2113 return vm->unmountAll();
2114}
2115
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002116int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002117 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002118 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002119 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002120 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002121 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002122 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002123 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002124 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002125 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002126 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002127 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002128 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002129 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002130 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002131
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002132 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002133 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2134 /* An encryption was underway and was interrupted */
2135 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2136 crypt_ftr.encrypted_upto = 0;
2137 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002138
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002139 /* At this point, we are in an inconsistent state. Until we successfully
2140 complete encryption, a reboot will leave us broken. So mark the
2141 encryption failed in case that happens.
2142 On successfully completing encryption, remove this flag */
2143 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002144
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002145 put_crypt_ftr_and_key(&crypt_ftr);
2146 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2147 if (!check_ftr_sha(&crypt_ftr)) {
2148 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2149 put_crypt_ftr_and_key(&crypt_ftr);
2150 goto error_unencrypted;
2151 }
2152
2153 /* Doing a reboot-encryption*/
2154 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2155 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2156 rebootEncryption = true;
2157 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002158 } else {
2159 // We don't want to accidentally reference invalid data.
2160 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002161 }
2162
2163 property_get("ro.crypto.state", encrypted_state, "");
2164 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2165 SLOGE("Device is already running encrypted, aborting");
2166 goto error_unencrypted;
2167 }
2168
Tom Cherry4c5bde22019-01-29 14:34:01 -08002169 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002170
Ken Sumrall3ed82362011-01-28 23:31:16 -08002171 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002172 uint64_t nr_sec;
2173 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002174 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002175 goto error_unencrypted;
2176 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002177
2178 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002179 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002180 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002181 fs_size_sec = get_fs_size(real_blkdev.c_str());
2182 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002183
Paul Lawrence87999172014-02-20 12:21:31 -08002184 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002185
2186 if (fs_size_sec > max_fs_size_sec) {
2187 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2188 goto error_unencrypted;
2189 }
2190 }
2191
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002192 /* Get a wakelock as this may take a while, and we don't want the
2193 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2194 * wants to keep the screen on, it can grab a full wakelock.
2195 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002196 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002197 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002198
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002199 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002200 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002201 */
2202 property_set("vold.decrypt", "trigger_shutdown_framework");
2203 SLOGD("Just asked init to shut down class main\n");
2204
Jeff Sharkey9c484982015-03-31 10:35:33 -07002205 /* Ask vold to unmount all devices that it manages */
2206 if (vold_unmountAll()) {
2207 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002208 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002210 /* no_ui means we are being called from init, not settings.
2211 Now we always reboot from settings, so !no_ui means reboot
2212 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002213 if (!no_ui) {
2214 /* Try fallback, which is to reboot and try there */
2215 onlyCreateHeader = true;
2216 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2217 if (breadcrumb == 0) {
2218 SLOGE("Failed to create breadcrumb file");
2219 goto error_shutting_down;
2220 }
2221 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002222 }
2223
2224 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002225 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002226 /* Now that /data is unmounted, we need to mount a tmpfs
2227 * /data, set a property saying we're doing inplace encryption,
2228 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002229 */
xzj7e38a3a2018-10-12 10:17:11 +08002230 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002231 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002232 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002233 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002234 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002235 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002236
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002237 /* restart the framework. */
2238 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002239 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002240
Ken Sumrall92736ef2012-10-17 20:57:14 -07002241 /* Ugh, shutting down the framework is not synchronous, so until it
2242 * can be fixed, this horrible hack will wait a moment for it all to
2243 * shut down before proceeding. Without it, some devices cannot
2244 * restart the graphics services.
2245 */
2246 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002247 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002248
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002249 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002250 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002251 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002252 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2253 goto error_shutting_down;
2254 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002255
Tom Cherry4c5bde22019-01-29 14:34:01 -08002256 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002257 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002258 } else {
2259 crypt_ftr.fs_size = nr_sec;
2260 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002261 /* At this point, we are in an inconsistent state. Until we successfully
2262 complete encryption, a reboot will leave us broken. So mark the
2263 encryption failed in case that happens.
2264 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002265 if (onlyCreateHeader) {
2266 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2267 } else {
2268 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2269 }
Paul Lawrence87999172014-02-20 12:21:31 -08002270 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002271 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002272 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002273
Paul Lawrence87999172014-02-20 12:21:31 -08002274 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002275 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2276 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002277 SLOGE("Cannot create encrypted master key\n");
2278 goto error_shutting_down;
2279 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002280
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002281 /* Replace scrypted intermediate key if we are preparing for a reboot */
2282 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002283 unsigned char fake_master_key[MAX_KEY_LEN];
2284 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002285 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002286 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2287 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002288 }
2289
Paul Lawrence87999172014-02-20 12:21:31 -08002290 /* Write the key to the end of the partition */
2291 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002292
Paul Lawrence87999172014-02-20 12:21:31 -08002293 /* If any persistent data has been remembered, save it.
2294 * If none, create a valid empty table and save that.
2295 */
2296 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002297 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2298 if (pdata) {
2299 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2300 persist_data = pdata;
2301 }
Paul Lawrence87999172014-02-20 12:21:31 -08002302 }
2303 if (persist_data) {
2304 save_persistent_data();
2305 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002306 }
2307
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002308 if (onlyCreateHeader) {
2309 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002310 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002311 }
2312
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002313 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002314 /* startup service classes main and late_start */
2315 property_set("vold.decrypt", "trigger_restart_min_framework");
2316 SLOGD("Just triggered restart_min_framework\n");
2317
2318 /* OK, the framework is restarted and will soon be showing a
2319 * progress bar. Time to setup an encrypted mapping, and
2320 * either write a new filesystem, or encrypt in place updating
2321 * the progress bar as we work.
2322 */
2323 }
2324
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002325 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002326 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002327 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002328
Paul Lawrence87999172014-02-20 12:21:31 -08002329 /* If we are continuing, check checksums match */
2330 rc = 0;
2331 if (previously_encrypted_upto) {
2332 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002333 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002334
Paul Crowley14c8c072018-09-18 13:30:21 -07002335 if (!rc &&
2336 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002337 SLOGE("Checksums do not match - trigger wipe");
2338 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002339 }
2340 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002341
Paul Lawrence87999172014-02-20 12:21:31 -08002342 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002343 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002344 previously_encrypted_upto);
2345 }
2346
2347 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002348 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002349 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002350 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002351 SLOGE("Error calculating checksum for continuing encryption");
2352 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002353 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002354 }
2355
2356 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002357 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002358
Paul Crowley14c8c072018-09-18 13:30:21 -07002359 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002360 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002361 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002362
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002363 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002364 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2365 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002366 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002367 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002368
Paul Lawrence6bfed202014-07-28 12:47:22 -07002369 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002370
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002371 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2372 char value[PROPERTY_VALUE_MAX];
2373 property_get("ro.crypto.state", value, "");
2374 if (!strcmp(value, "")) {
2375 /* default encryption - continue first boot sequence */
2376 property_set("ro.crypto.state", "encrypted");
2377 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002378 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002379 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2380 // Bring up cryptkeeper that will check the password and set it
2381 property_set("vold.decrypt", "trigger_shutdown_framework");
2382 sleep(2);
2383 property_set("vold.encrypt_progress", "");
2384 cryptfs_trigger_restart_min_framework();
2385 } else {
2386 cryptfs_check_passwd(DEFAULT_PASSWORD);
2387 cryptfs_restart_internal(1);
2388 }
2389 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002390 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002391 sleep(2); /* Give the UI a chance to show 100% progress */
2392 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002393 }
Paul Lawrence87999172014-02-20 12:21:31 -08002394 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002395 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002396 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002397 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002398 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002399 char value[PROPERTY_VALUE_MAX];
2400
Ken Sumrall319369a2012-06-27 16:30:18 -07002401 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002402 if (!strcmp(value, "1")) {
2403 /* wipe data if encryption failed */
2404 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002405 std::string err;
2406 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002407 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002408 if (!write_bootloader_message(options, &err)) {
2409 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002410 }
Josh Gaofec44372017-08-28 13:22:55 -07002411 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002412 } else {
2413 /* set property to trigger dialog */
2414 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002415 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002416 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002417 }
2418
Ken Sumrall3ed82362011-01-28 23:31:16 -08002419 /* hrm, the encrypt step claims success, but the reboot failed.
2420 * This should not happen.
2421 * Set the property and return. Hope the framework can deal with it.
2422 */
2423 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002424 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002425
2426error_unencrypted:
2427 property_set("vold.encrypt_progress", "error_not_encrypted");
2428 return -1;
2429
2430error_shutting_down:
2431 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2432 * but the framework is stopped and not restarted to show the error, so it's up to
2433 * vold to restart the system.
2434 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002435 SLOGE(
2436 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2437 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002438 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002439
2440 /* shouldn't get here */
2441 property_set("vold.encrypt_progress", "error_shutting_down");
2442 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002443}
2444
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002445int cryptfs_enable(int type, const char* passwd, int no_ui) {
2446 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002447}
2448
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002449int cryptfs_enable_default(int no_ui) {
2450 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002451}
2452
Paul Crowley14c8c072018-09-18 13:30:21 -07002453int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002454 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002455 SLOGE("cryptfs_changepw not valid for file encryption");
2456 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002457 }
2458
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002459 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002460 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002461
2462 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002463 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002464 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002465 return -1;
2466 }
2467
Paul Lawrencef4faa572014-01-29 13:31:03 -08002468 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2469 SLOGE("Invalid crypt_type %d", crypt_type);
2470 return -1;
2471 }
2472
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002473 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002474 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002475 SLOGE("Error getting crypt footer and key");
2476 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002477 }
2478
Paul Lawrencef4faa572014-01-29 13:31:03 -08002479 crypt_ftr.crypt_type = crypt_type;
2480
Paul Crowley14c8c072018-09-18 13:30:21 -07002481 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2482 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002483 if (rc) {
2484 SLOGE("Encrypt master key failed: %d", rc);
2485 return -1;
2486 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002487 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002488 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002489
2490 return 0;
2491}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002492
Rubin Xu85c01f92014-10-13 12:49:54 +01002493static unsigned int persist_get_max_entries(int encrypted) {
2494 struct crypt_mnt_ftr crypt_ftr;
2495 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002496
2497 /* If encrypted, use the values from the crypt_ftr, otherwise
2498 * use the values for the current spec.
2499 */
2500 if (encrypted) {
2501 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002502 /* Something is wrong, assume no space for entries */
2503 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002504 }
2505 dsize = crypt_ftr.persist_data_size;
2506 } else {
2507 dsize = CRYPT_PERSIST_DATA_SIZE;
2508 }
2509
Rubin Xuf83cc612018-10-09 16:13:38 +01002510 if (dsize > sizeof(struct crypt_persist_data)) {
2511 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2512 } else {
2513 return 0;
2514 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002515}
2516
Paul Crowley14c8c072018-09-18 13:30:21 -07002517static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002518 unsigned int i;
2519
2520 if (persist_data == NULL) {
2521 return -1;
2522 }
2523 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2524 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2525 /* We found it! */
2526 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2527 return 0;
2528 }
2529 }
2530
2531 return -1;
2532}
2533
Paul Crowley14c8c072018-09-18 13:30:21 -07002534static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002535 unsigned int i;
2536 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002537 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002538
2539 if (persist_data == NULL) {
2540 return -1;
2541 }
2542
Rubin Xu85c01f92014-10-13 12:49:54 +01002543 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002544
2545 num = persist_data->persist_valid_entries;
2546
2547 for (i = 0; i < num; i++) {
2548 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2549 /* We found an existing entry, update it! */
2550 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2551 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2552 return 0;
2553 }
2554 }
2555
2556 /* We didn't find it, add it to the end, if there is room */
2557 if (persist_data->persist_valid_entries < max_persistent_entries) {
2558 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2559 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2560 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2561 persist_data->persist_valid_entries++;
2562 return 0;
2563 }
2564
2565 return -1;
2566}
2567
Rubin Xu85c01f92014-10-13 12:49:54 +01002568/**
2569 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2570 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2571 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002572int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002573 std::string key_ = key;
2574 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002575
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002576 std::string parsed_field;
2577 unsigned parsed_index;
2578
2579 std::string::size_type split = key_.find_last_of('_');
2580 if (split == std::string::npos) {
2581 parsed_field = key_;
2582 parsed_index = 0;
2583 } else {
2584 parsed_field = key_.substr(0, split);
2585 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002586 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002587
2588 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002589}
2590
2591/*
2592 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2593 * remaining entries starting from index will be deleted.
2594 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2595 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2596 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2597 *
2598 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002599static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002600 unsigned int i;
2601 unsigned int j;
2602 unsigned int num;
2603
2604 if (persist_data == NULL) {
2605 return PERSIST_DEL_KEY_ERROR_OTHER;
2606 }
2607
2608 num = persist_data->persist_valid_entries;
2609
Paul Crowley14c8c072018-09-18 13:30:21 -07002610 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002611 // Filter out to-be-deleted entries in place.
2612 for (i = 0; i < num; i++) {
2613 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2614 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2615 j++;
2616 }
2617 }
2618
2619 if (j < num) {
2620 persist_data->persist_valid_entries = j;
2621 // Zeroise the remaining entries
2622 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2623 return PERSIST_DEL_KEY_OK;
2624 } else {
2625 // Did not find an entry matching the given fieldname
2626 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2627 }
2628}
2629
Paul Crowley14c8c072018-09-18 13:30:21 -07002630static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002631 unsigned int i;
2632 unsigned int count;
2633
2634 if (persist_data == NULL) {
2635 return -1;
2636 }
2637
2638 count = 0;
2639 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2640 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2641 count++;
2642 }
2643 }
2644
2645 return count;
2646}
2647
Ken Sumrall160b4d62013-04-22 12:15:39 -07002648/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002649int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002650 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002651 SLOGE("Cannot get field when file encrypted");
2652 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002653 }
2654
Ken Sumrall160b4d62013-04-22 12:15:39 -07002655 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002656 /* CRYPTO_GETFIELD_OK is success,
2657 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2658 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2659 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002660 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002661 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2662 int i;
2663 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002664
2665 if (persist_data == NULL) {
2666 load_persistent_data();
2667 if (persist_data == NULL) {
2668 SLOGE("Getfield error, cannot load persistent data");
2669 goto out;
2670 }
2671 }
2672
Rubin Xu85c01f92014-10-13 12:49:54 +01002673 // Read value from persistent entries. If the original value is split into multiple entries,
2674 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002675 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002676 // 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 -07002677 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002678 // value too small
2679 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2680 goto out;
2681 }
2682 rc = CRYPTO_GETFIELD_OK;
2683
2684 for (i = 1; /* break explicitly */; i++) {
2685 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002686 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002687 // If the fieldname is very long, we stop as soon as it begins to overflow the
2688 // maximum field length. At this point we have in fact fully read out the original
2689 // value because cryptfs_setfield would not allow fields with longer names to be
2690 // written in the first place.
2691 break;
2692 }
2693 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002694 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2695 // value too small.
2696 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2697 goto out;
2698 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002699 } else {
2700 // Exhaust all entries.
2701 break;
2702 }
2703 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002704 } else {
2705 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002706 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002707 }
2708
2709out:
2710 return rc;
2711}
2712
2713/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002714int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002715 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002716 SLOGE("Cannot set field when file encrypted");
2717 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002718 }
2719
Ken Sumrall160b4d62013-04-22 12:15:39 -07002720 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002721 /* 0 is success, negative values are error */
2722 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002723 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002724 unsigned int field_id;
2725 char temp_field[PROPERTY_KEY_MAX];
2726 unsigned int num_entries;
2727 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002728
2729 if (persist_data == NULL) {
2730 load_persistent_data();
2731 if (persist_data == NULL) {
2732 SLOGE("Setfield error, cannot load persistent data");
2733 goto out;
2734 }
2735 }
2736
2737 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002738 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002739 encrypted = 1;
2740 }
2741
Rubin Xu85c01f92014-10-13 12:49:54 +01002742 // Compute the number of entries required to store value, each entry can store up to
2743 // (PROPERTY_VALUE_MAX - 1) chars
2744 if (strlen(value) == 0) {
2745 // Empty value also needs one entry to store.
2746 num_entries = 1;
2747 } else {
2748 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2749 }
2750
2751 max_keylen = strlen(fieldname);
2752 if (num_entries > 1) {
2753 // Need an extra "_%d" suffix.
2754 max_keylen += 1 + log10(num_entries);
2755 }
2756 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2757 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002758 goto out;
2759 }
2760
Rubin Xu85c01f92014-10-13 12:49:54 +01002761 // Make sure we have enough space to write the new value
2762 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2763 persist_get_max_entries(encrypted)) {
2764 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2765 goto out;
2766 }
2767
2768 // Now that we know persist_data has enough space for value, let's delete the old field first
2769 // to make up space.
2770 persist_del_keys(fieldname, 0);
2771
2772 if (persist_set_key(fieldname, value, encrypted)) {
2773 // fail to set key, should not happen as we have already checked the available space
2774 SLOGE("persist_set_key() error during setfield()");
2775 goto out;
2776 }
2777
2778 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002779 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002780
2781 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2782 // fail to set key, should not happen as we have already checked the available space.
2783 SLOGE("persist_set_key() error during setfield()");
2784 goto out;
2785 }
2786 }
2787
Ken Sumrall160b4d62013-04-22 12:15:39 -07002788 /* If we are running encrypted, save the persistent data now */
2789 if (encrypted) {
2790 if (save_persistent_data()) {
2791 SLOGE("Setfield error, cannot save persistent data");
2792 goto out;
2793 }
2794 }
2795
Rubin Xu85c01f92014-10-13 12:49:54 +01002796 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002797
2798out:
2799 return rc;
2800}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002801
2802/* Checks userdata. Attempt to mount the volume if default-
2803 * encrypted.
2804 * On success trigger next init phase and return 0.
2805 * Currently do not handle failure - see TODO below.
2806 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002807int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002808 int crypt_type = cryptfs_get_password_type();
2809 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2810 SLOGE("Bad crypt type - error");
2811 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002812 SLOGD(
2813 "Password is not default - "
2814 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002815 property_set("vold.decrypt", "trigger_restart_min_framework");
2816 return 0;
2817 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2818 SLOGD("Password is default - restarting filesystem");
2819 cryptfs_restart_internal(0);
2820 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002821 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002822 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002823 }
2824
Paul Lawrence6bfed202014-07-28 12:47:22 -07002825 /** Corrupt. Allow us to boot into framework, which will detect bad
2826 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002827 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002828 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002829 return 0;
2830}
2831
2832/* Returns type of the password, default, pattern, pin or password.
2833 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002834int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002835 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002836 SLOGE("cryptfs_get_password_type not valid for file encryption");
2837 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002838 }
2839
Paul Lawrencef4faa572014-01-29 13:31:03 -08002840 struct crypt_mnt_ftr crypt_ftr;
2841
2842 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2843 SLOGE("Error getting crypt footer and key\n");
2844 return -1;
2845 }
2846
Paul Lawrence6bfed202014-07-28 12:47:22 -07002847 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2848 return -1;
2849 }
2850
Paul Lawrencef4faa572014-01-29 13:31:03 -08002851 return crypt_ftr.crypt_type;
2852}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002853
Paul Crowley14c8c072018-09-18 13:30:21 -07002854const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002855 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002856 SLOGE("cryptfs_get_password not valid for file encryption");
2857 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002858 }
2859
Paul Lawrence399317e2014-03-10 13:20:50 -07002860 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002861 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002862 if (now.tv_sec < password_expiry_time) {
2863 return password;
2864 } else {
2865 cryptfs_clear_password();
2866 return 0;
2867 }
2868}
2869
Paul Crowley14c8c072018-09-18 13:30:21 -07002870void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002871 if (password) {
2872 size_t len = strlen(password);
2873 memset(password, 0, len);
2874 free(password);
2875 password = 0;
2876 password_expiry_time = 0;
2877 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002878}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002879
Paul Crowley14c8c072018-09-18 13:30:21 -07002880int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002881 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2882 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002883}