blob: 1ddb34b2af21a9ed16e46de0af166e1985a40c6e [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
Martijn Coenen26ad7b32020-02-13 16:20:52 +010070#include <chrono>
71#include <thread>
72
Wei Wang4375f1b2017-02-24 17:43:01 -080073extern "C" {
74#include <crypto_scrypt.h>
75}
Mark Salyzyn3e971272014-01-21 13:27:04 -080076
Eric Biggersed45ec32019-01-25 10:47:55 -080077using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080078using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080079using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080080using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080081using android::vold::KeyBuffer;
Paul Crowleyb3d018a2020-02-12 11:04:05 -080082using android::vold::KeyGeneration;
David Andersonb9224732019-05-13 13:02:54 -070083using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070084using namespace std::chrono_literals;
85
Paul Crowley73be12d2020-02-03 12:22:03 -080086/* The current cryptfs version */
87#define CURRENT_MAJOR_VERSION 1
88#define CURRENT_MINOR_VERSION 3
89
90#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
91#define CRYPT_PERSIST_DATA_SIZE 0x1000
92
93#define MAX_CRYPTO_TYPE_NAME_LEN 64
94
95#define MAX_KEY_LEN 48
96#define SALT_LEN 16
97#define SCRYPT_LEN 32
98
99/* definitions of flags in the structure below */
100#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
101#define CRYPT_ENCRYPTION_IN_PROGRESS \
102 0x2 /* Encryption partially completed, \
103 encrypted_upto valid*/
104#define CRYPT_INCONSISTENT_STATE \
105 0x4 /* Set when starting encryption, clear when \
106 exit cleanly, either through success or \
107 correctly marked partial encryption */
108#define CRYPT_DATA_CORRUPT \
109 0x8 /* Set when encryption is fine, but the \
110 underlying volume is corrupt */
111#define CRYPT_FORCE_ENCRYPTION \
112 0x10 /* Set when it is time to encrypt this \
113 volume on boot. Everything in this \
114 structure is set up correctly as \
115 though device is encrypted except \
116 that the master key is encrypted with the \
117 default password. */
118#define CRYPT_FORCE_COMPLETE \
119 0x20 /* Set when the above encryption cycle is \
120 complete. On next cryptkeeper entry, match \
121 the password. If it matches fix the master \
122 key and remove this flag. */
123
124/* Allowed values for type in the structure below */
125#define CRYPT_TYPE_PASSWORD \
126 0 /* master_key is encrypted with a password \
127 * Must be zero to be compatible with pre-L \
128 * devices where type is always password.*/
129#define CRYPT_TYPE_DEFAULT \
130 1 /* master_key is encrypted with default \
131 * password */
132#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
133#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
134#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
135
136#define CRYPT_MNT_MAGIC 0xD0B5B1C4
137#define PERSIST_DATA_MAGIC 0xE950CD44
138
139/* Key Derivation Function algorithms */
140#define KDF_PBKDF2 1
141#define KDF_SCRYPT 2
142/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
143#define KDF_SCRYPT_KEYMASTER 5
144
145/* Maximum allowed keymaster blob size. */
146#define KEYMASTER_BLOB_SIZE 2048
147
148/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
149#define __le8 unsigned char
150
151#if !defined(SHA256_DIGEST_LENGTH)
152#define SHA256_DIGEST_LENGTH 32
153#endif
154
155/* This structure starts 16,384 bytes before the end of a hardware
156 * partition that is encrypted, or in a separate partition. It's location
157 * is specified by a property set in init.<device>.rc.
158 * The structure allocates 48 bytes for a key, but the real key size is
159 * specified in the struct. Currently, the code is hardcoded to use 128
160 * bit keys.
161 * The fields after salt are only valid in rev 1.1 and later stuctures.
162 * Obviously, the filesystem does not include the last 16 kbytes
163 * of the partition if the crypt_mnt_ftr lives at the end of the
164 * partition.
165 */
166
167struct crypt_mnt_ftr {
168 __le32 magic; /* See above */
169 __le16 major_version;
170 __le16 minor_version;
171 __le32 ftr_size; /* in bytes, not including key following */
172 __le32 flags; /* See above */
173 __le32 keysize; /* in bytes */
174 __le32 crypt_type; /* how master_key is encrypted. Must be a
175 * CRYPT_TYPE_XXX value */
176 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
177 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
178 mount, set to 0 on successful mount */
179 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
180 needed to decrypt this
181 partition, null terminated */
182 __le32 spare2; /* ignored */
183 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
184 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
185 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
186 * on device with that info, either the footer of the
187 * real_blkdevice or the metadata partition. */
188
189 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
190 * persistent data table*/
191
192 __le8 kdf_type; /* The key derivation function used. */
193
194 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
195 __le8 N_factor; /* (1 << N) */
196 __le8 r_factor; /* (1 << r) */
197 __le8 p_factor; /* (1 << p) */
198 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
199 we have to stop (e.g. power low) this is the last
200 encrypted 512 byte sector.*/
201 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
202 set, hash of first block, used
203 to validate before continuing*/
204
205 /* key_master key, used to sign the derived key which is then used to generate
206 * the intermediate key
207 * This key should be used for no other purposes! We use this key to sign unpadded
208 * data, which is acceptable but only if the key is not reused elsewhere. */
209 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
210 __le32 keymaster_blob_size;
211
212 /* Store scrypt of salted intermediate key. When decryption fails, we can
213 check if this matches, and if it does, we know that the problem is with the
214 drive, and there is no point in asking the user for more passwords.
215
216 Note that if any part of this structure is corrupt, this will not match and
217 we will continue to believe the user entered the wrong password. In that
218 case the only solution is for the user to enter a password enough times to
219 force a wipe.
220
221 Note also that there is no need to worry about migration. If this data is
222 wrong, we simply won't recognise a right password, and will continue to
223 prompt. On the first password change, this value will be populated and
224 then we will be OK.
225 */
226 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
227
228 /* sha of this structure with this element set to zero
229 Used when encrypting on reboot to validate structure before doing something
230 fatal
231 */
232 unsigned char sha256[SHA256_DIGEST_LENGTH];
233};
234
235/* Persistant data that should be available before decryption.
236 * Things like airplane mode, locale and timezone are kept
237 * here and can be retrieved by the CryptKeeper UI to properly
238 * configure the phone before asking for the password
239 * This is only valid if the major and minor version above
240 * is set to 1.1 or higher.
241 *
242 * This is a 4K structure. There are 2 copies, and the code alternates
243 * writing one and then clearing the previous one. The reading
244 * code reads the first valid copy it finds, based on the magic number.
245 * The absolute offset to the first of the two copies is kept in rev 1.1
246 * and higher crypt_mnt_ftr structures.
247 */
248struct crypt_persist_entry {
249 char key[PROPERTY_KEY_MAX];
250 char val[PROPERTY_VALUE_MAX];
251};
252
253/* Should be exactly 4K in size */
254struct crypt_persist_data {
255 __le32 persist_magic;
256 __le32 persist_valid_entries;
257 __le32 persist_spare[30];
258 struct crypt_persist_entry persist_entry[0];
259};
260
261static int wait_and_unmount(const char* mountpoint, bool kill);
262
263typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
264 void* params);
265
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800266#define UNUSED __attribute__((unused))
267
Jason parks70a4b3f2011-01-28 10:10:47 -0600268#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800269
270constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
271constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700272constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800273
274// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700275static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600276
Paul Crowley14c8c072018-09-18 13:30:21 -0700277#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700278
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700279#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800280
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800281#define CRYPTO_BLOCK_DEVICE "userdata"
282
283#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
284
Ken Sumrall29d8da82011-05-18 17:20:07 -0700285#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700286#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700287
Ken Sumralle919efe2012-09-29 17:07:41 -0700288#define TABLE_LOAD_RETRIES 10
289
Shawn Willden47ba10d2014-09-03 17:07:06 -0600290#define RSA_KEY_SIZE 2048
291#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
292#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600293#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700294
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700295#define RETRY_MOUNT_ATTEMPTS 10
296#define RETRY_MOUNT_DELAY_SECONDS 1
297
Paul Crowley5afbc622017-11-27 09:42:17 -0800298#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
299
Paul Crowley73473332017-11-21 15:43:51 -0800300static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
301
Greg Kaiser59ad0182018-02-16 13:01:36 -0800302static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700303static char* saved_mount_point;
304static int master_key_saved = 0;
305static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800306
Paul Crowley220567c2020-02-07 12:45:20 -0800307constexpr CryptoType aes_128_cbc = CryptoType()
308 .set_config_name("AES-128-CBC")
309 .set_kernel_name("aes-cbc-essiv:sha256")
310 .set_keysize(16);
311
312constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
313
314static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
315 array_length(supported_crypto_types)),
316 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
317 "incompletely constructed.");
318
319static const CryptoType& get_crypto_type() {
320 // We only want to parse this read-only property once. But we need to wait
321 // until the system is initialized before we can read it. So we use a static
322 // scoped within this function to get it only once.
323 static CryptoType crypto_type =
324 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
325 aes_128_cbc, "ro.crypto.fde_algorithm");
326 return crypto_type;
327}
328
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800329const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800330 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800331}
332
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700333/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700334static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000335 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700336}
337
338/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700339static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800340 if (ftr->keymaster_blob_size) {
341 SLOGI("Already have key");
342 return 0;
343 }
344
Paul Crowley14c8c072018-09-18 13:30:21 -0700345 int rc = keymaster_create_key_for_cryptfs_scrypt(
346 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
347 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000348 if (rc) {
349 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800350 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000351 ftr->keymaster_blob_size = 0;
352 }
353 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700354 return -1;
355 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000356 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700357}
358
Shawn Willdene17a9c42014-09-08 13:04:08 -0600359/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700360static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
361 const size_t object_size, unsigned char** signature,
362 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600363 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600364 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600365 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600366
Shawn Willdene17a9c42014-09-08 13:04:08 -0600367 // To sign a message with RSA, the message must satisfy two
368 // constraints:
369 //
370 // 1. The message, when interpreted as a big-endian numeric value, must
371 // be strictly less than the public modulus of the RSA key. Note
372 // that because the most significant bit of the public modulus is
373 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
374 // key), an n-bit message with most significant bit 0 always
375 // satisfies this requirement.
376 //
377 // 2. The message must have the same length in bits as the public
378 // modulus of the RSA key. This requirement isn't mathematically
379 // necessary, but is necessary to ensure consistency in
380 // implementations.
381 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600382 case KDF_SCRYPT_KEYMASTER:
383 // This ensures the most significant byte of the signed message
384 // is zero. We could have zero-padded to the left instead, but
385 // this approach is slightly more robust against changes in
386 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600387 // so) because we really should be using a proper deterministic
388 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800389 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600390 SLOGI("Signing safely-padded object");
391 break;
392 default:
393 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000394 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600395 }
Paul Crowley73473332017-11-21 15:43:51 -0800396 for (;;) {
397 auto result = keymaster_sign_object_for_cryptfs_scrypt(
398 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
399 to_sign_size, signature, signature_size);
400 switch (result) {
401 case KeymasterSignResult::ok:
402 return 0;
403 case KeymasterSignResult::upgrade:
404 break;
405 default:
406 return -1;
407 }
408 SLOGD("Upgrading key");
409 if (keymaster_upgrade_key_for_cryptfs_scrypt(
410 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
411 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
412 &ftr->keymaster_blob_size) != 0) {
413 SLOGE("Failed to upgrade key");
414 return -1;
415 }
416 if (put_crypt_ftr_and_key(ftr) != 0) {
417 SLOGE("Failed to write upgraded key to disk");
418 }
419 SLOGD("Key upgraded successfully");
420 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600421}
422
Paul Lawrence399317e2014-03-10 13:20:50 -0700423/* Store password when userdata is successfully decrypted and mounted.
424 * Cleared by cryptfs_clear_password
425 *
426 * To avoid a double prompt at boot, we need to store the CryptKeeper
427 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
428 * Since the entire framework is torn down and rebuilt after encryption,
429 * we have to use a daemon or similar to store the password. Since vold
430 * is secured against IPC except from system processes, it seems a reasonable
431 * place to store this.
432 *
433 * password should be cleared once it has been used.
434 *
435 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800436 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700437static char* password = 0;
438static int password_expiry_time = 0;
439static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800440
Paul Crowley14c8c072018-09-18 13:30:21 -0700441enum class RebootType { reboot, recovery, shutdown };
442static void cryptfs_reboot(RebootType rt) {
443 switch (rt) {
444 case RebootType::reboot:
445 property_set(ANDROID_RB_PROPERTY, "reboot");
446 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800447
Paul Crowley14c8c072018-09-18 13:30:21 -0700448 case RebootType::recovery:
449 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
450 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800451
Paul Crowley14c8c072018-09-18 13:30:21 -0700452 case RebootType::shutdown:
453 property_set(ANDROID_RB_PROPERTY, "shutdown");
454 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700455 }
Paul Lawrence87999172014-02-20 12:21:31 -0800456
Ken Sumralladfba362013-06-04 16:37:52 -0700457 sleep(20);
458
459 /* Shouldn't get here, reboot should happen before sleep times out */
460 return;
461}
462
Kenny Rootc4c70f12013-06-14 12:11:38 -0700463/**
464 * Gets the default device scrypt parameters for key derivation time tuning.
465 * The parameters should lead to about one second derivation time for the
466 * given device.
467 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700468static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700469 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000470 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700471
Paul Crowley63c18d32016-02-10 14:02:47 +0000472 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
473 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
474 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
475 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700476 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000477 ftr->N_factor = Nf;
478 ftr->r_factor = rf;
479 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700480}
481
Tom Cherry4c5bde22019-01-29 14:34:01 -0800482static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800483 int fd, block_size;
484 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200485 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800486
Paul Crowley14c8c072018-09-18 13:30:21 -0700487 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800488 SLOGE("Cannot open device to get filesystem size ");
489 return 0;
490 }
491
492 if (lseek64(fd, 1024, SEEK_SET) < 0) {
493 SLOGE("Cannot seek to superblock");
494 return 0;
495 }
496
497 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
498 SLOGE("Cannot read superblock");
499 return 0;
500 }
501
502 close(fd);
503
Daniel Rosenberge82df162014-08-15 22:19:23 +0000504 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
505 SLOGE("Not a valid ext4 superblock");
506 return 0;
507 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800508 block_size = 1024 << sb.s_log_block_size;
509 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200510 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800511
512 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200513 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800514}
515
Tom Cherry4c5bde22019-01-29 14:34:01 -0800516static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
517 for (const auto& entry : fstab_default) {
518 if (!entry.fs_mgr_flags.vold_managed &&
519 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
520 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
521 if (key_loc != nullptr) {
522 *key_loc = entry.key_loc;
523 }
524 if (real_blk_device != nullptr) {
525 *real_blk_device = entry.blk_device;
526 }
527 return;
528 }
529 }
530}
531
Paul Crowley14c8c072018-09-18 13:30:21 -0700532static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
533 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200534 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700535 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700536 char key_loc[PROPERTY_VALUE_MAX];
537 char real_blkdev[PROPERTY_VALUE_MAX];
538 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700539
Paul Crowley14c8c072018-09-18 13:30:21 -0700540 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800541 std::string key_loc;
542 std::string real_blkdev;
543 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700544
Tom Cherry4c5bde22019-01-29 14:34:01 -0800545 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200546 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700547 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
548 * encryption info footer and key, and plenty of bytes to spare for future
549 * growth.
550 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800551 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200552 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700553 cached_data = 1;
554 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800555 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700556 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700557 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800558 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700559 cached_off = 0;
560 cached_data = 1;
561 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700562 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700563
Paul Crowley14c8c072018-09-18 13:30:21 -0700564 if (cached_data) {
565 if (metadata_fname) {
566 *metadata_fname = cached_metadata_fname;
567 }
568 if (off) {
569 *off = cached_off;
570 }
571 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700572 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700573
Paul Crowley14c8c072018-09-18 13:30:21 -0700574 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700575}
576
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800577/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700578static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800579 SHA256_CTX c;
580 SHA256_Init(&c);
581 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
582 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
583 SHA256_Final(crypt_ftr->sha256, &c);
584}
585
Ken Sumralle8744072011-01-18 22:01:55 -0800586/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800587 * update the failed mount count but not change the key.
588 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700589static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
590 int fd;
591 unsigned int cnt;
592 /* starting_off is set to the SEEK_SET offset
593 * where the crypto structure starts
594 */
595 off64_t starting_off;
596 int rc = -1;
597 char* fname = NULL;
598 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800599
Paul Crowley14c8c072018-09-18 13:30:21 -0700600 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800601
Paul Crowley14c8c072018-09-18 13:30:21 -0700602 if (get_crypt_ftr_info(&fname, &starting_off)) {
603 SLOGE("Unable to get crypt_ftr_info\n");
604 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800605 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700606 if (fname[0] != '/') {
607 SLOGE("Unexpected value for crypto key location\n");
608 return -1;
609 }
610 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
611 SLOGE("Cannot open footer file %s for put\n", fname);
612 return -1;
613 }
Ken Sumralle8744072011-01-18 22:01:55 -0800614
Paul Crowley14c8c072018-09-18 13:30:21 -0700615 /* Seek to the start of the crypt footer */
616 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
617 SLOGE("Cannot seek to real block device footer\n");
618 goto errout;
619 }
620
621 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
622 SLOGE("Cannot write real block device footer\n");
623 goto errout;
624 }
625
626 fstat(fd, &statbuf);
627 /* If the keys are kept on a raw block device, do not try to truncate it. */
628 if (S_ISREG(statbuf.st_mode)) {
629 if (ftruncate(fd, 0x4000)) {
630 SLOGE("Cannot set footer file size\n");
631 goto errout;
632 }
633 }
634
635 /* Success! */
636 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800637
638errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700639 close(fd);
640 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800641}
642
Paul Crowley14c8c072018-09-18 13:30:21 -0700643static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800644 struct crypt_mnt_ftr copy;
645 memcpy(&copy, crypt_ftr, sizeof(copy));
646 set_ftr_sha(&copy);
647 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
648}
649
Paul Crowley14c8c072018-09-18 13:30:21 -0700650static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700651 return TEMP_FAILURE_RETRY(read(fd, buff, len));
652}
653
Paul Crowley14c8c072018-09-18 13:30:21 -0700654static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700655 return TEMP_FAILURE_RETRY(write(fd, buff, len));
656}
657
Paul Crowley14c8c072018-09-18 13:30:21 -0700658static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700659 memset(pdata, 0, len);
660 pdata->persist_magic = PERSIST_DATA_MAGIC;
661 pdata->persist_valid_entries = 0;
662}
663
664/* A routine to update the passed in crypt_ftr to the lastest version.
665 * fd is open read/write on the device that holds the crypto footer and persistent
666 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
667 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
668 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700669static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700670 int orig_major = crypt_ftr->major_version;
671 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700672
Kenny Root7434b312013-06-14 11:29:53 -0700673 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700674 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700675 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700676
Kenny Rootc4c70f12013-06-14 12:11:38 -0700677 SLOGW("upgrading crypto footer to 1.1");
678
Paul Crowley14c8c072018-09-18 13:30:21 -0700679 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700680 if (pdata == NULL) {
681 SLOGE("Cannot allocate persisent data\n");
682 return;
683 }
684 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
685
686 /* Need to initialize the persistent data area */
687 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
688 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100689 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700690 return;
691 }
692 /* Write all zeros to the first copy, making it invalid */
693 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
694
695 /* Write a valid but empty structure to the second copy */
696 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
697 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
698
699 /* Update the footer */
700 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
701 crypt_ftr->persist_data_offset[0] = pdata_offset;
702 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
703 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100704 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700705 }
706
Paul Lawrencef4faa572014-01-29 13:31:03 -0800707 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700708 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800709 /* But keep the old kdf_type.
710 * It will get updated later to KDF_SCRYPT after the password has been verified.
711 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700712 crypt_ftr->kdf_type = KDF_PBKDF2;
713 get_device_scrypt_params(crypt_ftr);
714 crypt_ftr->minor_version = 2;
715 }
716
Paul Lawrencef4faa572014-01-29 13:31:03 -0800717 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
718 SLOGW("upgrading crypto footer to 1.3");
719 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
720 crypt_ftr->minor_version = 3;
721 }
722
Kenny Root7434b312013-06-14 11:29:53 -0700723 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
724 if (lseek64(fd, offset, SEEK_SET) == -1) {
725 SLOGE("Cannot seek to crypt footer\n");
726 return;
727 }
728 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700729 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700730}
731
Paul Crowley14c8c072018-09-18 13:30:21 -0700732static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
733 int fd;
734 unsigned int cnt;
735 off64_t starting_off;
736 int rc = -1;
737 char* fname = NULL;
738 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700739
Paul Crowley14c8c072018-09-18 13:30:21 -0700740 if (get_crypt_ftr_info(&fname, &starting_off)) {
741 SLOGE("Unable to get crypt_ftr_info\n");
742 return -1;
743 }
744 if (fname[0] != '/') {
745 SLOGE("Unexpected value for crypto key location\n");
746 return -1;
747 }
748 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
749 SLOGE("Cannot open footer file %s for get\n", fname);
750 return -1;
751 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800752
Paul Crowley14c8c072018-09-18 13:30:21 -0700753 /* Make sure it's 16 Kbytes in length */
754 fstat(fd, &statbuf);
755 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
756 SLOGE("footer file %s is not the expected size!\n", fname);
757 goto errout;
758 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759
Paul Crowley14c8c072018-09-18 13:30:21 -0700760 /* Seek to the start of the crypt footer */
761 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
762 SLOGE("Cannot seek to real block device footer\n");
763 goto errout;
764 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765
Paul Crowley14c8c072018-09-18 13:30:21 -0700766 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
767 SLOGE("Cannot read real block device footer\n");
768 goto errout;
769 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800770
Paul Crowley14c8c072018-09-18 13:30:21 -0700771 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
772 SLOGE("Bad magic for real block device %s\n", fname);
773 goto errout;
774 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800775
Paul Crowley14c8c072018-09-18 13:30:21 -0700776 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
777 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
778 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
779 goto errout;
780 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800781
Paul Crowley14c8c072018-09-18 13:30:21 -0700782 // We risk buffer overflows with oversized keys, so we just reject them.
783 // 0-sized keys are problematic (essentially by-passing encryption), and
784 // AES-CBC key wrapping only works for multiples of 16 bytes.
785 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
786 (crypt_ftr->keysize > MAX_KEY_LEN)) {
787 SLOGE(
788 "Invalid keysize (%u) for block device %s; Must be non-zero, "
789 "divisible by 16, and <= %d\n",
790 crypt_ftr->keysize, fname, MAX_KEY_LEN);
791 goto errout;
792 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800793
Paul Crowley14c8c072018-09-18 13:30:21 -0700794 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
795 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
796 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
797 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800798
Paul Crowley14c8c072018-09-18 13:30:21 -0700799 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
800 * copy on disk before returning.
801 */
802 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
803 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
804 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800805
Paul Crowley14c8c072018-09-18 13:30:21 -0700806 /* Success! */
807 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800808
809errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700810 close(fd);
811 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800812}
813
Paul Crowley14c8c072018-09-18 13:30:21 -0700814static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
816 crypt_ftr->persist_data_offset[1]) {
817 SLOGE("Crypt_ftr persist data regions overlap");
818 return -1;
819 }
820
821 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
822 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
823 return -1;
824 }
825
826 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700827 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700828 CRYPT_FOOTER_OFFSET) {
829 SLOGE("Persistent data extends past crypto footer");
830 return -1;
831 }
832
833 return 0;
834}
835
Paul Crowley14c8c072018-09-18 13:30:21 -0700836static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700837 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700838 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700839 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700840 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700841 int found = 0;
842 int fd;
843 int ret;
844 int i;
845
846 if (persist_data) {
847 /* Nothing to do, we've already loaded or initialized it */
848 return 0;
849 }
850
Ken Sumrall160b4d62013-04-22 12:15:39 -0700851 /* If not encrypted, just allocate an empty table and initialize it */
852 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700853 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800854 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700855 if (pdata) {
856 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
857 persist_data = pdata;
858 return 0;
859 }
860 return -1;
861 }
862
Paul Crowley14c8c072018-09-18 13:30:21 -0700863 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700864 return -1;
865 }
866
Paul Crowley14c8c072018-09-18 13:30:21 -0700867 if ((crypt_ftr.major_version < 1) ||
868 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700869 SLOGE("Crypt_ftr version doesn't support persistent data");
870 return -1;
871 }
872
873 if (get_crypt_ftr_info(&fname, NULL)) {
874 return -1;
875 }
876
877 ret = validate_persistent_data_storage(&crypt_ftr);
878 if (ret) {
879 return -1;
880 }
881
Paul Crowley14c8c072018-09-18 13:30:21 -0700882 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700883 if (fd < 0) {
884 SLOGE("Cannot open %s metadata file", fname);
885 return -1;
886 }
887
Wei Wang4375f1b2017-02-24 17:43:01 -0800888 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800889 if (pdata == NULL) {
890 SLOGE("Cannot allocate memory for persistent data");
891 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700892 }
893
894 for (i = 0; i < 2; i++) {
895 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
896 SLOGE("Cannot seek to read persistent data on %s", fname);
897 goto err2;
898 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700899 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700900 SLOGE("Error reading persistent data on iteration %d", i);
901 goto err2;
902 }
903 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
904 found = 1;
905 break;
906 }
907 }
908
909 if (!found) {
910 SLOGI("Could not find valid persistent data, creating");
911 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
912 }
913
914 /* Success */
915 persist_data = pdata;
916 close(fd);
917 return 0;
918
919err2:
920 free(pdata);
921
922err:
923 close(fd);
924 return -1;
925}
926
Paul Crowley14c8c072018-09-18 13:30:21 -0700927static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700928 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700929 struct crypt_persist_data* pdata;
930 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700931 off64_t write_offset;
932 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700933 int fd;
934 int ret;
935
936 if (persist_data == NULL) {
937 SLOGE("No persistent data to save");
938 return -1;
939 }
940
Paul Crowley14c8c072018-09-18 13:30:21 -0700941 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700942 return -1;
943 }
944
Paul Crowley14c8c072018-09-18 13:30:21 -0700945 if ((crypt_ftr.major_version < 1) ||
946 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700947 SLOGE("Crypt_ftr version doesn't support persistent data");
948 return -1;
949 }
950
951 ret = validate_persistent_data_storage(&crypt_ftr);
952 if (ret) {
953 return -1;
954 }
955
956 if (get_crypt_ftr_info(&fname, NULL)) {
957 return -1;
958 }
959
Paul Crowley14c8c072018-09-18 13:30:21 -0700960 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700961 if (fd < 0) {
962 SLOGE("Cannot open %s metadata file", fname);
963 return -1;
964 }
965
Wei Wang4375f1b2017-02-24 17:43:01 -0800966 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700967 if (pdata == NULL) {
968 SLOGE("Cannot allocate persistant data");
969 goto err;
970 }
971
972 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
973 SLOGE("Cannot seek to read persistent data on %s", fname);
974 goto err2;
975 }
976
977 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700978 SLOGE("Error reading persistent data before save");
979 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700980 }
981
982 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
983 /* The first copy is the curent valid copy, so write to
984 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700985 write_offset = crypt_ftr.persist_data_offset[1];
986 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700987 } else {
988 /* The second copy must be the valid copy, so write to
989 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700990 write_offset = crypt_ftr.persist_data_offset[0];
991 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700992 }
993
994 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100995 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700996 SLOGE("Cannot seek to write persistent data");
997 goto err2;
998 }
999 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001000 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001001 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001002 SLOGE("Cannot seek to erase previous persistent data");
1003 goto err2;
1004 }
1005 fsync(fd);
1006 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001007 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001008 SLOGE("Cannot write to erase previous persistent data");
1009 goto err2;
1010 }
1011 fsync(fd);
1012 } else {
1013 SLOGE("Cannot write to save persistent data");
1014 goto err2;
1015 }
1016
1017 /* Success */
1018 free(pdata);
1019 close(fd);
1020 return 0;
1021
1022err2:
1023 free(pdata);
1024err:
1025 close(fd);
1026 return -1;
1027}
1028
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001029/* Convert a binary key of specified length into an ascii hex string equivalent,
1030 * without the leading 0x and with null termination
1031 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001032static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1033 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001034 unsigned int i, a;
1035 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001036
Paul Crowley14c8c072018-09-18 13:30:21 -07001037 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001038 /* For each byte, write out two ascii hex digits */
1039 nibble = (master_key[i] >> 4) & 0xf;
1040 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001041
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001042 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001043 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001044 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001045
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001046 /* Add the null termination */
1047 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001048}
1049
Eric Biggersed45ec32019-01-25 10:47:55 -08001050/*
1051 * If the ro.crypto.fde_sector_size system property is set, append the
1052 * parameters to make dm-crypt use the specified crypto sector size and round
1053 * the crypto device size down to a crypto sector boundary.
1054 */
David Andersonb9224732019-05-13 13:02:54 -07001055static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001056 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001057 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001058
Eric Biggersed45ec32019-01-25 10:47:55 -08001059 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1060 unsigned int sector_size;
1061
1062 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1063 (sector_size & (sector_size - 1)) != 0) {
1064 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1065 DM_CRYPT_SECTOR_SIZE, value);
1066 return -1;
1067 }
1068
David Andersonb9224732019-05-13 13:02:54 -07001069 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001070
1071 // With this option, IVs will match the sector numbering, instead
1072 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001073 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001074
1075 // Round the crypto device size down to a crypto sector boundary.
1076 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001077 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001078 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001079}
1080
Paul Crowley5afbc622017-11-27 09:42:17 -08001081static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001082 const char* real_blk_name, std::string* crypto_blk_name,
1083 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001084 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001085
David Andersonb9224732019-05-13 13:02:54 -07001086 // We need two ASCII characters to represent each byte, and need space for
1087 // the '\0' terminator.
1088 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1089 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001090
David Andersonb9224732019-05-13 13:02:54 -07001091 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1092 (const char*)crypt_ftr->crypto_type_name,
1093 master_key_ascii, 0, real_blk_name, 0);
1094 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001095
Paul Crowley5afbc622017-11-27 09:42:17 -08001096 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001097 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001098 }
David Andersonb9224732019-05-13 13:02:54 -07001099 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001100 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001101 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001102 }
David Andersonb9224732019-05-13 13:02:54 -07001103
1104 DmTable table;
1105 table.AddTarget(std::move(target));
1106
1107 int load_count = 1;
1108 while (load_count < TABLE_LOAD_RETRIES) {
1109 if (dm.CreateDevice(name, table)) {
1110 break;
1111 }
1112 load_count++;
1113 }
1114
1115 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001116 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001117 return -1;
1118 }
1119 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001120 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1121 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122
Paul Crowley81796e92020-02-07 11:27:49 -08001123 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001124 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1125 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001126 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001127
Paul Crowleycfe39722018-10-30 15:59:24 -07001128 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001129 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001130 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001131 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001132 }
David Andersonb9224732019-05-13 13:02:54 -07001133 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134}
1135
David Andersonb9224732019-05-13 13:02:54 -07001136static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001137 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001138 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001139 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1140 // to delete the device fails with EBUSY; for now, work around this by retrying.
1141 int tries = 5;
1142 while (tries-- > 0) {
1143 ret = dm.DeleteDevice(name);
1144 if (ret || errno != EBUSY) {
1145 break;
1146 }
1147 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1148 strerror(errno));
1149 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1150 }
1151 if (!ret) {
1152 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001153 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001154 }
David Andersonb9224732019-05-13 13:02:54 -07001155 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156}
1157
Paul Crowley14c8c072018-09-18 13:30:21 -07001158static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1159 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001160 SLOGI("Using pbkdf2 for cryptfs KDF");
1161
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001162 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001163 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1164 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001165}
1166
Paul Crowley14c8c072018-09-18 13:30:21 -07001167static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001168 SLOGI("Using scrypt for cryptfs KDF");
1169
Paul Crowley14c8c072018-09-18 13:30:21 -07001170 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001171
1172 int N = 1 << ftr->N_factor;
1173 int r = 1 << ftr->r_factor;
1174 int p = 1 << ftr->p_factor;
1175
1176 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001177 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001178 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001179
Paul Crowley14c8c072018-09-18 13:30:21 -07001180 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001181}
1182
Paul Crowley14c8c072018-09-18 13:30:21 -07001183static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1184 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001185 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1186
1187 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001188 size_t signature_size;
1189 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001190 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001191
1192 int N = 1 << ftr->N_factor;
1193 int r = 1 << ftr->r_factor;
1194 int p = 1 << ftr->p_factor;
1195
Paul Crowley14c8c072018-09-18 13:30:21 -07001196 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001197 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001198
1199 if (rc) {
1200 SLOGE("scrypt failed");
1201 return -1;
1202 }
1203
Paul Crowley14c8c072018-09-18 13:30:21 -07001204 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001205 SLOGE("Signing failed");
1206 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001207 }
1208
Paul Crowley14c8c072018-09-18 13:30:21 -07001209 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1210 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001211 free(signature);
1212
1213 if (rc) {
1214 SLOGE("scrypt failed");
1215 return -1;
1216 }
1217
1218 return 0;
1219}
1220
Paul Crowley14c8c072018-09-18 13:30:21 -07001221static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1222 const unsigned char* decrypted_master_key,
1223 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1224 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001225 EVP_CIPHER_CTX e_ctx;
1226 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001227 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001228
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001229 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001230 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001231
1232 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001233 case KDF_SCRYPT_KEYMASTER:
1234 if (keymaster_create_key(crypt_ftr)) {
1235 SLOGE("keymaster_create_key failed");
1236 return -1;
1237 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001238
Paul Crowley14c8c072018-09-18 13:30:21 -07001239 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1240 SLOGE("scrypt failed");
1241 return -1;
1242 }
1243 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001244
Paul Crowley14c8c072018-09-18 13:30:21 -07001245 case KDF_SCRYPT:
1246 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1247 SLOGE("scrypt failed");
1248 return -1;
1249 }
1250 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001251
Paul Crowley14c8c072018-09-18 13:30:21 -07001252 default:
1253 SLOGE("Invalid kdf_type");
1254 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001255 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001256
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001257 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001258 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001259 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1260 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001261 SLOGE("EVP_EncryptInit failed\n");
1262 return -1;
1263 }
1264 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001265
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001266 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001267 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1268 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001269 SLOGE("EVP_EncryptUpdate failed\n");
1270 return -1;
1271 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001272 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001273 SLOGE("EVP_EncryptFinal failed\n");
1274 return -1;
1275 }
1276
Greg Kaiser59ad0182018-02-16 13:01:36 -08001277 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001278 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1279 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001280 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001281
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001282 /* Store the scrypt of the intermediate key, so we can validate if it's a
1283 password error or mount error when things go wrong.
1284 Note there's no need to check for errors, since if this is incorrect, we
1285 simply won't wipe userdata, which is the correct default behavior
1286 */
1287 int N = 1 << crypt_ftr->N_factor;
1288 int r = 1 << crypt_ftr->r_factor;
1289 int p = 1 << crypt_ftr->p_factor;
1290
Paul Crowley14c8c072018-09-18 13:30:21 -07001291 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1292 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001293 sizeof(crypt_ftr->scrypted_intermediate_key));
1294
1295 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001296 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001297 }
1298
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001299 EVP_CIPHER_CTX_cleanup(&e_ctx);
1300
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001301 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302}
1303
Paul Crowley14c8c072018-09-18 13:30:21 -07001304static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1305 const unsigned char* encrypted_master_key, size_t keysize,
1306 unsigned char* decrypted_master_key, kdf_func kdf,
1307 void* kdf_params, unsigned char** intermediate_key,
1308 size_t* intermediate_key_size) {
1309 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1310 EVP_CIPHER_CTX d_ctx;
1311 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001312
Paul Crowley14c8c072018-09-18 13:30:21 -07001313 /* Turn the password into an intermediate key and IV that can decrypt the
1314 master key */
1315 if (kdf(passwd, salt, ikey, kdf_params)) {
1316 SLOGE("kdf failed");
1317 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001318 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001319
Paul Crowley14c8c072018-09-18 13:30:21 -07001320 /* Initialize the decryption engine */
1321 EVP_CIPHER_CTX_init(&d_ctx);
1322 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1323 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1324 return -1;
1325 }
1326 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1327 /* Decrypt the master key */
1328 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1329 keysize)) {
1330 return -1;
1331 }
1332 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1333 return -1;
1334 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001335
Paul Crowley14c8c072018-09-18 13:30:21 -07001336 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1337 return -1;
1338 }
1339
1340 /* Copy intermediate key if needed by params */
1341 if (intermediate_key && intermediate_key_size) {
1342 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1343 if (*intermediate_key) {
1344 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1345 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1346 }
1347 }
1348
1349 EVP_CIPHER_CTX_cleanup(&d_ctx);
1350
1351 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001352}
1353
Paul Crowley14c8c072018-09-18 13:30:21 -07001354static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001355 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001356 *kdf = scrypt_keymaster;
1357 *kdf_params = ftr;
1358 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001359 *kdf = scrypt;
1360 *kdf_params = ftr;
1361 } else {
1362 *kdf = pbkdf2;
1363 *kdf_params = NULL;
1364 }
1365}
1366
Paul Crowley14c8c072018-09-18 13:30:21 -07001367static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1368 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1369 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001370 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001371 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001372 int ret;
1373
1374 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001375 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1376 decrypted_master_key, kdf, kdf_params, intermediate_key,
1377 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001378 if (ret != 0) {
1379 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001380 }
1381
1382 return ret;
1383}
1384
Paul Crowley14c8c072018-09-18 13:30:21 -07001385static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1386 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001387 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001388
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001389 /* Get some random bits for a key and salt */
1390 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1391 return -1;
1392 }
1393 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1394 return -1;
1395 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001396
1397 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001398 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001399}
1400
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001401static void ensure_subdirectory_unmounted(const char *prefix) {
1402 std::vector<std::string> umount_points;
1403 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1404 if (!mnts) {
1405 SLOGW("could not read mount files");
1406 return;
1407 }
1408
1409 //Find sudirectory mount point
1410 mntent* mentry;
1411 std::string top_directory(prefix);
1412 if (!android::base::EndsWith(prefix, "/")) {
1413 top_directory = top_directory + "/";
1414 }
1415 while ((mentry = getmntent(mnts.get())) != nullptr) {
1416 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1417 continue;
1418 }
1419
1420 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1421 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1422 umount_points.push_back(mentry->mnt_dir);
1423 }
1424 }
1425
1426 //Sort by path length to umount longest path first
1427 std::sort(std::begin(umount_points), std::end(umount_points),
1428 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1429
1430 for (std::string& mount_point : umount_points) {
1431 umount(mount_point.c_str());
1432 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1433 }
1434}
1435
Paul Crowley73be12d2020-02-03 12:22:03 -08001436static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001437 int i, err, rc;
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001438
1439 // Subdirectory mount will cause a failure of umount.
1440 ensure_subdirectory_unmounted(mountpoint);
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001441#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442
1443 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001444 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001445 if (umount(mountpoint) == 0) {
1446 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001447 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001448
1449 if (errno == EINVAL) {
1450 /* EINVAL is returned if the directory is not a mountpoint,
1451 * i.e. there is no filesystem mounted there. So just get out.
1452 */
1453 break;
1454 }
1455
1456 err = errno;
1457
1458 /* If allowed, be increasingly aggressive before the last two retries */
1459 if (kill) {
1460 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1461 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001462 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001463 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1464 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001465 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001466 }
1467 }
1468
1469 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001470 }
1471
1472 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001473 SLOGD("unmounting %s succeeded\n", mountpoint);
1474 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001475 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001476 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1477 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1478 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001479 }
1480
1481 return rc;
1482}
1483
Paul Crowley14c8c072018-09-18 13:30:21 -07001484static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001485 // NOTE: post_fs_data results in init calling back around to vold, so all
1486 // callers to this method must be async
1487
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001488 /* Do the prep of the /data filesystem */
1489 property_set("vold.post_fs_data_done", "0");
1490 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001491 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001492
Ken Sumrallc5872692013-05-14 15:26:31 -07001493 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001494 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001495 /* We timed out to prep /data in time. Continue wait. */
1496 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001497 }
Wei Wang42e38102017-06-07 10:46:12 -07001498 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001499}
1500
Paul Crowley14c8c072018-09-18 13:30:21 -07001501static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001502 // Mark the footer as bad
1503 struct crypt_mnt_ftr crypt_ftr;
1504 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1505 SLOGE("Failed to get crypto footer - panic");
1506 return;
1507 }
1508
1509 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1510 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1511 SLOGE("Failed to set crypto footer - panic");
1512 return;
1513 }
1514}
1515
Paul Crowley14c8c072018-09-18 13:30:21 -07001516static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001517 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001518 SLOGE("Failed to mount tmpfs on data - panic");
1519 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001520 }
1521
1522 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1523 SLOGE("Failed to trigger post fs data - panic");
1524 return;
1525 }
1526
1527 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1528 SLOGE("Failed to trigger restart min framework - panic");
1529 return;
1530 }
1531}
1532
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001533/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001534static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001535 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001536 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001537 static int restart_successful = 0;
1538
1539 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001540 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001541 SLOGE("Encrypted filesystem not validated, aborting");
1542 return -1;
1543 }
1544
1545 if (restart_successful) {
1546 SLOGE("System already restarted with encrypted disk, aborting");
1547 return -1;
1548 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001549
Paul Lawrencef4faa572014-01-29 13:31:03 -08001550 if (restart_main) {
1551 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001552 * start all services in one of these classes: core, early_hal, hal,
1553 * main and late_start. To get to the minimal UI for PIN entry, we
1554 * need to start core, early_hal, hal and main. When we want to
1555 * shutdown the framework again, we need to stop most of the services in
1556 * these classes, but only those services that were started after
1557 * /data was mounted. This excludes critical services like vold and
1558 * ueventd, which need to keep running. We could possible stop
1559 * even fewer services, but because we want services to pick up APEX
1560 * libraries from the real /data, restarting is better, as it makes
1561 * these devices consistent with FBE devices and lets them use the
1562 * most recent code.
1563 *
1564 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001565 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001566 * We then restart the class core, hal, main, and also the class
1567 * late_start.
1568 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001569 * At the moment, I've only put a few things in late_start that I know
1570 * are not needed to bring up the framework, and that also cause problems
1571 * with unmounting the tmpfs /data, but I hope to add add more services
1572 * to the late_start class as we optimize this to decrease the delay
1573 * till the user is asked for the password to the filesystem.
1574 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001575
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001576 /* The init files are setup to stop the right set of services when
1577 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001578 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001579 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001580 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001581
Paul Lawrencef4faa572014-01-29 13:31:03 -08001582 /* Ugh, shutting down the framework is not synchronous, so until it
1583 * can be fixed, this horrible hack will wait a moment for it all to
1584 * shut down before proceeding. Without it, some devices cannot
1585 * restart the graphics services.
1586 */
1587 sleep(2);
1588 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001589
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001590 /* Now that the framework is shutdown, we should be able to umount()
1591 * the tmpfs filesystem, and mount the real one.
1592 */
1593
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001594 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1595 if (strlen(crypto_blkdev) == 0) {
1596 SLOGE("fs_crypto_blkdev not set\n");
1597 return -1;
1598 }
1599
Paul Crowley14c8c072018-09-18 13:30:21 -07001600 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001601 /* If ro.crypto.readonly is set to 1, mount the decrypted
1602 * filesystem readonly. This is used when /data is mounted by
1603 * recovery mode.
1604 */
1605 char ro_prop[PROPERTY_VALUE_MAX];
1606 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001607 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001608 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1609 if (entry != nullptr) {
1610 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001611 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001612 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001613
Ken Sumralle5032c42012-04-01 23:58:44 -07001614 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001615 int retries = RETRY_MOUNT_ATTEMPTS;
1616 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001617
1618 /*
1619 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1620 * partitions in the fsck domain.
1621 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001622 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001623 SLOGE("Failed to setexeccon");
1624 return -1;
1625 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001626 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001627 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001628 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001629 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1630 /* TODO: invoke something similar to
1631 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1632 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001633 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001634 if (--retries) {
1635 sleep(RETRY_MOUNT_DELAY_SECONDS);
1636 } else {
1637 /* Let's hope that a reboot clears away whatever is keeping
1638 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001639 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001640 }
1641 } else {
1642 SLOGE("Failed to mount decrypted data");
1643 cryptfs_set_corrupt();
1644 cryptfs_trigger_restart_min_framework();
1645 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001646 if (setexeccon(NULL)) {
1647 SLOGE("Failed to setexeccon");
1648 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001649 return -1;
1650 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001651 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001652 if (setexeccon(NULL)) {
1653 SLOGE("Failed to setexeccon");
1654 return -1;
1655 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001656
Ken Sumralle5032c42012-04-01 23:58:44 -07001657 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001658 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001659 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001660
1661 /* startup service classes main and late_start */
1662 property_set("vold.decrypt", "trigger_restart_framework");
1663 SLOGD("Just triggered restart_framework\n");
1664
1665 /* Give it a few moments to get started */
1666 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001667 }
1668
Ken Sumrall0cc16632011-01-18 20:32:26 -08001669 if (rc == 0) {
1670 restart_successful = 1;
1671 }
1672
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001673 return rc;
1674}
1675
Paul Crowley14c8c072018-09-18 13:30:21 -07001676int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001677 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001678 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001679 SLOGE("cryptfs_restart not valid for file encryption:");
1680 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001681 }
1682
Paul Lawrencef4faa572014-01-29 13:31:03 -08001683 /* Call internal implementation forcing a restart of main service group */
1684 return cryptfs_restart_internal(1);
1685}
1686
Paul Crowley14c8c072018-09-18 13:30:21 -07001687static int do_crypto_complete(const char* mount_point) {
1688 struct crypt_mnt_ftr crypt_ftr;
1689 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001690
Paul Crowley14c8c072018-09-18 13:30:21 -07001691 property_get("ro.crypto.state", encrypted_state, "");
1692 if (strcmp(encrypted_state, "encrypted")) {
1693 SLOGE("not running with encryption, aborting");
1694 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001695 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001696
Paul Crowley14c8c072018-09-18 13:30:21 -07001697 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001698 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001699 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1700 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001701
Paul Crowley14c8c072018-09-18 13:30:21 -07001702 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001703 std::string key_loc;
1704 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001705
Paul Crowley14c8c072018-09-18 13:30:21 -07001706 /*
1707 * Only report this error if key_loc is a file and it exists.
1708 * If the device was never encrypted, and /data is not mountable for
1709 * some reason, returning 1 should prevent the UI from presenting the
1710 * a "enter password" screen, or worse, a "press button to wipe the
1711 * device" screen.
1712 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001713 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001714 SLOGE("master key file does not exist, aborting");
1715 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1716 } else {
1717 SLOGE("Error getting crypt footer and key\n");
1718 return CRYPTO_COMPLETE_BAD_METADATA;
1719 }
1720 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001721
Paul Crowley14c8c072018-09-18 13:30:21 -07001722 // Test for possible error flags
1723 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1724 SLOGE("Encryption process is partway completed\n");
1725 return CRYPTO_COMPLETE_PARTIAL;
1726 }
1727
1728 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1729 SLOGE("Encryption process was interrupted but cannot continue\n");
1730 return CRYPTO_COMPLETE_INCONSISTENT;
1731 }
1732
1733 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1734 SLOGE("Encryption is successful but data is corrupt\n");
1735 return CRYPTO_COMPLETE_CORRUPT;
1736 }
1737
1738 /* We passed the test! We shall diminish, and return to the west */
1739 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001740}
1741
Paul Crowley14c8c072018-09-18 13:30:21 -07001742static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1743 const char* mount_point, const char* label) {
1744 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001745 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001746 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001747 char tmp_mount_point[64];
1748 unsigned int orig_failed_decrypt_count;
1749 int rc;
1750 int use_keymaster = 0;
1751 int upgrade = 0;
1752 unsigned char* intermediate_key = 0;
1753 size_t intermediate_key_size = 0;
1754 int N = 1 << crypt_ftr->N_factor;
1755 int r = 1 << crypt_ftr->r_factor;
1756 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001757
Paul Crowley14c8c072018-09-18 13:30:21 -07001758 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1759 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001760
Paul Crowley14c8c072018-09-18 13:30:21 -07001761 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1762 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1763 &intermediate_key_size)) {
1764 SLOGE("Failed to decrypt master key\n");
1765 rc = -1;
1766 goto errout;
1767 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001768 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001769
Tom Cherry4c5bde22019-01-29 14:34:01 -08001770 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001771
Paul Crowley14c8c072018-09-18 13:30:21 -07001772 // Create crypto block device - all (non fatal) code paths
1773 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001774 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001775 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001776 SLOGE("Error creating decrypted block device\n");
1777 rc = -1;
1778 goto errout;
1779 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001780
Paul Crowley14c8c072018-09-18 13:30:21 -07001781 /* Work out if the problem is the password or the data */
1782 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001783
Paul Crowley14c8c072018-09-18 13:30:21 -07001784 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1785 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1786 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001787
Paul Crowley14c8c072018-09-18 13:30:21 -07001788 // Does the key match the crypto footer?
1789 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1790 sizeof(scrypted_intermediate_key)) == 0) {
1791 SLOGI("Password matches");
1792 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001793 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001794 /* Try mounting the file system anyway, just in case the problem's with
1795 * the footer, not the key. */
1796 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1797 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001798 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1799 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001800 SLOGE("Error temp mounting decrypted block device\n");
1801 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001802
Paul Crowley14c8c072018-09-18 13:30:21 -07001803 rc = ++crypt_ftr->failed_decrypt_count;
1804 put_crypt_ftr_and_key(crypt_ftr);
1805 } else {
1806 /* Success! */
1807 SLOGI("Password did not match but decrypted drive mounted - continue");
1808 umount(tmp_mount_point);
1809 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001810 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001811 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001812
Paul Crowley14c8c072018-09-18 13:30:21 -07001813 if (rc == 0) {
1814 crypt_ftr->failed_decrypt_count = 0;
1815 if (orig_failed_decrypt_count != 0) {
1816 put_crypt_ftr_and_key(crypt_ftr);
1817 }
1818
1819 /* Save the name of the crypto block device
1820 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001821 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001822
1823 /* Also save a the master key so we can reencrypted the key
1824 * the key when we want to change the password on it. */
1825 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1826 saved_mount_point = strdup(mount_point);
1827 master_key_saved = 1;
1828 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1829 rc = 0;
1830
1831 // Upgrade if we're not using the latest KDF.
1832 use_keymaster = keymaster_check_compatibility();
1833 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1834 // Don't allow downgrade
1835 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1836 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1837 upgrade = 1;
1838 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1839 crypt_ftr->kdf_type = KDF_SCRYPT;
1840 upgrade = 1;
1841 }
1842
1843 if (upgrade) {
1844 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1845 crypt_ftr->master_key, crypt_ftr);
1846 if (!rc) {
1847 rc = put_crypt_ftr_and_key(crypt_ftr);
1848 }
1849 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1850
1851 // Do not fail even if upgrade failed - machine is bootable
1852 // Note that if this code is ever hit, there is a *serious* problem
1853 // since KDFs should never fail. You *must* fix the kdf before
1854 // proceeding!
1855 if (rc) {
1856 SLOGW(
1857 "Upgrade failed with error %d,"
1858 " but continuing with previous state",
1859 rc);
1860 rc = 0;
1861 }
1862 }
1863 }
1864
1865errout:
1866 if (intermediate_key) {
1867 memset(intermediate_key, 0, intermediate_key_size);
1868 free(intermediate_key);
1869 }
1870 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001871}
1872
Ken Sumrall29d8da82011-05-18 17:20:07 -07001873/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001874 * Called by vold when it's asked to mount an encrypted external
1875 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001876 * as any metadata is been stored in a separate, small partition. We
1877 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001878 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001879int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001880 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001881 auto crypto_type = get_crypto_type();
1882 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001883 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001884 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001885 return -1;
1886 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001887 uint64_t nr_sec = 0;
1888 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001889 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001890 return -1;
1891 }
1892
Jeff Sharkey9c484982015-03-31 10:35:33 -07001893 struct crypt_mnt_ftr ext_crypt_ftr;
1894 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1895 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001896 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1897 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001898 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001899 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001900 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001901 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1902 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001903
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001904 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1905 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001906}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001907
Paul Crowley14c8c072018-09-18 13:30:21 -07001908int cryptfs_crypto_complete(void) {
1909 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001910}
1911
Paul Crowley14c8c072018-09-18 13:30:21 -07001912int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001913 char encrypted_state[PROPERTY_VALUE_MAX];
1914 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001915 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1916 SLOGE(
1917 "encrypted fs already validated or not running with encryption,"
1918 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001919 return -1;
1920 }
1921
1922 if (get_crypt_ftr_and_key(crypt_ftr)) {
1923 SLOGE("Error getting crypt footer and key");
1924 return -1;
1925 }
1926
1927 return 0;
1928}
1929
Paul Crowley14c8c072018-09-18 13:30:21 -07001930int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001931 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001932 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001933 SLOGE("cryptfs_check_passwd not valid for file encryption");
1934 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001935 }
1936
Paul Lawrencef4faa572014-01-29 13:31:03 -08001937 struct crypt_mnt_ftr crypt_ftr;
1938 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001939
Paul Lawrencef4faa572014-01-29 13:31:03 -08001940 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001941 if (rc) {
1942 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001943 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001944 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001945
Paul Crowley14c8c072018-09-18 13:30:21 -07001946 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001947 if (rc) {
1948 SLOGE("Password did not match");
1949 return rc;
1950 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001951
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001952 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1953 // Here we have a default actual password but a real password
1954 // we must test against the scrypted value
1955 // First, we must delete the crypto block device that
1956 // test_mount_encrypted_fs leaves behind as a side effect
1957 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001958 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1959 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001960 if (rc) {
1961 SLOGE("Default password did not match on reboot encryption");
1962 return rc;
1963 }
1964
1965 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1966 put_crypt_ftr_and_key(&crypt_ftr);
1967 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1968 if (rc) {
1969 SLOGE("Could not change password on reboot encryption");
1970 return rc;
1971 }
1972 }
1973
1974 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001975 cryptfs_clear_password();
1976 password = strdup(passwd);
1977 struct timespec now;
1978 clock_gettime(CLOCK_BOOTTIME, &now);
1979 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001980 }
1981
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001982 return rc;
1983}
1984
Paul Crowley14c8c072018-09-18 13:30:21 -07001985int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001986 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001987 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001988 char encrypted_state[PROPERTY_VALUE_MAX];
1989 int rc;
1990
1991 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001992 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001993 SLOGE("device not encrypted, aborting");
1994 return -2;
1995 }
1996
1997 if (!master_key_saved) {
1998 SLOGE("encrypted fs not yet mounted, aborting");
1999 return -1;
2000 }
2001
2002 if (!saved_mount_point) {
2003 SLOGE("encrypted fs failed to save mount point, aborting");
2004 return -1;
2005 }
2006
Ken Sumrall160b4d62013-04-22 12:15:39 -07002007 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002008 SLOGE("Error getting crypt footer and key\n");
2009 return -1;
2010 }
2011
2012 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2013 /* If the device has no password, then just say the password is valid */
2014 rc = 0;
2015 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002016 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002017 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2018 /* They match, the password is correct */
2019 rc = 0;
2020 } else {
2021 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2022 sleep(1);
2023 rc = 1;
2024 }
2025 }
2026
2027 return rc;
2028}
2029
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002030/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002031 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002032 * Presumably, at a minimum, the caller will update the
2033 * filesystem size and crypto_type_name after calling this function.
2034 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002035static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002036 off64_t off;
2037
2038 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002039 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002040 ftr->major_version = CURRENT_MAJOR_VERSION;
2041 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002042 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002043 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002044
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002045 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002046 case 1:
2047 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2048 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002049
Paul Crowley14c8c072018-09-18 13:30:21 -07002050 case 0:
2051 ftr->kdf_type = KDF_SCRYPT;
2052 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002053
Paul Crowley14c8c072018-09-18 13:30:21 -07002054 default:
2055 SLOGE("keymaster_check_compatibility failed");
2056 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002057 }
2058
Kenny Rootc4c70f12013-06-14 12:11:38 -07002059 get_device_scrypt_params(ftr);
2060
Ken Sumrall160b4d62013-04-22 12:15:39 -07002061 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2062 if (get_crypt_ftr_info(NULL, &off) == 0) {
2063 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002064 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002065 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002066
2067 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002068}
2069
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002070#define FRAMEWORK_BOOT_WAIT 60
2071
Paul Crowley14c8c072018-09-18 13:30:21 -07002072static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2073 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002074 if (fd == -1) {
2075 SLOGE("Error opening file %s", filename);
2076 return -1;
2077 }
2078
2079 char block[CRYPT_INPLACE_BUFSIZE];
2080 memset(block, 0, sizeof(block));
2081 if (unix_read(fd, block, sizeof(block)) < 0) {
2082 SLOGE("Error reading file %s", filename);
2083 close(fd);
2084 return -1;
2085 }
2086
2087 close(fd);
2088
2089 SHA256_CTX c;
2090 SHA256_Init(&c);
2091 SHA256_Update(&c, block, sizeof(block));
2092 SHA256_Final(buf, &c);
2093
2094 return 0;
2095}
2096
Paul Crowley81796e92020-02-07 11:27:49 -08002097static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2098 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002099 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002100 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002101
Paul Lawrence87999172014-02-20 12:21:31 -08002102 /* The size of the userdata partition, and add in the vold volumes below */
2103 tot_encryption_size = crypt_ftr->fs_size;
2104
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002105 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002106 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002107
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002108 if (rc == ENABLE_INPLACE_ERR_DEV) {
2109 /* Hack for b/17898962 */
2110 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2111 cryptfs_reboot(RebootType::reboot);
2112 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002113
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002114 if (!rc) {
2115 crypt_ftr->encrypted_upto = cur_encryption_done;
2116 }
Paul Lawrence87999172014-02-20 12:21:31 -08002117
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002118 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2119 /* The inplace routine never actually sets the progress to 100% due
2120 * to the round down nature of integer division, so set it here */
2121 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002122 }
2123
2124 return rc;
2125}
2126
Paul Crowleyb64933a2017-10-31 08:25:55 -07002127static int vold_unmountAll(void) {
2128 VolumeManager* vm = VolumeManager::Instance();
2129 return vm->unmountAll();
2130}
2131
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002132int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002133 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002134 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002135 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002136 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002137 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002138 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002139 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002140 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002141 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002142 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002143 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002144 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002145 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002146 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002147
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002148 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002149 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2150 /* An encryption was underway and was interrupted */
2151 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2152 crypt_ftr.encrypted_upto = 0;
2153 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002154
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002155 /* At this point, we are in an inconsistent state. Until we successfully
2156 complete encryption, a reboot will leave us broken. So mark the
2157 encryption failed in case that happens.
2158 On successfully completing encryption, remove this flag */
2159 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002160
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002161 put_crypt_ftr_and_key(&crypt_ftr);
2162 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2163 if (!check_ftr_sha(&crypt_ftr)) {
2164 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2165 put_crypt_ftr_and_key(&crypt_ftr);
2166 goto error_unencrypted;
2167 }
2168
2169 /* Doing a reboot-encryption*/
2170 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2171 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2172 rebootEncryption = true;
2173 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002174 } else {
2175 // We don't want to accidentally reference invalid data.
2176 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002177 }
2178
2179 property_get("ro.crypto.state", encrypted_state, "");
2180 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2181 SLOGE("Device is already running encrypted, aborting");
2182 goto error_unencrypted;
2183 }
2184
Tom Cherry4c5bde22019-01-29 14:34:01 -08002185 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002186
Ken Sumrall3ed82362011-01-28 23:31:16 -08002187 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002188 uint64_t nr_sec;
2189 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002190 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002191 goto error_unencrypted;
2192 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002193
2194 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002195 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002196 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002197 fs_size_sec = get_fs_size(real_blkdev.c_str());
2198 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002199
Paul Lawrence87999172014-02-20 12:21:31 -08002200 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002201
2202 if (fs_size_sec > max_fs_size_sec) {
2203 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2204 goto error_unencrypted;
2205 }
2206 }
2207
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002208 /* Get a wakelock as this may take a while, and we don't want the
2209 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2210 * wants to keep the screen on, it can grab a full wakelock.
2211 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002212 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002213 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002214
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002215 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002216 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002217 */
2218 property_set("vold.decrypt", "trigger_shutdown_framework");
2219 SLOGD("Just asked init to shut down class main\n");
2220
Jeff Sharkey9c484982015-03-31 10:35:33 -07002221 /* Ask vold to unmount all devices that it manages */
2222 if (vold_unmountAll()) {
2223 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002224 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002225
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002226 /* no_ui means we are being called from init, not settings.
2227 Now we always reboot from settings, so !no_ui means reboot
2228 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002229 if (!no_ui) {
2230 /* Try fallback, which is to reboot and try there */
2231 onlyCreateHeader = true;
2232 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2233 if (breadcrumb == 0) {
2234 SLOGE("Failed to create breadcrumb file");
2235 goto error_shutting_down;
2236 }
2237 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002238 }
2239
2240 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002241 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002242 /* Now that /data is unmounted, we need to mount a tmpfs
2243 * /data, set a property saying we're doing inplace encryption,
2244 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002245 */
xzj7e38a3a2018-10-12 10:17:11 +08002246 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002247 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002248 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002249 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002250 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002251 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002252
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002253 /* restart the framework. */
2254 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002255 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002256
Ken Sumrall92736ef2012-10-17 20:57:14 -07002257 /* Ugh, shutting down the framework is not synchronous, so until it
2258 * can be fixed, this horrible hack will wait a moment for it all to
2259 * shut down before proceeding. Without it, some devices cannot
2260 * restart the graphics services.
2261 */
2262 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002263 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002264
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002265 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002266 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002267 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002268 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2269 goto error_shutting_down;
2270 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002271
Tom Cherry4c5bde22019-01-29 14:34:01 -08002272 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002273 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002274 } else {
2275 crypt_ftr.fs_size = nr_sec;
2276 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002277 /* At this point, we are in an inconsistent state. Until we successfully
2278 complete encryption, a reboot will leave us broken. So mark the
2279 encryption failed in case that happens.
2280 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002281 if (onlyCreateHeader) {
2282 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2283 } else {
2284 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2285 }
Paul Lawrence87999172014-02-20 12:21:31 -08002286 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002287 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002288 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002289
Paul Lawrence87999172014-02-20 12:21:31 -08002290 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002291 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2292 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002293 SLOGE("Cannot create encrypted master key\n");
2294 goto error_shutting_down;
2295 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002296
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002297 /* Replace scrypted intermediate key if we are preparing for a reboot */
2298 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002299 unsigned char fake_master_key[MAX_KEY_LEN];
2300 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002301 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002302 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2303 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002304 }
2305
Paul Lawrence87999172014-02-20 12:21:31 -08002306 /* Write the key to the end of the partition */
2307 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002308
Paul Lawrence87999172014-02-20 12:21:31 -08002309 /* If any persistent data has been remembered, save it.
2310 * If none, create a valid empty table and save that.
2311 */
2312 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002313 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2314 if (pdata) {
2315 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2316 persist_data = pdata;
2317 }
Paul Lawrence87999172014-02-20 12:21:31 -08002318 }
2319 if (persist_data) {
2320 save_persistent_data();
2321 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002322 }
2323
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002324 if (onlyCreateHeader) {
2325 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002326 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002327 }
2328
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002329 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002330 /* startup service classes main and late_start */
2331 property_set("vold.decrypt", "trigger_restart_min_framework");
2332 SLOGD("Just triggered restart_min_framework\n");
2333
2334 /* OK, the framework is restarted and will soon be showing a
2335 * progress bar. Time to setup an encrypted mapping, and
2336 * either write a new filesystem, or encrypt in place updating
2337 * the progress bar as we work.
2338 */
2339 }
2340
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002341 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002342 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002343 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002344
Paul Lawrence87999172014-02-20 12:21:31 -08002345 /* If we are continuing, check checksums match */
2346 rc = 0;
2347 if (previously_encrypted_upto) {
2348 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002349 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002350
Paul Crowley14c8c072018-09-18 13:30:21 -07002351 if (!rc &&
2352 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002353 SLOGE("Checksums do not match - trigger wipe");
2354 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002355 }
2356 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002357
Paul Lawrence87999172014-02-20 12:21:31 -08002358 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002359 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002360 previously_encrypted_upto);
2361 }
2362
2363 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002364 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002365 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002366 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002367 SLOGE("Error calculating checksum for continuing encryption");
2368 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002369 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002370 }
2371
2372 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002373 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002374
Paul Crowley14c8c072018-09-18 13:30:21 -07002375 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002376 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002377 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002378
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002379 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002380 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2381 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002382 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002383 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002384
Paul Lawrence6bfed202014-07-28 12:47:22 -07002385 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002386
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002387 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2388 char value[PROPERTY_VALUE_MAX];
2389 property_get("ro.crypto.state", value, "");
2390 if (!strcmp(value, "")) {
2391 /* default encryption - continue first boot sequence */
2392 property_set("ro.crypto.state", "encrypted");
2393 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002394 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002395 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2396 // Bring up cryptkeeper that will check the password and set it
2397 property_set("vold.decrypt", "trigger_shutdown_framework");
2398 sleep(2);
2399 property_set("vold.encrypt_progress", "");
2400 cryptfs_trigger_restart_min_framework();
2401 } else {
2402 cryptfs_check_passwd(DEFAULT_PASSWORD);
2403 cryptfs_restart_internal(1);
2404 }
2405 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002406 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002407 sleep(2); /* Give the UI a chance to show 100% progress */
2408 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002409 }
Paul Lawrence87999172014-02-20 12:21:31 -08002410 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002411 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002412 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002413 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002414 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002415 char value[PROPERTY_VALUE_MAX];
2416
Ken Sumrall319369a2012-06-27 16:30:18 -07002417 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002418 if (!strcmp(value, "1")) {
2419 /* wipe data if encryption failed */
2420 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002421 std::string err;
2422 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002423 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002424 if (!write_bootloader_message(options, &err)) {
2425 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002426 }
Josh Gaofec44372017-08-28 13:22:55 -07002427 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002428 } else {
2429 /* set property to trigger dialog */
2430 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002431 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002432 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002433 }
2434
Ken Sumrall3ed82362011-01-28 23:31:16 -08002435 /* hrm, the encrypt step claims success, but the reboot failed.
2436 * This should not happen.
2437 * Set the property and return. Hope the framework can deal with it.
2438 */
2439 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002440 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002441
2442error_unencrypted:
2443 property_set("vold.encrypt_progress", "error_not_encrypted");
2444 return -1;
2445
2446error_shutting_down:
2447 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2448 * but the framework is stopped and not restarted to show the error, so it's up to
2449 * vold to restart the system.
2450 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002451 SLOGE(
2452 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2453 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002454 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002455
2456 /* shouldn't get here */
2457 property_set("vold.encrypt_progress", "error_shutting_down");
2458 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002459}
2460
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002461int cryptfs_enable(int type, const char* passwd, int no_ui) {
2462 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002463}
2464
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002465int cryptfs_enable_default(int no_ui) {
2466 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002467}
2468
Paul Crowley14c8c072018-09-18 13:30:21 -07002469int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002470 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002471 SLOGE("cryptfs_changepw not valid for file encryption");
2472 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002473 }
2474
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002475 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002476 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002477
2478 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002479 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002480 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002481 return -1;
2482 }
2483
Paul Lawrencef4faa572014-01-29 13:31:03 -08002484 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2485 SLOGE("Invalid crypt_type %d", crypt_type);
2486 return -1;
2487 }
2488
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002489 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002490 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002491 SLOGE("Error getting crypt footer and key");
2492 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002493 }
2494
Paul Lawrencef4faa572014-01-29 13:31:03 -08002495 crypt_ftr.crypt_type = crypt_type;
2496
Paul Crowley14c8c072018-09-18 13:30:21 -07002497 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2498 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002499 if (rc) {
2500 SLOGE("Encrypt master key failed: %d", rc);
2501 return -1;
2502 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002503 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002504 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002505
2506 return 0;
2507}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002508
Rubin Xu85c01f92014-10-13 12:49:54 +01002509static unsigned int persist_get_max_entries(int encrypted) {
2510 struct crypt_mnt_ftr crypt_ftr;
2511 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002512
2513 /* If encrypted, use the values from the crypt_ftr, otherwise
2514 * use the values for the current spec.
2515 */
2516 if (encrypted) {
2517 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002518 /* Something is wrong, assume no space for entries */
2519 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002520 }
2521 dsize = crypt_ftr.persist_data_size;
2522 } else {
2523 dsize = CRYPT_PERSIST_DATA_SIZE;
2524 }
2525
Rubin Xuf83cc612018-10-09 16:13:38 +01002526 if (dsize > sizeof(struct crypt_persist_data)) {
2527 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2528 } else {
2529 return 0;
2530 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002531}
2532
Paul Crowley14c8c072018-09-18 13:30:21 -07002533static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002534 unsigned int i;
2535
2536 if (persist_data == NULL) {
2537 return -1;
2538 }
2539 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2540 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2541 /* We found it! */
2542 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2543 return 0;
2544 }
2545 }
2546
2547 return -1;
2548}
2549
Paul Crowley14c8c072018-09-18 13:30:21 -07002550static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002551 unsigned int i;
2552 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002553 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002554
2555 if (persist_data == NULL) {
2556 return -1;
2557 }
2558
Rubin Xu85c01f92014-10-13 12:49:54 +01002559 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002560
2561 num = persist_data->persist_valid_entries;
2562
2563 for (i = 0; i < num; i++) {
2564 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2565 /* We found an existing entry, update it! */
2566 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2567 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2568 return 0;
2569 }
2570 }
2571
2572 /* We didn't find it, add it to the end, if there is room */
2573 if (persist_data->persist_valid_entries < max_persistent_entries) {
2574 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2575 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2576 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2577 persist_data->persist_valid_entries++;
2578 return 0;
2579 }
2580
2581 return -1;
2582}
2583
Rubin Xu85c01f92014-10-13 12:49:54 +01002584/**
2585 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2586 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2587 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002588int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002589 std::string key_ = key;
2590 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002591
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002592 std::string parsed_field;
2593 unsigned parsed_index;
2594
2595 std::string::size_type split = key_.find_last_of('_');
2596 if (split == std::string::npos) {
2597 parsed_field = key_;
2598 parsed_index = 0;
2599 } else {
2600 parsed_field = key_.substr(0, split);
2601 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002602 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002603
2604 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002605}
2606
2607/*
2608 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2609 * remaining entries starting from index will be deleted.
2610 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2611 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2612 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2613 *
2614 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002615static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002616 unsigned int i;
2617 unsigned int j;
2618 unsigned int num;
2619
2620 if (persist_data == NULL) {
2621 return PERSIST_DEL_KEY_ERROR_OTHER;
2622 }
2623
2624 num = persist_data->persist_valid_entries;
2625
Paul Crowley14c8c072018-09-18 13:30:21 -07002626 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002627 // Filter out to-be-deleted entries in place.
2628 for (i = 0; i < num; i++) {
2629 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2630 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2631 j++;
2632 }
2633 }
2634
2635 if (j < num) {
2636 persist_data->persist_valid_entries = j;
2637 // Zeroise the remaining entries
2638 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2639 return PERSIST_DEL_KEY_OK;
2640 } else {
2641 // Did not find an entry matching the given fieldname
2642 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2643 }
2644}
2645
Paul Crowley14c8c072018-09-18 13:30:21 -07002646static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002647 unsigned int i;
2648 unsigned int count;
2649
2650 if (persist_data == NULL) {
2651 return -1;
2652 }
2653
2654 count = 0;
2655 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2656 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2657 count++;
2658 }
2659 }
2660
2661 return count;
2662}
2663
Ken Sumrall160b4d62013-04-22 12:15:39 -07002664/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002665int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002666 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002667 SLOGE("Cannot get field when file encrypted");
2668 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002669 }
2670
Ken Sumrall160b4d62013-04-22 12:15:39 -07002671 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002672 /* CRYPTO_GETFIELD_OK is success,
2673 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2674 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2675 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002676 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002677 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2678 int i;
2679 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002680
2681 if (persist_data == NULL) {
2682 load_persistent_data();
2683 if (persist_data == NULL) {
2684 SLOGE("Getfield error, cannot load persistent data");
2685 goto out;
2686 }
2687 }
2688
Rubin Xu85c01f92014-10-13 12:49:54 +01002689 // Read value from persistent entries. If the original value is split into multiple entries,
2690 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002691 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002692 // 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 -07002693 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002694 // value too small
2695 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2696 goto out;
2697 }
2698 rc = CRYPTO_GETFIELD_OK;
2699
2700 for (i = 1; /* break explicitly */; i++) {
2701 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002702 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002703 // If the fieldname is very long, we stop as soon as it begins to overflow the
2704 // maximum field length. At this point we have in fact fully read out the original
2705 // value because cryptfs_setfield would not allow fields with longer names to be
2706 // written in the first place.
2707 break;
2708 }
2709 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002710 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2711 // value too small.
2712 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2713 goto out;
2714 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002715 } else {
2716 // Exhaust all entries.
2717 break;
2718 }
2719 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002720 } else {
2721 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002722 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002723 }
2724
2725out:
2726 return rc;
2727}
2728
2729/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002730int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002731 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002732 SLOGE("Cannot set field when file encrypted");
2733 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002734 }
2735
Ken Sumrall160b4d62013-04-22 12:15:39 -07002736 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002737 /* 0 is success, negative values are error */
2738 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002739 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002740 unsigned int field_id;
2741 char temp_field[PROPERTY_KEY_MAX];
2742 unsigned int num_entries;
2743 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002744
2745 if (persist_data == NULL) {
2746 load_persistent_data();
2747 if (persist_data == NULL) {
2748 SLOGE("Setfield error, cannot load persistent data");
2749 goto out;
2750 }
2751 }
2752
2753 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002754 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002755 encrypted = 1;
2756 }
2757
Rubin Xu85c01f92014-10-13 12:49:54 +01002758 // Compute the number of entries required to store value, each entry can store up to
2759 // (PROPERTY_VALUE_MAX - 1) chars
2760 if (strlen(value) == 0) {
2761 // Empty value also needs one entry to store.
2762 num_entries = 1;
2763 } else {
2764 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2765 }
2766
2767 max_keylen = strlen(fieldname);
2768 if (num_entries > 1) {
2769 // Need an extra "_%d" suffix.
2770 max_keylen += 1 + log10(num_entries);
2771 }
2772 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2773 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002774 goto out;
2775 }
2776
Rubin Xu85c01f92014-10-13 12:49:54 +01002777 // Make sure we have enough space to write the new value
2778 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2779 persist_get_max_entries(encrypted)) {
2780 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2781 goto out;
2782 }
2783
2784 // Now that we know persist_data has enough space for value, let's delete the old field first
2785 // to make up space.
2786 persist_del_keys(fieldname, 0);
2787
2788 if (persist_set_key(fieldname, value, encrypted)) {
2789 // fail to set key, should not happen as we have already checked the available space
2790 SLOGE("persist_set_key() error during setfield()");
2791 goto out;
2792 }
2793
2794 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002795 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002796
2797 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2798 // fail to set key, should not happen as we have already checked the available space.
2799 SLOGE("persist_set_key() error during setfield()");
2800 goto out;
2801 }
2802 }
2803
Ken Sumrall160b4d62013-04-22 12:15:39 -07002804 /* If we are running encrypted, save the persistent data now */
2805 if (encrypted) {
2806 if (save_persistent_data()) {
2807 SLOGE("Setfield error, cannot save persistent data");
2808 goto out;
2809 }
2810 }
2811
Rubin Xu85c01f92014-10-13 12:49:54 +01002812 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002813
2814out:
2815 return rc;
2816}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002817
2818/* Checks userdata. Attempt to mount the volume if default-
2819 * encrypted.
2820 * On success trigger next init phase and return 0.
2821 * Currently do not handle failure - see TODO below.
2822 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002823int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002824 int crypt_type = cryptfs_get_password_type();
2825 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2826 SLOGE("Bad crypt type - error");
2827 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002828 SLOGD(
2829 "Password is not default - "
2830 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002831 property_set("vold.decrypt", "trigger_restart_min_framework");
2832 return 0;
2833 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2834 SLOGD("Password is default - restarting filesystem");
2835 cryptfs_restart_internal(0);
2836 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002837 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002838 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002839 }
2840
Paul Lawrence6bfed202014-07-28 12:47:22 -07002841 /** Corrupt. Allow us to boot into framework, which will detect bad
2842 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002843 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002844 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002845 return 0;
2846}
2847
2848/* Returns type of the password, default, pattern, pin or password.
2849 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002850int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002851 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002852 SLOGE("cryptfs_get_password_type not valid for file encryption");
2853 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002854 }
2855
Paul Lawrencef4faa572014-01-29 13:31:03 -08002856 struct crypt_mnt_ftr crypt_ftr;
2857
2858 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2859 SLOGE("Error getting crypt footer and key\n");
2860 return -1;
2861 }
2862
Paul Lawrence6bfed202014-07-28 12:47:22 -07002863 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2864 return -1;
2865 }
2866
Paul Lawrencef4faa572014-01-29 13:31:03 -08002867 return crypt_ftr.crypt_type;
2868}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002869
Paul Crowley14c8c072018-09-18 13:30:21 -07002870const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002871 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002872 SLOGE("cryptfs_get_password not valid for file encryption");
2873 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002874 }
2875
Paul Lawrence399317e2014-03-10 13:20:50 -07002876 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002877 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002878 if (now.tv_sec < password_expiry_time) {
2879 return password;
2880 } else {
2881 cryptfs_clear_password();
2882 return 0;
2883 }
2884}
2885
Paul Crowley14c8c072018-09-18 13:30:21 -07002886void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002887 if (password) {
2888 size_t len = strlen(password);
2889 memset(password, 0, len);
2890 free(password);
2891 password = 0;
2892 password_expiry_time = 0;
2893 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002894}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002895
Paul Crowley14c8c072018-09-18 13:30:21 -07002896int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002897 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2898 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002899}