blob: 14314597e6f806c87be67cb00c849e3ca1401235 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Logan Chiend557d762018-05-02 11:36:45 +080017#define LOG_TAG "Cryptfs"
18
19#include "cryptfs.h"
20
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070021#include "Checkpoint.h"
Paul Crowley220567c2020-02-07 12:45:20 -080022#include "CryptoType.h"
Logan Chiend557d762018-05-02 11:36:45 +080023#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070024#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080025#include "Keymaster.h"
26#include "Process.h"
27#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070028#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080029#include "VoldUtil.h"
30#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080031
Eric Biggersed45ec32019-01-25 10:47:55 -080032#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080033#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080034#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080035#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080036#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080037#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070038#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070040#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070041#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070042#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080043#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080044#include <logwrap/logwrap.h>
45#include <openssl/evp.h>
46#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070048#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080049
50#include <ctype.h>
51#include <errno.h>
52#include <fcntl.h>
53#include <inttypes.h>
54#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080055#include <linux/kdev_t.h>
56#include <math.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080060#include <sys/mount.h>
61#include <sys/param.h>
62#include <sys/stat.h>
63#include <sys/types.h>
64#include <sys/wait.h>
65#include <time.h>
66#include <unistd.h>
67
Martijn Coenen26ad7b32020-02-13 16:20:52 +010068#include <chrono>
69#include <thread>
70
Wei Wang4375f1b2017-02-24 17:43:01 -080071extern "C" {
72#include <crypto_scrypt.h>
73}
Mark Salyzyn3e971272014-01-21 13:27:04 -080074
Eric Biggersed45ec32019-01-25 10:47:55 -080075using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080076using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080077using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080078using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080079using android::vold::KeyBuffer;
Paul Crowleyb3d018a2020-02-12 11:04:05 -080080using android::vold::KeyGeneration;
David Andersonb9224732019-05-13 13:02:54 -070081using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070082using namespace std::chrono_literals;
83
Paul Crowley73be12d2020-02-03 12:22:03 -080084/* The current cryptfs version */
85#define CURRENT_MAJOR_VERSION 1
86#define CURRENT_MINOR_VERSION 3
87
88#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
89#define CRYPT_PERSIST_DATA_SIZE 0x1000
90
91#define MAX_CRYPTO_TYPE_NAME_LEN 64
92
93#define MAX_KEY_LEN 48
94#define SALT_LEN 16
95#define SCRYPT_LEN 32
96
97/* definitions of flags in the structure below */
98#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
99#define CRYPT_ENCRYPTION_IN_PROGRESS \
100 0x2 /* Encryption partially completed, \
101 encrypted_upto valid*/
102#define CRYPT_INCONSISTENT_STATE \
103 0x4 /* Set when starting encryption, clear when \
104 exit cleanly, either through success or \
105 correctly marked partial encryption */
106#define CRYPT_DATA_CORRUPT \
107 0x8 /* Set when encryption is fine, but the \
108 underlying volume is corrupt */
109#define CRYPT_FORCE_ENCRYPTION \
110 0x10 /* Set when it is time to encrypt this \
111 volume on boot. Everything in this \
112 structure is set up correctly as \
113 though device is encrypted except \
114 that the master key is encrypted with the \
115 default password. */
116#define CRYPT_FORCE_COMPLETE \
117 0x20 /* Set when the above encryption cycle is \
118 complete. On next cryptkeeper entry, match \
119 the password. If it matches fix the master \
120 key and remove this flag. */
121
122/* Allowed values for type in the structure below */
123#define CRYPT_TYPE_PASSWORD \
124 0 /* master_key is encrypted with a password \
125 * Must be zero to be compatible with pre-L \
126 * devices where type is always password.*/
127#define CRYPT_TYPE_DEFAULT \
128 1 /* master_key is encrypted with default \
129 * password */
130#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
131#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
132#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
133
134#define CRYPT_MNT_MAGIC 0xD0B5B1C4
135#define PERSIST_DATA_MAGIC 0xE950CD44
136
137/* Key Derivation Function algorithms */
138#define KDF_PBKDF2 1
139#define KDF_SCRYPT 2
140/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
141#define KDF_SCRYPT_KEYMASTER 5
142
143/* Maximum allowed keymaster blob size. */
144#define KEYMASTER_BLOB_SIZE 2048
145
146/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
147#define __le8 unsigned char
148
149#if !defined(SHA256_DIGEST_LENGTH)
150#define SHA256_DIGEST_LENGTH 32
151#endif
152
153/* This structure starts 16,384 bytes before the end of a hardware
154 * partition that is encrypted, or in a separate partition. It's location
155 * is specified by a property set in init.<device>.rc.
156 * The structure allocates 48 bytes for a key, but the real key size is
157 * specified in the struct. Currently, the code is hardcoded to use 128
158 * bit keys.
159 * The fields after salt are only valid in rev 1.1 and later stuctures.
160 * Obviously, the filesystem does not include the last 16 kbytes
161 * of the partition if the crypt_mnt_ftr lives at the end of the
162 * partition.
163 */
164
165struct crypt_mnt_ftr {
166 __le32 magic; /* See above */
167 __le16 major_version;
168 __le16 minor_version;
169 __le32 ftr_size; /* in bytes, not including key following */
170 __le32 flags; /* See above */
171 __le32 keysize; /* in bytes */
172 __le32 crypt_type; /* how master_key is encrypted. Must be a
173 * CRYPT_TYPE_XXX value */
174 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
175 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
176 mount, set to 0 on successful mount */
177 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
178 needed to decrypt this
179 partition, null terminated */
180 __le32 spare2; /* ignored */
181 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
182 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
183 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
184 * on device with that info, either the footer of the
185 * real_blkdevice or the metadata partition. */
186
187 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
188 * persistent data table*/
189
190 __le8 kdf_type; /* The key derivation function used. */
191
192 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
193 __le8 N_factor; /* (1 << N) */
194 __le8 r_factor; /* (1 << r) */
195 __le8 p_factor; /* (1 << p) */
196 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
197 we have to stop (e.g. power low) this is the last
198 encrypted 512 byte sector.*/
199 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
200 set, hash of first block, used
201 to validate before continuing*/
202
203 /* key_master key, used to sign the derived key which is then used to generate
204 * the intermediate key
205 * This key should be used for no other purposes! We use this key to sign unpadded
206 * data, which is acceptable but only if the key is not reused elsewhere. */
207 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
208 __le32 keymaster_blob_size;
209
210 /* Store scrypt of salted intermediate key. When decryption fails, we can
211 check if this matches, and if it does, we know that the problem is with the
212 drive, and there is no point in asking the user for more passwords.
213
214 Note that if any part of this structure is corrupt, this will not match and
215 we will continue to believe the user entered the wrong password. In that
216 case the only solution is for the user to enter a password enough times to
217 force a wipe.
218
219 Note also that there is no need to worry about migration. If this data is
220 wrong, we simply won't recognise a right password, and will continue to
221 prompt. On the first password change, this value will be populated and
222 then we will be OK.
223 */
224 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
225
226 /* sha of this structure with this element set to zero
227 Used when encrypting on reboot to validate structure before doing something
228 fatal
229 */
230 unsigned char sha256[SHA256_DIGEST_LENGTH];
231};
232
233/* Persistant data that should be available before decryption.
234 * Things like airplane mode, locale and timezone are kept
235 * here and can be retrieved by the CryptKeeper UI to properly
236 * configure the phone before asking for the password
237 * This is only valid if the major and minor version above
238 * is set to 1.1 or higher.
239 *
240 * This is a 4K structure. There are 2 copies, and the code alternates
241 * writing one and then clearing the previous one. The reading
242 * code reads the first valid copy it finds, based on the magic number.
243 * The absolute offset to the first of the two copies is kept in rev 1.1
244 * and higher crypt_mnt_ftr structures.
245 */
246struct crypt_persist_entry {
247 char key[PROPERTY_KEY_MAX];
248 char val[PROPERTY_VALUE_MAX];
249};
250
251/* Should be exactly 4K in size */
252struct crypt_persist_data {
253 __le32 persist_magic;
254 __le32 persist_valid_entries;
255 __le32 persist_spare[30];
256 struct crypt_persist_entry persist_entry[0];
257};
258
259static int wait_and_unmount(const char* mountpoint, bool kill);
260
261typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
262 void* params);
263
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800264#define UNUSED __attribute__((unused))
265
Jason parks70a4b3f2011-01-28 10:10:47 -0600266#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800267
268constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
269constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700270constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800271
272// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700273static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600274
Paul Crowley14c8c072018-09-18 13:30:21 -0700275#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700276
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700277#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800278
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800279#define CRYPTO_BLOCK_DEVICE "userdata"
280
281#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
282
Ken Sumrall29d8da82011-05-18 17:20:07 -0700283#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700284#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700285
Ken Sumralle919efe2012-09-29 17:07:41 -0700286#define TABLE_LOAD_RETRIES 10
287
Shawn Willden47ba10d2014-09-03 17:07:06 -0600288#define RSA_KEY_SIZE 2048
289#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
290#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600291#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700292
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700293#define RETRY_MOUNT_ATTEMPTS 10
294#define RETRY_MOUNT_DELAY_SECONDS 1
295
Paul Crowley5afbc622017-11-27 09:42:17 -0800296#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
297
Paul Crowley73473332017-11-21 15:43:51 -0800298static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
299
Greg Kaiser59ad0182018-02-16 13:01:36 -0800300static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700301static char* saved_mount_point;
302static int master_key_saved = 0;
303static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800304
Paul Crowley220567c2020-02-07 12:45:20 -0800305constexpr CryptoType aes_128_cbc = CryptoType()
306 .set_config_name("AES-128-CBC")
307 .set_kernel_name("aes-cbc-essiv:sha256")
308 .set_keysize(16);
309
310constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
311
312static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
313 array_length(supported_crypto_types)),
314 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
315 "incompletely constructed.");
316
317static const CryptoType& get_crypto_type() {
318 // We only want to parse this read-only property once. But we need to wait
319 // until the system is initialized before we can read it. So we use a static
320 // scoped within this function to get it only once.
321 static CryptoType crypto_type =
322 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
323 aes_128_cbc, "ro.crypto.fde_algorithm");
324 return crypto_type;
325}
326
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800327const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800328 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800329}
330
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700331/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700332static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000333 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700334}
335
336/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700337static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800338 if (ftr->keymaster_blob_size) {
339 SLOGI("Already have key");
340 return 0;
341 }
342
Paul Crowley14c8c072018-09-18 13:30:21 -0700343 int rc = keymaster_create_key_for_cryptfs_scrypt(
344 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
345 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000346 if (rc) {
347 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800348 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000349 ftr->keymaster_blob_size = 0;
350 }
351 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700352 return -1;
353 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000354 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700355}
356
Shawn Willdene17a9c42014-09-08 13:04:08 -0600357/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700358static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
359 const size_t object_size, unsigned char** signature,
360 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600361 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600362 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600363 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600364
Shawn Willdene17a9c42014-09-08 13:04:08 -0600365 // To sign a message with RSA, the message must satisfy two
366 // constraints:
367 //
368 // 1. The message, when interpreted as a big-endian numeric value, must
369 // be strictly less than the public modulus of the RSA key. Note
370 // that because the most significant bit of the public modulus is
371 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
372 // key), an n-bit message with most significant bit 0 always
373 // satisfies this requirement.
374 //
375 // 2. The message must have the same length in bits as the public
376 // modulus of the RSA key. This requirement isn't mathematically
377 // necessary, but is necessary to ensure consistency in
378 // implementations.
379 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600380 case KDF_SCRYPT_KEYMASTER:
381 // This ensures the most significant byte of the signed message
382 // is zero. We could have zero-padded to the left instead, but
383 // this approach is slightly more robust against changes in
384 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600385 // so) because we really should be using a proper deterministic
386 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800387 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600388 SLOGI("Signing safely-padded object");
389 break;
390 default:
391 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000392 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600393 }
Paul Crowley73473332017-11-21 15:43:51 -0800394 for (;;) {
395 auto result = keymaster_sign_object_for_cryptfs_scrypt(
396 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
397 to_sign_size, signature, signature_size);
398 switch (result) {
399 case KeymasterSignResult::ok:
400 return 0;
401 case KeymasterSignResult::upgrade:
402 break;
403 default:
404 return -1;
405 }
406 SLOGD("Upgrading key");
407 if (keymaster_upgrade_key_for_cryptfs_scrypt(
408 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
409 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
410 &ftr->keymaster_blob_size) != 0) {
411 SLOGE("Failed to upgrade key");
412 return -1;
413 }
414 if (put_crypt_ftr_and_key(ftr) != 0) {
415 SLOGE("Failed to write upgraded key to disk");
416 }
417 SLOGD("Key upgraded successfully");
418 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600419}
420
Paul Lawrence399317e2014-03-10 13:20:50 -0700421/* Store password when userdata is successfully decrypted and mounted.
422 * Cleared by cryptfs_clear_password
423 *
424 * To avoid a double prompt at boot, we need to store the CryptKeeper
425 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
426 * Since the entire framework is torn down and rebuilt after encryption,
427 * we have to use a daemon or similar to store the password. Since vold
428 * is secured against IPC except from system processes, it seems a reasonable
429 * place to store this.
430 *
431 * password should be cleared once it has been used.
432 *
433 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800434 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700435static char* password = 0;
436static int password_expiry_time = 0;
437static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800438
Paul Crowley14c8c072018-09-18 13:30:21 -0700439enum class RebootType { reboot, recovery, shutdown };
440static void cryptfs_reboot(RebootType rt) {
441 switch (rt) {
442 case RebootType::reboot:
443 property_set(ANDROID_RB_PROPERTY, "reboot");
444 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800445
Paul Crowley14c8c072018-09-18 13:30:21 -0700446 case RebootType::recovery:
447 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
448 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800449
Paul Crowley14c8c072018-09-18 13:30:21 -0700450 case RebootType::shutdown:
451 property_set(ANDROID_RB_PROPERTY, "shutdown");
452 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700453 }
Paul Lawrence87999172014-02-20 12:21:31 -0800454
Ken Sumralladfba362013-06-04 16:37:52 -0700455 sleep(20);
456
457 /* Shouldn't get here, reboot should happen before sleep times out */
458 return;
459}
460
Kenny Rootc4c70f12013-06-14 12:11:38 -0700461/**
462 * Gets the default device scrypt parameters for key derivation time tuning.
463 * The parameters should lead to about one second derivation time for the
464 * given device.
465 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700466static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700467 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000468 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700469
Paul Crowley63c18d32016-02-10 14:02:47 +0000470 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
471 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
472 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
473 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700474 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000475 ftr->N_factor = Nf;
476 ftr->r_factor = rf;
477 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700478}
479
Tom Cherry4c5bde22019-01-29 14:34:01 -0800480static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800481 int fd, block_size;
482 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200483 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800484
Paul Crowley14c8c072018-09-18 13:30:21 -0700485 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800486 SLOGE("Cannot open device to get filesystem size ");
487 return 0;
488 }
489
490 if (lseek64(fd, 1024, SEEK_SET) < 0) {
491 SLOGE("Cannot seek to superblock");
492 return 0;
493 }
494
495 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
496 SLOGE("Cannot read superblock");
497 return 0;
498 }
499
500 close(fd);
501
Daniel Rosenberge82df162014-08-15 22:19:23 +0000502 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
503 SLOGE("Not a valid ext4 superblock");
504 return 0;
505 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800506 block_size = 1024 << sb.s_log_block_size;
507 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200508 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800509
510 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200511 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800512}
513
Tom Cherry4c5bde22019-01-29 14:34:01 -0800514static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
515 for (const auto& entry : fstab_default) {
516 if (!entry.fs_mgr_flags.vold_managed &&
517 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
518 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
519 if (key_loc != nullptr) {
520 *key_loc = entry.key_loc;
521 }
522 if (real_blk_device != nullptr) {
523 *real_blk_device = entry.blk_device;
524 }
525 return;
526 }
527 }
528}
529
Paul Crowley14c8c072018-09-18 13:30:21 -0700530static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
531 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200532 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700533 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700534 char key_loc[PROPERTY_VALUE_MAX];
535 char real_blkdev[PROPERTY_VALUE_MAX];
536 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700537
Paul Crowley14c8c072018-09-18 13:30:21 -0700538 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800539 std::string key_loc;
540 std::string real_blkdev;
541 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700542
Tom Cherry4c5bde22019-01-29 14:34:01 -0800543 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200544 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700545 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
546 * encryption info footer and key, and plenty of bytes to spare for future
547 * growth.
548 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800549 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200550 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700551 cached_data = 1;
552 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800553 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700554 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700555 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800556 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700557 cached_off = 0;
558 cached_data = 1;
559 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700560 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700561
Paul Crowley14c8c072018-09-18 13:30:21 -0700562 if (cached_data) {
563 if (metadata_fname) {
564 *metadata_fname = cached_metadata_fname;
565 }
566 if (off) {
567 *off = cached_off;
568 }
569 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700570 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700571
Paul Crowley14c8c072018-09-18 13:30:21 -0700572 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700573}
574
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800575/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700576static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800577 SHA256_CTX c;
578 SHA256_Init(&c);
579 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
580 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
581 SHA256_Final(crypt_ftr->sha256, &c);
582}
583
Ken Sumralle8744072011-01-18 22:01:55 -0800584/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800585 * update the failed mount count but not change the key.
586 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700587static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
588 int fd;
589 unsigned int cnt;
590 /* starting_off is set to the SEEK_SET offset
591 * where the crypto structure starts
592 */
593 off64_t starting_off;
594 int rc = -1;
595 char* fname = NULL;
596 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800597
Paul Crowley14c8c072018-09-18 13:30:21 -0700598 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800599
Paul Crowley14c8c072018-09-18 13:30:21 -0700600 if (get_crypt_ftr_info(&fname, &starting_off)) {
601 SLOGE("Unable to get crypt_ftr_info\n");
602 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800603 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700604 if (fname[0] != '/') {
605 SLOGE("Unexpected value for crypto key location\n");
606 return -1;
607 }
608 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
609 SLOGE("Cannot open footer file %s for put\n", fname);
610 return -1;
611 }
Ken Sumralle8744072011-01-18 22:01:55 -0800612
Paul Crowley14c8c072018-09-18 13:30:21 -0700613 /* Seek to the start of the crypt footer */
614 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
615 SLOGE("Cannot seek to real block device footer\n");
616 goto errout;
617 }
618
619 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
620 SLOGE("Cannot write real block device footer\n");
621 goto errout;
622 }
623
624 fstat(fd, &statbuf);
625 /* If the keys are kept on a raw block device, do not try to truncate it. */
626 if (S_ISREG(statbuf.st_mode)) {
627 if (ftruncate(fd, 0x4000)) {
628 SLOGE("Cannot set footer file size\n");
629 goto errout;
630 }
631 }
632
633 /* Success! */
634 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800635
636errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700637 close(fd);
638 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800639}
640
Paul Crowley14c8c072018-09-18 13:30:21 -0700641static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800642 struct crypt_mnt_ftr copy;
643 memcpy(&copy, crypt_ftr, sizeof(copy));
644 set_ftr_sha(&copy);
645 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
646}
647
Paul Crowley14c8c072018-09-18 13:30:21 -0700648static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700649 return TEMP_FAILURE_RETRY(read(fd, buff, len));
650}
651
Paul Crowley14c8c072018-09-18 13:30:21 -0700652static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700653 return TEMP_FAILURE_RETRY(write(fd, buff, len));
654}
655
Paul Crowley14c8c072018-09-18 13:30:21 -0700656static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700657 memset(pdata, 0, len);
658 pdata->persist_magic = PERSIST_DATA_MAGIC;
659 pdata->persist_valid_entries = 0;
660}
661
662/* A routine to update the passed in crypt_ftr to the lastest version.
663 * fd is open read/write on the device that holds the crypto footer and persistent
664 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
665 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
666 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700667static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700668 int orig_major = crypt_ftr->major_version;
669 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670
Kenny Root7434b312013-06-14 11:29:53 -0700671 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700672 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700673 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700674
Kenny Rootc4c70f12013-06-14 12:11:38 -0700675 SLOGW("upgrading crypto footer to 1.1");
676
Paul Crowley14c8c072018-09-18 13:30:21 -0700677 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700678 if (pdata == NULL) {
679 SLOGE("Cannot allocate persisent data\n");
680 return;
681 }
682 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
683
684 /* Need to initialize the persistent data area */
685 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
686 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100687 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700688 return;
689 }
690 /* Write all zeros to the first copy, making it invalid */
691 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
692
693 /* Write a valid but empty structure to the second copy */
694 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
695 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
696
697 /* Update the footer */
698 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
699 crypt_ftr->persist_data_offset[0] = pdata_offset;
700 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
701 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100702 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700703 }
704
Paul Lawrencef4faa572014-01-29 13:31:03 -0800705 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700706 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800707 /* But keep the old kdf_type.
708 * It will get updated later to KDF_SCRYPT after the password has been verified.
709 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700710 crypt_ftr->kdf_type = KDF_PBKDF2;
711 get_device_scrypt_params(crypt_ftr);
712 crypt_ftr->minor_version = 2;
713 }
714
Paul Lawrencef4faa572014-01-29 13:31:03 -0800715 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
716 SLOGW("upgrading crypto footer to 1.3");
717 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
718 crypt_ftr->minor_version = 3;
719 }
720
Kenny Root7434b312013-06-14 11:29:53 -0700721 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
722 if (lseek64(fd, offset, SEEK_SET) == -1) {
723 SLOGE("Cannot seek to crypt footer\n");
724 return;
725 }
726 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700727 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700728}
729
Paul Crowley14c8c072018-09-18 13:30:21 -0700730static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
731 int fd;
732 unsigned int cnt;
733 off64_t starting_off;
734 int rc = -1;
735 char* fname = NULL;
736 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737
Paul Crowley14c8c072018-09-18 13:30:21 -0700738 if (get_crypt_ftr_info(&fname, &starting_off)) {
739 SLOGE("Unable to get crypt_ftr_info\n");
740 return -1;
741 }
742 if (fname[0] != '/') {
743 SLOGE("Unexpected value for crypto key location\n");
744 return -1;
745 }
746 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
747 SLOGE("Cannot open footer file %s for get\n", fname);
748 return -1;
749 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800750
Paul Crowley14c8c072018-09-18 13:30:21 -0700751 /* Make sure it's 16 Kbytes in length */
752 fstat(fd, &statbuf);
753 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
754 SLOGE("footer file %s is not the expected size!\n", fname);
755 goto errout;
756 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700757
Paul Crowley14c8c072018-09-18 13:30:21 -0700758 /* Seek to the start of the crypt footer */
759 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
760 SLOGE("Cannot seek to real block device footer\n");
761 goto errout;
762 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700763
Paul Crowley14c8c072018-09-18 13:30:21 -0700764 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
765 SLOGE("Cannot read real block device footer\n");
766 goto errout;
767 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800768
Paul Crowley14c8c072018-09-18 13:30:21 -0700769 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
770 SLOGE("Bad magic for real block device %s\n", fname);
771 goto errout;
772 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800773
Paul Crowley14c8c072018-09-18 13:30:21 -0700774 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
775 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
776 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
777 goto errout;
778 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800779
Paul Crowley14c8c072018-09-18 13:30:21 -0700780 // We risk buffer overflows with oversized keys, so we just reject them.
781 // 0-sized keys are problematic (essentially by-passing encryption), and
782 // AES-CBC key wrapping only works for multiples of 16 bytes.
783 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
784 (crypt_ftr->keysize > MAX_KEY_LEN)) {
785 SLOGE(
786 "Invalid keysize (%u) for block device %s; Must be non-zero, "
787 "divisible by 16, and <= %d\n",
788 crypt_ftr->keysize, fname, MAX_KEY_LEN);
789 goto errout;
790 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800791
Paul Crowley14c8c072018-09-18 13:30:21 -0700792 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
793 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
794 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
795 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800796
Paul Crowley14c8c072018-09-18 13:30:21 -0700797 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
798 * copy on disk before returning.
799 */
800 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
801 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
802 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800803
Paul Crowley14c8c072018-09-18 13:30:21 -0700804 /* Success! */
805 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800806
807errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700808 close(fd);
809 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800810}
811
Paul Crowley14c8c072018-09-18 13:30:21 -0700812static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700813 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
814 crypt_ftr->persist_data_offset[1]) {
815 SLOGE("Crypt_ftr persist data regions overlap");
816 return -1;
817 }
818
819 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
820 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
821 return -1;
822 }
823
824 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700825 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700826 CRYPT_FOOTER_OFFSET) {
827 SLOGE("Persistent data extends past crypto footer");
828 return -1;
829 }
830
831 return 0;
832}
833
Paul Crowley14c8c072018-09-18 13:30:21 -0700834static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700836 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700837 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700838 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700839 int found = 0;
840 int fd;
841 int ret;
842 int i;
843
844 if (persist_data) {
845 /* Nothing to do, we've already loaded or initialized it */
846 return 0;
847 }
848
Ken Sumrall160b4d62013-04-22 12:15:39 -0700849 /* If not encrypted, just allocate an empty table and initialize it */
850 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700851 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800852 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700853 if (pdata) {
854 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
855 persist_data = pdata;
856 return 0;
857 }
858 return -1;
859 }
860
Paul Crowley14c8c072018-09-18 13:30:21 -0700861 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700862 return -1;
863 }
864
Paul Crowley14c8c072018-09-18 13:30:21 -0700865 if ((crypt_ftr.major_version < 1) ||
866 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700867 SLOGE("Crypt_ftr version doesn't support persistent data");
868 return -1;
869 }
870
871 if (get_crypt_ftr_info(&fname, NULL)) {
872 return -1;
873 }
874
875 ret = validate_persistent_data_storage(&crypt_ftr);
876 if (ret) {
877 return -1;
878 }
879
Paul Crowley14c8c072018-09-18 13:30:21 -0700880 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700881 if (fd < 0) {
882 SLOGE("Cannot open %s metadata file", fname);
883 return -1;
884 }
885
Wei Wang4375f1b2017-02-24 17:43:01 -0800886 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800887 if (pdata == NULL) {
888 SLOGE("Cannot allocate memory for persistent data");
889 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700890 }
891
892 for (i = 0; i < 2; i++) {
893 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
894 SLOGE("Cannot seek to read persistent data on %s", fname);
895 goto err2;
896 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700897 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700898 SLOGE("Error reading persistent data on iteration %d", i);
899 goto err2;
900 }
901 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
902 found = 1;
903 break;
904 }
905 }
906
907 if (!found) {
908 SLOGI("Could not find valid persistent data, creating");
909 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
910 }
911
912 /* Success */
913 persist_data = pdata;
914 close(fd);
915 return 0;
916
917err2:
918 free(pdata);
919
920err:
921 close(fd);
922 return -1;
923}
924
Paul Crowley14c8c072018-09-18 13:30:21 -0700925static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700926 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700927 struct crypt_persist_data* pdata;
928 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700929 off64_t write_offset;
930 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700931 int fd;
932 int ret;
933
934 if (persist_data == NULL) {
935 SLOGE("No persistent data to save");
936 return -1;
937 }
938
Paul Crowley14c8c072018-09-18 13:30:21 -0700939 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700940 return -1;
941 }
942
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 if ((crypt_ftr.major_version < 1) ||
944 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700945 SLOGE("Crypt_ftr version doesn't support persistent data");
946 return -1;
947 }
948
949 ret = validate_persistent_data_storage(&crypt_ftr);
950 if (ret) {
951 return -1;
952 }
953
954 if (get_crypt_ftr_info(&fname, NULL)) {
955 return -1;
956 }
957
Paul Crowley14c8c072018-09-18 13:30:21 -0700958 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700959 if (fd < 0) {
960 SLOGE("Cannot open %s metadata file", fname);
961 return -1;
962 }
963
Wei Wang4375f1b2017-02-24 17:43:01 -0800964 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700965 if (pdata == NULL) {
966 SLOGE("Cannot allocate persistant data");
967 goto err;
968 }
969
970 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
971 SLOGE("Cannot seek to read persistent data on %s", fname);
972 goto err2;
973 }
974
975 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700976 SLOGE("Error reading persistent data before save");
977 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700978 }
979
980 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
981 /* The first copy is the curent valid copy, so write to
982 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700983 write_offset = crypt_ftr.persist_data_offset[1];
984 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700985 } else {
986 /* The second copy must be the valid copy, so write to
987 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700988 write_offset = crypt_ftr.persist_data_offset[0];
989 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700990 }
991
992 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100993 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700994 SLOGE("Cannot seek to write persistent data");
995 goto err2;
996 }
997 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700998 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100999 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001000 SLOGE("Cannot seek to erase previous persistent data");
1001 goto err2;
1002 }
1003 fsync(fd);
1004 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001005 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001006 SLOGE("Cannot write to erase previous persistent data");
1007 goto err2;
1008 }
1009 fsync(fd);
1010 } else {
1011 SLOGE("Cannot write to save persistent data");
1012 goto err2;
1013 }
1014
1015 /* Success */
1016 free(pdata);
1017 close(fd);
1018 return 0;
1019
1020err2:
1021 free(pdata);
1022err:
1023 close(fd);
1024 return -1;
1025}
1026
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001027/* Convert a binary key of specified length into an ascii hex string equivalent,
1028 * without the leading 0x and with null termination
1029 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001030static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1031 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001032 unsigned int i, a;
1033 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001034
Paul Crowley14c8c072018-09-18 13:30:21 -07001035 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001036 /* For each byte, write out two ascii hex digits */
1037 nibble = (master_key[i] >> 4) & 0xf;
1038 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001039
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001040 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001041 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001042 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001043
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001044 /* Add the null termination */
1045 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001046}
1047
Eric Biggersed45ec32019-01-25 10:47:55 -08001048/*
1049 * If the ro.crypto.fde_sector_size system property is set, append the
1050 * parameters to make dm-crypt use the specified crypto sector size and round
1051 * the crypto device size down to a crypto sector boundary.
1052 */
David Andersonb9224732019-05-13 13:02:54 -07001053static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001054 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001055 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001056
Eric Biggersed45ec32019-01-25 10:47:55 -08001057 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1058 unsigned int sector_size;
1059
1060 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1061 (sector_size & (sector_size - 1)) != 0) {
1062 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1063 DM_CRYPT_SECTOR_SIZE, value);
1064 return -1;
1065 }
1066
David Andersonb9224732019-05-13 13:02:54 -07001067 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001068
1069 // With this option, IVs will match the sector numbering, instead
1070 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001071 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001072
1073 // Round the crypto device size down to a crypto sector boundary.
1074 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001075 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001076 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001077}
1078
Paul Crowley5afbc622017-11-27 09:42:17 -08001079static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001080 const char* real_blk_name, std::string* crypto_blk_name,
1081 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001082 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001083
David Andersonb9224732019-05-13 13:02:54 -07001084 // We need two ASCII characters to represent each byte, and need space for
1085 // the '\0' terminator.
1086 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1087 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001088
David Andersonb9224732019-05-13 13:02:54 -07001089 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1090 (const char*)crypt_ftr->crypto_type_name,
1091 master_key_ascii, 0, real_blk_name, 0);
1092 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001093
Paul Crowley5afbc622017-11-27 09:42:17 -08001094 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001095 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001096 }
David Andersonb9224732019-05-13 13:02:54 -07001097 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001098 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001099 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001100 }
David Andersonb9224732019-05-13 13:02:54 -07001101
1102 DmTable table;
1103 table.AddTarget(std::move(target));
1104
1105 int load_count = 1;
1106 while (load_count < TABLE_LOAD_RETRIES) {
1107 if (dm.CreateDevice(name, table)) {
1108 break;
1109 }
1110 load_count++;
1111 }
1112
1113 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001114 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001115 return -1;
1116 }
1117 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001118 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1119 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120
Paul Crowley81796e92020-02-07 11:27:49 -08001121 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001122 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1123 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001124 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125
Paul Crowleycfe39722018-10-30 15:59:24 -07001126 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001127 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001128 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001129 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001130 }
David Andersonb9224732019-05-13 13:02:54 -07001131 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001132}
1133
David Andersonb9224732019-05-13 13:02:54 -07001134static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001135 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001136 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001137 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1138 // to delete the device fails with EBUSY; for now, work around this by retrying.
1139 int tries = 5;
1140 while (tries-- > 0) {
1141 ret = dm.DeleteDevice(name);
1142 if (ret || errno != EBUSY) {
1143 break;
1144 }
1145 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1146 strerror(errno));
1147 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1148 }
1149 if (!ret) {
1150 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001151 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001152 }
David Andersonb9224732019-05-13 13:02:54 -07001153 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154}
1155
Paul Crowley14c8c072018-09-18 13:30:21 -07001156static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1157 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001158 SLOGI("Using pbkdf2 for cryptfs KDF");
1159
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001160 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001161 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1162 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001163}
1164
Paul Crowley14c8c072018-09-18 13:30:21 -07001165static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001166 SLOGI("Using scrypt for cryptfs KDF");
1167
Paul Crowley14c8c072018-09-18 13:30:21 -07001168 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001169
1170 int N = 1 << ftr->N_factor;
1171 int r = 1 << ftr->r_factor;
1172 int p = 1 << ftr->p_factor;
1173
1174 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001175 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001176 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001177
Paul Crowley14c8c072018-09-18 13:30:21 -07001178 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001179}
1180
Paul Crowley14c8c072018-09-18 13:30:21 -07001181static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1182 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001183 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1184
1185 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001186 size_t signature_size;
1187 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001188 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001189
1190 int N = 1 << ftr->N_factor;
1191 int r = 1 << ftr->r_factor;
1192 int p = 1 << ftr->p_factor;
1193
Paul Crowley14c8c072018-09-18 13:30:21 -07001194 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001195 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001196
1197 if (rc) {
1198 SLOGE("scrypt failed");
1199 return -1;
1200 }
1201
Paul Crowley14c8c072018-09-18 13:30:21 -07001202 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001203 SLOGE("Signing failed");
1204 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001205 }
1206
Paul Crowley14c8c072018-09-18 13:30:21 -07001207 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1208 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001209 free(signature);
1210
1211 if (rc) {
1212 SLOGE("scrypt failed");
1213 return -1;
1214 }
1215
1216 return 0;
1217}
1218
Paul Crowley14c8c072018-09-18 13:30:21 -07001219static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1220 const unsigned char* decrypted_master_key,
1221 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1222 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001223 EVP_CIPHER_CTX e_ctx;
1224 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001225 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001226
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001227 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001228 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001229
1230 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001231 case KDF_SCRYPT_KEYMASTER:
1232 if (keymaster_create_key(crypt_ftr)) {
1233 SLOGE("keymaster_create_key failed");
1234 return -1;
1235 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001236
Paul Crowley14c8c072018-09-18 13:30:21 -07001237 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1238 SLOGE("scrypt failed");
1239 return -1;
1240 }
1241 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001242
Paul Crowley14c8c072018-09-18 13:30:21 -07001243 case KDF_SCRYPT:
1244 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1245 SLOGE("scrypt failed");
1246 return -1;
1247 }
1248 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001249
Paul Crowley14c8c072018-09-18 13:30:21 -07001250 default:
1251 SLOGE("Invalid kdf_type");
1252 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001253 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001254
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001255 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001256 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001257 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1258 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259 SLOGE("EVP_EncryptInit failed\n");
1260 return -1;
1261 }
1262 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001263
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001264 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001265 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1266 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001267 SLOGE("EVP_EncryptUpdate failed\n");
1268 return -1;
1269 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001270 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001271 SLOGE("EVP_EncryptFinal failed\n");
1272 return -1;
1273 }
1274
Greg Kaiser59ad0182018-02-16 13:01:36 -08001275 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001276 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1277 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001278 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001279
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001280 /* Store the scrypt of the intermediate key, so we can validate if it's a
1281 password error or mount error when things go wrong.
1282 Note there's no need to check for errors, since if this is incorrect, we
1283 simply won't wipe userdata, which is the correct default behavior
1284 */
1285 int N = 1 << crypt_ftr->N_factor;
1286 int r = 1 << crypt_ftr->r_factor;
1287 int p = 1 << crypt_ftr->p_factor;
1288
Paul Crowley14c8c072018-09-18 13:30:21 -07001289 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1290 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001291 sizeof(crypt_ftr->scrypted_intermediate_key));
1292
1293 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001294 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001295 }
1296
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001297 EVP_CIPHER_CTX_cleanup(&e_ctx);
1298
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001299 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001300}
1301
Paul Crowley14c8c072018-09-18 13:30:21 -07001302static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1303 const unsigned char* encrypted_master_key, size_t keysize,
1304 unsigned char* decrypted_master_key, kdf_func kdf,
1305 void* kdf_params, unsigned char** intermediate_key,
1306 size_t* intermediate_key_size) {
1307 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1308 EVP_CIPHER_CTX d_ctx;
1309 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001310
Paul Crowley14c8c072018-09-18 13:30:21 -07001311 /* Turn the password into an intermediate key and IV that can decrypt the
1312 master key */
1313 if (kdf(passwd, salt, ikey, kdf_params)) {
1314 SLOGE("kdf failed");
1315 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001316 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001317
Paul Crowley14c8c072018-09-18 13:30:21 -07001318 /* Initialize the decryption engine */
1319 EVP_CIPHER_CTX_init(&d_ctx);
1320 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1321 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1322 return -1;
1323 }
1324 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1325 /* Decrypt the master key */
1326 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1327 keysize)) {
1328 return -1;
1329 }
1330 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1331 return -1;
1332 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001333
Paul Crowley14c8c072018-09-18 13:30:21 -07001334 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1335 return -1;
1336 }
1337
1338 /* Copy intermediate key if needed by params */
1339 if (intermediate_key && intermediate_key_size) {
1340 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1341 if (*intermediate_key) {
1342 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1343 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1344 }
1345 }
1346
1347 EVP_CIPHER_CTX_cleanup(&d_ctx);
1348
1349 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001350}
1351
Paul Crowley14c8c072018-09-18 13:30:21 -07001352static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001353 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001354 *kdf = scrypt_keymaster;
1355 *kdf_params = ftr;
1356 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001357 *kdf = scrypt;
1358 *kdf_params = ftr;
1359 } else {
1360 *kdf = pbkdf2;
1361 *kdf_params = NULL;
1362 }
1363}
1364
Paul Crowley14c8c072018-09-18 13:30:21 -07001365static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1366 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1367 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001368 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001369 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001370 int ret;
1371
1372 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001373 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1374 decrypted_master_key, kdf, kdf_params, intermediate_key,
1375 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001376 if (ret != 0) {
1377 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001378 }
1379
1380 return ret;
1381}
1382
Paul Crowley14c8c072018-09-18 13:30:21 -07001383static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1384 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001385 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001386
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001387 /* Get some random bits for a key and salt */
1388 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1389 return -1;
1390 }
1391 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1392 return -1;
1393 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001394
1395 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001396 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001397}
1398
Paul Crowley73be12d2020-02-03 12:22:03 -08001399static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001400 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001401#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001402
1403 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001404 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001405 if (umount(mountpoint) == 0) {
1406 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001407 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001408
1409 if (errno == EINVAL) {
1410 /* EINVAL is returned if the directory is not a mountpoint,
1411 * i.e. there is no filesystem mounted there. So just get out.
1412 */
1413 break;
1414 }
1415
1416 err = errno;
1417
1418 /* If allowed, be increasingly aggressive before the last two retries */
1419 if (kill) {
1420 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1421 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001422 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001423 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1424 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001425 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001426 }
1427 }
1428
1429 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430 }
1431
1432 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001433 SLOGD("unmounting %s succeeded\n", mountpoint);
1434 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001436 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1437 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1438 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001439 }
1440
1441 return rc;
1442}
1443
Paul Crowley14c8c072018-09-18 13:30:21 -07001444static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001445 // NOTE: post_fs_data results in init calling back around to vold, so all
1446 // callers to this method must be async
1447
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001448 /* Do the prep of the /data filesystem */
1449 property_set("vold.post_fs_data_done", "0");
1450 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001451 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001452
Ken Sumrallc5872692013-05-14 15:26:31 -07001453 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001454 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001455 /* We timed out to prep /data in time. Continue wait. */
1456 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001457 }
Wei Wang42e38102017-06-07 10:46:12 -07001458 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001459}
1460
Paul Crowley14c8c072018-09-18 13:30:21 -07001461static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001462 // Mark the footer as bad
1463 struct crypt_mnt_ftr crypt_ftr;
1464 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1465 SLOGE("Failed to get crypto footer - panic");
1466 return;
1467 }
1468
1469 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1470 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1471 SLOGE("Failed to set crypto footer - panic");
1472 return;
1473 }
1474}
1475
Paul Crowley14c8c072018-09-18 13:30:21 -07001476static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001477 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001478 SLOGE("Failed to mount tmpfs on data - panic");
1479 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001480 }
1481
1482 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1483 SLOGE("Failed to trigger post fs data - panic");
1484 return;
1485 }
1486
1487 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1488 SLOGE("Failed to trigger restart min framework - panic");
1489 return;
1490 }
1491}
1492
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001493/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001494static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001495 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001496 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001497 static int restart_successful = 0;
1498
1499 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001500 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001501 SLOGE("Encrypted filesystem not validated, aborting");
1502 return -1;
1503 }
1504
1505 if (restart_successful) {
1506 SLOGE("System already restarted with encrypted disk, aborting");
1507 return -1;
1508 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001509
Paul Lawrencef4faa572014-01-29 13:31:03 -08001510 if (restart_main) {
1511 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001512 * start all services in one of these classes: core, early_hal, hal,
1513 * main and late_start. To get to the minimal UI for PIN entry, we
1514 * need to start core, early_hal, hal and main. When we want to
1515 * shutdown the framework again, we need to stop most of the services in
1516 * these classes, but only those services that were started after
1517 * /data was mounted. This excludes critical services like vold and
1518 * ueventd, which need to keep running. We could possible stop
1519 * even fewer services, but because we want services to pick up APEX
1520 * libraries from the real /data, restarting is better, as it makes
1521 * these devices consistent with FBE devices and lets them use the
1522 * most recent code.
1523 *
1524 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001525 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001526 * We then restart the class core, hal, main, and also the class
1527 * late_start.
1528 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001529 * At the moment, I've only put a few things in late_start that I know
1530 * are not needed to bring up the framework, and that also cause problems
1531 * with unmounting the tmpfs /data, but I hope to add add more services
1532 * to the late_start class as we optimize this to decrease the delay
1533 * till the user is asked for the password to the filesystem.
1534 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001535
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001536 /* The init files are setup to stop the right set of services when
1537 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001538 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001539 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001540 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001541
Paul Lawrencef4faa572014-01-29 13:31:03 -08001542 /* Ugh, shutting down the framework is not synchronous, so until it
1543 * can be fixed, this horrible hack will wait a moment for it all to
1544 * shut down before proceeding. Without it, some devices cannot
1545 * restart the graphics services.
1546 */
1547 sleep(2);
1548 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001549
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001550 /* Now that the framework is shutdown, we should be able to umount()
1551 * the tmpfs filesystem, and mount the real one.
1552 */
1553
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001554 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1555 if (strlen(crypto_blkdev) == 0) {
1556 SLOGE("fs_crypto_blkdev not set\n");
1557 return -1;
1558 }
1559
Paul Crowley14c8c072018-09-18 13:30:21 -07001560 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001561 /* If ro.crypto.readonly is set to 1, mount the decrypted
1562 * filesystem readonly. This is used when /data is mounted by
1563 * recovery mode.
1564 */
1565 char ro_prop[PROPERTY_VALUE_MAX];
1566 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001567 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001568 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1569 if (entry != nullptr) {
1570 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001571 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001572 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001573
Ken Sumralle5032c42012-04-01 23:58:44 -07001574 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001575 int retries = RETRY_MOUNT_ATTEMPTS;
1576 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001577
1578 /*
1579 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1580 * partitions in the fsck domain.
1581 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001582 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001583 SLOGE("Failed to setexeccon");
1584 return -1;
1585 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001586 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001587 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001588 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001589 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1590 /* TODO: invoke something similar to
1591 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1592 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001593 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001594 if (--retries) {
1595 sleep(RETRY_MOUNT_DELAY_SECONDS);
1596 } else {
1597 /* Let's hope that a reboot clears away whatever is keeping
1598 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001599 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001600 }
1601 } else {
1602 SLOGE("Failed to mount decrypted data");
1603 cryptfs_set_corrupt();
1604 cryptfs_trigger_restart_min_framework();
1605 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001606 if (setexeccon(NULL)) {
1607 SLOGE("Failed to setexeccon");
1608 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001609 return -1;
1610 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001611 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001612 if (setexeccon(NULL)) {
1613 SLOGE("Failed to setexeccon");
1614 return -1;
1615 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616
Ken Sumralle5032c42012-04-01 23:58:44 -07001617 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001618 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001619 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001620
1621 /* startup service classes main and late_start */
1622 property_set("vold.decrypt", "trigger_restart_framework");
1623 SLOGD("Just triggered restart_framework\n");
1624
1625 /* Give it a few moments to get started */
1626 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627 }
1628
Ken Sumrall0cc16632011-01-18 20:32:26 -08001629 if (rc == 0) {
1630 restart_successful = 1;
1631 }
1632
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001633 return rc;
1634}
1635
Paul Crowley14c8c072018-09-18 13:30:21 -07001636int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001637 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001638 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001639 SLOGE("cryptfs_restart not valid for file encryption:");
1640 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001641 }
1642
Paul Lawrencef4faa572014-01-29 13:31:03 -08001643 /* Call internal implementation forcing a restart of main service group */
1644 return cryptfs_restart_internal(1);
1645}
1646
Paul Crowley14c8c072018-09-18 13:30:21 -07001647static int do_crypto_complete(const char* mount_point) {
1648 struct crypt_mnt_ftr crypt_ftr;
1649 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001650
Paul Crowley14c8c072018-09-18 13:30:21 -07001651 property_get("ro.crypto.state", encrypted_state, "");
1652 if (strcmp(encrypted_state, "encrypted")) {
1653 SLOGE("not running with encryption, aborting");
1654 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001655 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001656
Paul Crowley14c8c072018-09-18 13:30:21 -07001657 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001658 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001659 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1660 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001661
Paul Crowley14c8c072018-09-18 13:30:21 -07001662 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001663 std::string key_loc;
1664 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001665
Paul Crowley14c8c072018-09-18 13:30:21 -07001666 /*
1667 * Only report this error if key_loc is a file and it exists.
1668 * If the device was never encrypted, and /data is not mountable for
1669 * some reason, returning 1 should prevent the UI from presenting the
1670 * a "enter password" screen, or worse, a "press button to wipe the
1671 * device" screen.
1672 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001673 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001674 SLOGE("master key file does not exist, aborting");
1675 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1676 } else {
1677 SLOGE("Error getting crypt footer and key\n");
1678 return CRYPTO_COMPLETE_BAD_METADATA;
1679 }
1680 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001681
Paul Crowley14c8c072018-09-18 13:30:21 -07001682 // Test for possible error flags
1683 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1684 SLOGE("Encryption process is partway completed\n");
1685 return CRYPTO_COMPLETE_PARTIAL;
1686 }
1687
1688 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1689 SLOGE("Encryption process was interrupted but cannot continue\n");
1690 return CRYPTO_COMPLETE_INCONSISTENT;
1691 }
1692
1693 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1694 SLOGE("Encryption is successful but data is corrupt\n");
1695 return CRYPTO_COMPLETE_CORRUPT;
1696 }
1697
1698 /* We passed the test! We shall diminish, and return to the west */
1699 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001700}
1701
Paul Crowley14c8c072018-09-18 13:30:21 -07001702static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1703 const char* mount_point, const char* label) {
1704 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001705 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001706 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001707 char tmp_mount_point[64];
1708 unsigned int orig_failed_decrypt_count;
1709 int rc;
1710 int use_keymaster = 0;
1711 int upgrade = 0;
1712 unsigned char* intermediate_key = 0;
1713 size_t intermediate_key_size = 0;
1714 int N = 1 << crypt_ftr->N_factor;
1715 int r = 1 << crypt_ftr->r_factor;
1716 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717
Paul Crowley14c8c072018-09-18 13:30:21 -07001718 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1719 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001720
Paul Crowley14c8c072018-09-18 13:30:21 -07001721 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1722 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1723 &intermediate_key_size)) {
1724 SLOGE("Failed to decrypt master key\n");
1725 rc = -1;
1726 goto errout;
1727 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001728 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001729
Tom Cherry4c5bde22019-01-29 14:34:01 -08001730 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001731
Paul Crowley14c8c072018-09-18 13:30:21 -07001732 // Create crypto block device - all (non fatal) code paths
1733 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001734 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001735 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001736 SLOGE("Error creating decrypted block device\n");
1737 rc = -1;
1738 goto errout;
1739 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001740
Paul Crowley14c8c072018-09-18 13:30:21 -07001741 /* Work out if the problem is the password or the data */
1742 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001743
Paul Crowley14c8c072018-09-18 13:30:21 -07001744 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1745 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1746 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001747
Paul Crowley14c8c072018-09-18 13:30:21 -07001748 // Does the key match the crypto footer?
1749 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1750 sizeof(scrypted_intermediate_key)) == 0) {
1751 SLOGI("Password matches");
1752 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001753 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001754 /* Try mounting the file system anyway, just in case the problem's with
1755 * the footer, not the key. */
1756 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1757 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001758 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1759 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001760 SLOGE("Error temp mounting decrypted block device\n");
1761 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001762
Paul Crowley14c8c072018-09-18 13:30:21 -07001763 rc = ++crypt_ftr->failed_decrypt_count;
1764 put_crypt_ftr_and_key(crypt_ftr);
1765 } else {
1766 /* Success! */
1767 SLOGI("Password did not match but decrypted drive mounted - continue");
1768 umount(tmp_mount_point);
1769 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001770 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001771 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001772
Paul Crowley14c8c072018-09-18 13:30:21 -07001773 if (rc == 0) {
1774 crypt_ftr->failed_decrypt_count = 0;
1775 if (orig_failed_decrypt_count != 0) {
1776 put_crypt_ftr_and_key(crypt_ftr);
1777 }
1778
1779 /* Save the name of the crypto block device
1780 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001781 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001782
1783 /* Also save a the master key so we can reencrypted the key
1784 * the key when we want to change the password on it. */
1785 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1786 saved_mount_point = strdup(mount_point);
1787 master_key_saved = 1;
1788 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1789 rc = 0;
1790
1791 // Upgrade if we're not using the latest KDF.
1792 use_keymaster = keymaster_check_compatibility();
1793 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1794 // Don't allow downgrade
1795 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1796 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1797 upgrade = 1;
1798 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1799 crypt_ftr->kdf_type = KDF_SCRYPT;
1800 upgrade = 1;
1801 }
1802
1803 if (upgrade) {
1804 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1805 crypt_ftr->master_key, crypt_ftr);
1806 if (!rc) {
1807 rc = put_crypt_ftr_and_key(crypt_ftr);
1808 }
1809 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1810
1811 // Do not fail even if upgrade failed - machine is bootable
1812 // Note that if this code is ever hit, there is a *serious* problem
1813 // since KDFs should never fail. You *must* fix the kdf before
1814 // proceeding!
1815 if (rc) {
1816 SLOGW(
1817 "Upgrade failed with error %d,"
1818 " but continuing with previous state",
1819 rc);
1820 rc = 0;
1821 }
1822 }
1823 }
1824
1825errout:
1826 if (intermediate_key) {
1827 memset(intermediate_key, 0, intermediate_key_size);
1828 free(intermediate_key);
1829 }
1830 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001831}
1832
Ken Sumrall29d8da82011-05-18 17:20:07 -07001833/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001834 * Called by vold when it's asked to mount an encrypted external
1835 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001836 * as any metadata is been stored in a separate, small partition. We
1837 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001838 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001839int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001840 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001841 auto crypto_type = get_crypto_type();
1842 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001843 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001844 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001845 return -1;
1846 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001847 uint64_t nr_sec = 0;
1848 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001849 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001850 return -1;
1851 }
1852
Jeff Sharkey9c484982015-03-31 10:35:33 -07001853 struct crypt_mnt_ftr ext_crypt_ftr;
1854 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1855 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001856 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1857 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001858 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001859 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001860 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001861 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1862 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001863
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001864 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1865 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001866}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001867
Paul Crowley14c8c072018-09-18 13:30:21 -07001868int cryptfs_crypto_complete(void) {
1869 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001870}
1871
Paul Crowley14c8c072018-09-18 13:30:21 -07001872int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001873 char encrypted_state[PROPERTY_VALUE_MAX];
1874 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001875 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1876 SLOGE(
1877 "encrypted fs already validated or not running with encryption,"
1878 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001879 return -1;
1880 }
1881
1882 if (get_crypt_ftr_and_key(crypt_ftr)) {
1883 SLOGE("Error getting crypt footer and key");
1884 return -1;
1885 }
1886
1887 return 0;
1888}
1889
Paul Crowley14c8c072018-09-18 13:30:21 -07001890int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001891 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001892 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001893 SLOGE("cryptfs_check_passwd not valid for file encryption");
1894 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001895 }
1896
Paul Lawrencef4faa572014-01-29 13:31:03 -08001897 struct crypt_mnt_ftr crypt_ftr;
1898 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001899
Paul Lawrencef4faa572014-01-29 13:31:03 -08001900 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001901 if (rc) {
1902 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001903 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001904 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001905
Paul Crowley14c8c072018-09-18 13:30:21 -07001906 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001907 if (rc) {
1908 SLOGE("Password did not match");
1909 return rc;
1910 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001911
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001912 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1913 // Here we have a default actual password but a real password
1914 // we must test against the scrypted value
1915 // First, we must delete the crypto block device that
1916 // test_mount_encrypted_fs leaves behind as a side effect
1917 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001918 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1919 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001920 if (rc) {
1921 SLOGE("Default password did not match on reboot encryption");
1922 return rc;
1923 }
1924
1925 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1926 put_crypt_ftr_and_key(&crypt_ftr);
1927 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1928 if (rc) {
1929 SLOGE("Could not change password on reboot encryption");
1930 return rc;
1931 }
1932 }
1933
1934 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001935 cryptfs_clear_password();
1936 password = strdup(passwd);
1937 struct timespec now;
1938 clock_gettime(CLOCK_BOOTTIME, &now);
1939 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001940 }
1941
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001942 return rc;
1943}
1944
Paul Crowley14c8c072018-09-18 13:30:21 -07001945int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001946 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001947 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001948 char encrypted_state[PROPERTY_VALUE_MAX];
1949 int rc;
1950
1951 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001952 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001953 SLOGE("device not encrypted, aborting");
1954 return -2;
1955 }
1956
1957 if (!master_key_saved) {
1958 SLOGE("encrypted fs not yet mounted, aborting");
1959 return -1;
1960 }
1961
1962 if (!saved_mount_point) {
1963 SLOGE("encrypted fs failed to save mount point, aborting");
1964 return -1;
1965 }
1966
Ken Sumrall160b4d62013-04-22 12:15:39 -07001967 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001968 SLOGE("Error getting crypt footer and key\n");
1969 return -1;
1970 }
1971
1972 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1973 /* If the device has no password, then just say the password is valid */
1974 rc = 0;
1975 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001976 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001977 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1978 /* They match, the password is correct */
1979 rc = 0;
1980 } else {
1981 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1982 sleep(1);
1983 rc = 1;
1984 }
1985 }
1986
1987 return rc;
1988}
1989
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001990/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08001991 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001992 * Presumably, at a minimum, the caller will update the
1993 * filesystem size and crypto_type_name after calling this function.
1994 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001995static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001996 off64_t off;
1997
1998 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001999 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002000 ftr->major_version = CURRENT_MAJOR_VERSION;
2001 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002002 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002003 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002004
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002005 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002006 case 1:
2007 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2008 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002009
Paul Crowley14c8c072018-09-18 13:30:21 -07002010 case 0:
2011 ftr->kdf_type = KDF_SCRYPT;
2012 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002013
Paul Crowley14c8c072018-09-18 13:30:21 -07002014 default:
2015 SLOGE("keymaster_check_compatibility failed");
2016 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002017 }
2018
Kenny Rootc4c70f12013-06-14 12:11:38 -07002019 get_device_scrypt_params(ftr);
2020
Ken Sumrall160b4d62013-04-22 12:15:39 -07002021 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2022 if (get_crypt_ftr_info(NULL, &off) == 0) {
2023 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002024 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002025 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002026
2027 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002028}
2029
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002030#define FRAMEWORK_BOOT_WAIT 60
2031
Paul Crowley14c8c072018-09-18 13:30:21 -07002032static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2033 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002034 if (fd == -1) {
2035 SLOGE("Error opening file %s", filename);
2036 return -1;
2037 }
2038
2039 char block[CRYPT_INPLACE_BUFSIZE];
2040 memset(block, 0, sizeof(block));
2041 if (unix_read(fd, block, sizeof(block)) < 0) {
2042 SLOGE("Error reading file %s", filename);
2043 close(fd);
2044 return -1;
2045 }
2046
2047 close(fd);
2048
2049 SHA256_CTX c;
2050 SHA256_Init(&c);
2051 SHA256_Update(&c, block, sizeof(block));
2052 SHA256_Final(buf, &c);
2053
2054 return 0;
2055}
2056
Paul Crowley81796e92020-02-07 11:27:49 -08002057static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2058 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002059 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002060 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002061
Paul Lawrence87999172014-02-20 12:21:31 -08002062 /* The size of the userdata partition, and add in the vold volumes below */
2063 tot_encryption_size = crypt_ftr->fs_size;
2064
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002065 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002066 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002067
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002068 if (rc == ENABLE_INPLACE_ERR_DEV) {
2069 /* Hack for b/17898962 */
2070 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2071 cryptfs_reboot(RebootType::reboot);
2072 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002073
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002074 if (!rc) {
2075 crypt_ftr->encrypted_upto = cur_encryption_done;
2076 }
Paul Lawrence87999172014-02-20 12:21:31 -08002077
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002078 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2079 /* The inplace routine never actually sets the progress to 100% due
2080 * to the round down nature of integer division, so set it here */
2081 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002082 }
2083
2084 return rc;
2085}
2086
Paul Crowleyb64933a2017-10-31 08:25:55 -07002087static int vold_unmountAll(void) {
2088 VolumeManager* vm = VolumeManager::Instance();
2089 return vm->unmountAll();
2090}
2091
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002092int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002093 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002094 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002095 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002096 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002097 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002098 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002099 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002100 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002101 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002102 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002103 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002104 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002105 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002106 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002107
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002108 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002109 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2110 /* An encryption was underway and was interrupted */
2111 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2112 crypt_ftr.encrypted_upto = 0;
2113 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002114
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002115 /* At this point, we are in an inconsistent state. Until we successfully
2116 complete encryption, a reboot will leave us broken. So mark the
2117 encryption failed in case that happens.
2118 On successfully completing encryption, remove this flag */
2119 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002120
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002121 put_crypt_ftr_and_key(&crypt_ftr);
2122 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2123 if (!check_ftr_sha(&crypt_ftr)) {
2124 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2125 put_crypt_ftr_and_key(&crypt_ftr);
2126 goto error_unencrypted;
2127 }
2128
2129 /* Doing a reboot-encryption*/
2130 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2131 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2132 rebootEncryption = true;
2133 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002134 } else {
2135 // We don't want to accidentally reference invalid data.
2136 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002137 }
2138
2139 property_get("ro.crypto.state", encrypted_state, "");
2140 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2141 SLOGE("Device is already running encrypted, aborting");
2142 goto error_unencrypted;
2143 }
2144
Tom Cherry4c5bde22019-01-29 14:34:01 -08002145 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002146
Ken Sumrall3ed82362011-01-28 23:31:16 -08002147 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002148 uint64_t nr_sec;
2149 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002150 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002151 goto error_unencrypted;
2152 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002153
2154 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002155 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002156 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002157 fs_size_sec = get_fs_size(real_blkdev.c_str());
2158 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002159
Paul Lawrence87999172014-02-20 12:21:31 -08002160 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002161
2162 if (fs_size_sec > max_fs_size_sec) {
2163 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2164 goto error_unencrypted;
2165 }
2166 }
2167
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002168 /* Get a wakelock as this may take a while, and we don't want the
2169 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2170 * wants to keep the screen on, it can grab a full wakelock.
2171 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002172 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002173 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002174
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002176 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002177 */
2178 property_set("vold.decrypt", "trigger_shutdown_framework");
2179 SLOGD("Just asked init to shut down class main\n");
2180
Jeff Sharkey9c484982015-03-31 10:35:33 -07002181 /* Ask vold to unmount all devices that it manages */
2182 if (vold_unmountAll()) {
2183 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002184 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002185
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002186 /* no_ui means we are being called from init, not settings.
2187 Now we always reboot from settings, so !no_ui means reboot
2188 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002189 if (!no_ui) {
2190 /* Try fallback, which is to reboot and try there */
2191 onlyCreateHeader = true;
2192 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2193 if (breadcrumb == 0) {
2194 SLOGE("Failed to create breadcrumb file");
2195 goto error_shutting_down;
2196 }
2197 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002198 }
2199
2200 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002201 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002202 /* Now that /data is unmounted, we need to mount a tmpfs
2203 * /data, set a property saying we're doing inplace encryption,
2204 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002205 */
xzj7e38a3a2018-10-12 10:17:11 +08002206 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002207 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002208 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002210 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002211 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002212
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002213 /* restart the framework. */
2214 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002215 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002216
Ken Sumrall92736ef2012-10-17 20:57:14 -07002217 /* Ugh, shutting down the framework is not synchronous, so until it
2218 * can be fixed, this horrible hack will wait a moment for it all to
2219 * shut down before proceeding. Without it, some devices cannot
2220 * restart the graphics services.
2221 */
2222 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002223 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002224
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002225 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002226 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002227 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002228 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2229 goto error_shutting_down;
2230 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002231
Tom Cherry4c5bde22019-01-29 14:34:01 -08002232 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002233 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002234 } else {
2235 crypt_ftr.fs_size = nr_sec;
2236 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002237 /* At this point, we are in an inconsistent state. Until we successfully
2238 complete encryption, a reboot will leave us broken. So mark the
2239 encryption failed in case that happens.
2240 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002241 if (onlyCreateHeader) {
2242 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2243 } else {
2244 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2245 }
Paul Lawrence87999172014-02-20 12:21:31 -08002246 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002247 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002248 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002249
Paul Lawrence87999172014-02-20 12:21:31 -08002250 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002251 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2252 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002253 SLOGE("Cannot create encrypted master key\n");
2254 goto error_shutting_down;
2255 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002256
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002257 /* Replace scrypted intermediate key if we are preparing for a reboot */
2258 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002259 unsigned char fake_master_key[MAX_KEY_LEN];
2260 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002261 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002262 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2263 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002264 }
2265
Paul Lawrence87999172014-02-20 12:21:31 -08002266 /* Write the key to the end of the partition */
2267 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002268
Paul Lawrence87999172014-02-20 12:21:31 -08002269 /* If any persistent data has been remembered, save it.
2270 * If none, create a valid empty table and save that.
2271 */
2272 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002273 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2274 if (pdata) {
2275 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2276 persist_data = pdata;
2277 }
Paul Lawrence87999172014-02-20 12:21:31 -08002278 }
2279 if (persist_data) {
2280 save_persistent_data();
2281 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002282 }
2283
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002284 if (onlyCreateHeader) {
2285 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002286 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002287 }
2288
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002289 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002290 /* startup service classes main and late_start */
2291 property_set("vold.decrypt", "trigger_restart_min_framework");
2292 SLOGD("Just triggered restart_min_framework\n");
2293
2294 /* OK, the framework is restarted and will soon be showing a
2295 * progress bar. Time to setup an encrypted mapping, and
2296 * either write a new filesystem, or encrypt in place updating
2297 * the progress bar as we work.
2298 */
2299 }
2300
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002301 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002302 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002303 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002304
Paul Lawrence87999172014-02-20 12:21:31 -08002305 /* If we are continuing, check checksums match */
2306 rc = 0;
2307 if (previously_encrypted_upto) {
2308 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002309 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002310
Paul Crowley14c8c072018-09-18 13:30:21 -07002311 if (!rc &&
2312 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002313 SLOGE("Checksums do not match - trigger wipe");
2314 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002315 }
2316 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002317
Paul Lawrence87999172014-02-20 12:21:31 -08002318 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002319 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002320 previously_encrypted_upto);
2321 }
2322
2323 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002324 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002325 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002326 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002327 SLOGE("Error calculating checksum for continuing encryption");
2328 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002329 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002330 }
2331
2332 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002333 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002334
Paul Crowley14c8c072018-09-18 13:30:21 -07002335 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002336 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002337 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002338
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002339 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002340 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2341 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002342 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002343 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002344
Paul Lawrence6bfed202014-07-28 12:47:22 -07002345 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002346
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002347 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2348 char value[PROPERTY_VALUE_MAX];
2349 property_get("ro.crypto.state", value, "");
2350 if (!strcmp(value, "")) {
2351 /* default encryption - continue first boot sequence */
2352 property_set("ro.crypto.state", "encrypted");
2353 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002354 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002355 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2356 // Bring up cryptkeeper that will check the password and set it
2357 property_set("vold.decrypt", "trigger_shutdown_framework");
2358 sleep(2);
2359 property_set("vold.encrypt_progress", "");
2360 cryptfs_trigger_restart_min_framework();
2361 } else {
2362 cryptfs_check_passwd(DEFAULT_PASSWORD);
2363 cryptfs_restart_internal(1);
2364 }
2365 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002366 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002367 sleep(2); /* Give the UI a chance to show 100% progress */
2368 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002369 }
Paul Lawrence87999172014-02-20 12:21:31 -08002370 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002371 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002372 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002373 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002374 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002375 char value[PROPERTY_VALUE_MAX];
2376
Ken Sumrall319369a2012-06-27 16:30:18 -07002377 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002378 if (!strcmp(value, "1")) {
2379 /* wipe data if encryption failed */
2380 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002381 std::string err;
2382 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002383 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002384 if (!write_bootloader_message(options, &err)) {
2385 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002386 }
Josh Gaofec44372017-08-28 13:22:55 -07002387 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002388 } else {
2389 /* set property to trigger dialog */
2390 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002391 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002392 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002393 }
2394
Ken Sumrall3ed82362011-01-28 23:31:16 -08002395 /* hrm, the encrypt step claims success, but the reboot failed.
2396 * This should not happen.
2397 * Set the property and return. Hope the framework can deal with it.
2398 */
2399 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002400 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002401
2402error_unencrypted:
2403 property_set("vold.encrypt_progress", "error_not_encrypted");
2404 return -1;
2405
2406error_shutting_down:
2407 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2408 * but the framework is stopped and not restarted to show the error, so it's up to
2409 * vold to restart the system.
2410 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002411 SLOGE(
2412 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2413 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002414 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002415
2416 /* shouldn't get here */
2417 property_set("vold.encrypt_progress", "error_shutting_down");
2418 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002419}
2420
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002421int cryptfs_enable(int type, const char* passwd, int no_ui) {
2422 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002423}
2424
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002425int cryptfs_enable_default(int no_ui) {
2426 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002427}
2428
Paul Crowley14c8c072018-09-18 13:30:21 -07002429int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002430 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002431 SLOGE("cryptfs_changepw not valid for file encryption");
2432 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002433 }
2434
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002435 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002436 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002437
2438 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002439 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002440 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002441 return -1;
2442 }
2443
Paul Lawrencef4faa572014-01-29 13:31:03 -08002444 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2445 SLOGE("Invalid crypt_type %d", crypt_type);
2446 return -1;
2447 }
2448
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002449 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002450 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002451 SLOGE("Error getting crypt footer and key");
2452 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002453 }
2454
Paul Lawrencef4faa572014-01-29 13:31:03 -08002455 crypt_ftr.crypt_type = crypt_type;
2456
Paul Crowley14c8c072018-09-18 13:30:21 -07002457 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2458 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002459 if (rc) {
2460 SLOGE("Encrypt master key failed: %d", rc);
2461 return -1;
2462 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002463 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002464 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002465
2466 return 0;
2467}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002468
Rubin Xu85c01f92014-10-13 12:49:54 +01002469static unsigned int persist_get_max_entries(int encrypted) {
2470 struct crypt_mnt_ftr crypt_ftr;
2471 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002472
2473 /* If encrypted, use the values from the crypt_ftr, otherwise
2474 * use the values for the current spec.
2475 */
2476 if (encrypted) {
2477 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002478 /* Something is wrong, assume no space for entries */
2479 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002480 }
2481 dsize = crypt_ftr.persist_data_size;
2482 } else {
2483 dsize = CRYPT_PERSIST_DATA_SIZE;
2484 }
2485
Rubin Xuf83cc612018-10-09 16:13:38 +01002486 if (dsize > sizeof(struct crypt_persist_data)) {
2487 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2488 } else {
2489 return 0;
2490 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002491}
2492
Paul Crowley14c8c072018-09-18 13:30:21 -07002493static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002494 unsigned int i;
2495
2496 if (persist_data == NULL) {
2497 return -1;
2498 }
2499 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2500 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2501 /* We found it! */
2502 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2503 return 0;
2504 }
2505 }
2506
2507 return -1;
2508}
2509
Paul Crowley14c8c072018-09-18 13:30:21 -07002510static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002511 unsigned int i;
2512 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002513 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002514
2515 if (persist_data == NULL) {
2516 return -1;
2517 }
2518
Rubin Xu85c01f92014-10-13 12:49:54 +01002519 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002520
2521 num = persist_data->persist_valid_entries;
2522
2523 for (i = 0; i < num; i++) {
2524 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2525 /* We found an existing entry, update it! */
2526 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2527 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2528 return 0;
2529 }
2530 }
2531
2532 /* We didn't find it, add it to the end, if there is room */
2533 if (persist_data->persist_valid_entries < max_persistent_entries) {
2534 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2535 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2536 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2537 persist_data->persist_valid_entries++;
2538 return 0;
2539 }
2540
2541 return -1;
2542}
2543
Rubin Xu85c01f92014-10-13 12:49:54 +01002544/**
2545 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2546 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2547 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002548int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002549 std::string key_ = key;
2550 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002551
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002552 std::string parsed_field;
2553 unsigned parsed_index;
2554
2555 std::string::size_type split = key_.find_last_of('_');
2556 if (split == std::string::npos) {
2557 parsed_field = key_;
2558 parsed_index = 0;
2559 } else {
2560 parsed_field = key_.substr(0, split);
2561 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002562 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002563
2564 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002565}
2566
2567/*
2568 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2569 * remaining entries starting from index will be deleted.
2570 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2571 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2572 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2573 *
2574 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002575static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002576 unsigned int i;
2577 unsigned int j;
2578 unsigned int num;
2579
2580 if (persist_data == NULL) {
2581 return PERSIST_DEL_KEY_ERROR_OTHER;
2582 }
2583
2584 num = persist_data->persist_valid_entries;
2585
Paul Crowley14c8c072018-09-18 13:30:21 -07002586 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002587 // Filter out to-be-deleted entries in place.
2588 for (i = 0; i < num; i++) {
2589 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2590 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2591 j++;
2592 }
2593 }
2594
2595 if (j < num) {
2596 persist_data->persist_valid_entries = j;
2597 // Zeroise the remaining entries
2598 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2599 return PERSIST_DEL_KEY_OK;
2600 } else {
2601 // Did not find an entry matching the given fieldname
2602 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2603 }
2604}
2605
Paul Crowley14c8c072018-09-18 13:30:21 -07002606static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002607 unsigned int i;
2608 unsigned int count;
2609
2610 if (persist_data == NULL) {
2611 return -1;
2612 }
2613
2614 count = 0;
2615 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2616 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2617 count++;
2618 }
2619 }
2620
2621 return count;
2622}
2623
Ken Sumrall160b4d62013-04-22 12:15:39 -07002624/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002625int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002626 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002627 SLOGE("Cannot get field when file encrypted");
2628 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002629 }
2630
Ken Sumrall160b4d62013-04-22 12:15:39 -07002631 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002632 /* CRYPTO_GETFIELD_OK is success,
2633 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2634 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2635 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002636 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002637 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2638 int i;
2639 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002640
2641 if (persist_data == NULL) {
2642 load_persistent_data();
2643 if (persist_data == NULL) {
2644 SLOGE("Getfield error, cannot load persistent data");
2645 goto out;
2646 }
2647 }
2648
Rubin Xu85c01f92014-10-13 12:49:54 +01002649 // Read value from persistent entries. If the original value is split into multiple entries,
2650 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002651 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002652 // 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 -07002653 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002654 // value too small
2655 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2656 goto out;
2657 }
2658 rc = CRYPTO_GETFIELD_OK;
2659
2660 for (i = 1; /* break explicitly */; i++) {
2661 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002662 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002663 // If the fieldname is very long, we stop as soon as it begins to overflow the
2664 // maximum field length. At this point we have in fact fully read out the original
2665 // value because cryptfs_setfield would not allow fields with longer names to be
2666 // written in the first place.
2667 break;
2668 }
2669 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002670 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2671 // value too small.
2672 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2673 goto out;
2674 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002675 } else {
2676 // Exhaust all entries.
2677 break;
2678 }
2679 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002680 } else {
2681 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002682 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002683 }
2684
2685out:
2686 return rc;
2687}
2688
2689/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002690int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002691 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002692 SLOGE("Cannot set field when file encrypted");
2693 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002694 }
2695
Ken Sumrall160b4d62013-04-22 12:15:39 -07002696 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002697 /* 0 is success, negative values are error */
2698 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002699 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002700 unsigned int field_id;
2701 char temp_field[PROPERTY_KEY_MAX];
2702 unsigned int num_entries;
2703 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002704
2705 if (persist_data == NULL) {
2706 load_persistent_data();
2707 if (persist_data == NULL) {
2708 SLOGE("Setfield error, cannot load persistent data");
2709 goto out;
2710 }
2711 }
2712
2713 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002714 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002715 encrypted = 1;
2716 }
2717
Rubin Xu85c01f92014-10-13 12:49:54 +01002718 // Compute the number of entries required to store value, each entry can store up to
2719 // (PROPERTY_VALUE_MAX - 1) chars
2720 if (strlen(value) == 0) {
2721 // Empty value also needs one entry to store.
2722 num_entries = 1;
2723 } else {
2724 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2725 }
2726
2727 max_keylen = strlen(fieldname);
2728 if (num_entries > 1) {
2729 // Need an extra "_%d" suffix.
2730 max_keylen += 1 + log10(num_entries);
2731 }
2732 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2733 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002734 goto out;
2735 }
2736
Rubin Xu85c01f92014-10-13 12:49:54 +01002737 // Make sure we have enough space to write the new value
2738 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2739 persist_get_max_entries(encrypted)) {
2740 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2741 goto out;
2742 }
2743
2744 // Now that we know persist_data has enough space for value, let's delete the old field first
2745 // to make up space.
2746 persist_del_keys(fieldname, 0);
2747
2748 if (persist_set_key(fieldname, value, encrypted)) {
2749 // fail to set key, should not happen as we have already checked the available space
2750 SLOGE("persist_set_key() error during setfield()");
2751 goto out;
2752 }
2753
2754 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002755 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002756
2757 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2758 // fail to set key, should not happen as we have already checked the available space.
2759 SLOGE("persist_set_key() error during setfield()");
2760 goto out;
2761 }
2762 }
2763
Ken Sumrall160b4d62013-04-22 12:15:39 -07002764 /* If we are running encrypted, save the persistent data now */
2765 if (encrypted) {
2766 if (save_persistent_data()) {
2767 SLOGE("Setfield error, cannot save persistent data");
2768 goto out;
2769 }
2770 }
2771
Rubin Xu85c01f92014-10-13 12:49:54 +01002772 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002773
2774out:
2775 return rc;
2776}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002777
2778/* Checks userdata. Attempt to mount the volume if default-
2779 * encrypted.
2780 * On success trigger next init phase and return 0.
2781 * Currently do not handle failure - see TODO below.
2782 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002783int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002784 int crypt_type = cryptfs_get_password_type();
2785 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2786 SLOGE("Bad crypt type - error");
2787 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002788 SLOGD(
2789 "Password is not default - "
2790 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002791 property_set("vold.decrypt", "trigger_restart_min_framework");
2792 return 0;
2793 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2794 SLOGD("Password is default - restarting filesystem");
2795 cryptfs_restart_internal(0);
2796 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002797 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002798 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002799 }
2800
Paul Lawrence6bfed202014-07-28 12:47:22 -07002801 /** Corrupt. Allow us to boot into framework, which will detect bad
2802 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002803 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002804 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002805 return 0;
2806}
2807
2808/* Returns type of the password, default, pattern, pin or password.
2809 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002810int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002811 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002812 SLOGE("cryptfs_get_password_type not valid for file encryption");
2813 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002814 }
2815
Paul Lawrencef4faa572014-01-29 13:31:03 -08002816 struct crypt_mnt_ftr crypt_ftr;
2817
2818 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2819 SLOGE("Error getting crypt footer and key\n");
2820 return -1;
2821 }
2822
Paul Lawrence6bfed202014-07-28 12:47:22 -07002823 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2824 return -1;
2825 }
2826
Paul Lawrencef4faa572014-01-29 13:31:03 -08002827 return crypt_ftr.crypt_type;
2828}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002829
Paul Crowley14c8c072018-09-18 13:30:21 -07002830const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002831 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002832 SLOGE("cryptfs_get_password not valid for file encryption");
2833 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002834 }
2835
Paul Lawrence399317e2014-03-10 13:20:50 -07002836 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002837 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002838 if (now.tv_sec < password_expiry_time) {
2839 return password;
2840 } else {
2841 cryptfs_clear_password();
2842 return 0;
2843 }
2844}
2845
Paul Crowley14c8c072018-09-18 13:30:21 -07002846void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002847 if (password) {
2848 size_t len = strlen(password);
2849 memset(password, 0, len);
2850 free(password);
2851 password = 0;
2852 password_expiry_time = 0;
2853 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002854}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002855
Paul Crowley14c8c072018-09-18 13:30:21 -07002856int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002857 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2858 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002859}