blob: 36bd43b3dea310c28665dd485de1a49823fefa83 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Logan Chiend557d762018-05-02 11:36:45 +080017#define LOG_TAG "Cryptfs"
18
19#include "cryptfs.h"
20
Daniel Rosenberg65f99c92018-08-28 01:58:49 -070021#include "Checkpoint.h"
Paul Crowley220567c2020-02-07 12:45:20 -080022#include "CryptoType.h"
Logan Chiend557d762018-05-02 11:36:45 +080023#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070024#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080025#include "Keymaster.h"
26#include "Process.h"
27#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070028#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080029#include "VoldUtil.h"
30#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080031
Eric Biggersed45ec32019-01-25 10:47:55 -080032#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080033#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080034#include <android-base/stringprintf.h>
Hyangseok Chae3cf32332020-02-27 18:21:50 +090035#include <android-base/strings.h>
Logan Chiend557d762018-05-02 11:36:45 +080036#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080037#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070039#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080040#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070042#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070043#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080044#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080045#include <logwrap/logwrap.h>
46#include <openssl/evp.h>
47#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080048#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070049#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080050
51#include <ctype.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <inttypes.h>
55#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080056#include <linux/kdev_t.h>
57#include <math.h>
Hyangseok Chae3cf32332020-02-27 18:21:50 +090058#include <mntent.h>
Logan Chiend557d762018-05-02 11:36:45 +080059#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080062#include <sys/mount.h>
63#include <sys/param.h>
64#include <sys/stat.h>
65#include <sys/types.h>
66#include <sys/wait.h>
67#include <time.h>
68#include <unistd.h>
69
Martijn Coenen26ad7b32020-02-13 16:20:52 +010070#include <chrono>
71#include <thread>
72
Wei Wang4375f1b2017-02-24 17:43:01 -080073extern "C" {
74#include <crypto_scrypt.h>
75}
Mark Salyzyn3e971272014-01-21 13:27:04 -080076
Eric Biggersed45ec32019-01-25 10:47:55 -080077using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080078using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080079using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley220567c2020-02-07 12:45:20 -080080using android::vold::CryptoType;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080081using android::vold::KeyBuffer;
Paul Crowleyb3d018a2020-02-12 11:04:05 -080082using android::vold::KeyGeneration;
David Andersonb9224732019-05-13 13:02:54 -070083using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070084using namespace std::chrono_literals;
85
Paul Crowley73be12d2020-02-03 12:22:03 -080086/* The current cryptfs version */
87#define CURRENT_MAJOR_VERSION 1
88#define CURRENT_MINOR_VERSION 3
89
90#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
91#define CRYPT_PERSIST_DATA_SIZE 0x1000
92
93#define MAX_CRYPTO_TYPE_NAME_LEN 64
94
95#define MAX_KEY_LEN 48
96#define SALT_LEN 16
97#define SCRYPT_LEN 32
98
99/* definitions of flags in the structure below */
100#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
Eric Biggersc01995e2020-11-03 14:11:00 -0800101#define CRYPT_ENCRYPTION_IN_PROGRESS 0x2 /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800102#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) */
Eric Biggersc01995e2020-11-03 14:11:00 -0800196 __le64 encrypted_upto; /* no longer used */
197 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800198
199 /* key_master key, used to sign the derived key which is then used to generate
200 * the intermediate key
201 * This key should be used for no other purposes! We use this key to sign unpadded
202 * data, which is acceptable but only if the key is not reused elsewhere. */
203 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
204 __le32 keymaster_blob_size;
205
206 /* Store scrypt of salted intermediate key. When decryption fails, we can
207 check if this matches, and if it does, we know that the problem is with the
208 drive, and there is no point in asking the user for more passwords.
209
210 Note that if any part of this structure is corrupt, this will not match and
211 we will continue to believe the user entered the wrong password. In that
212 case the only solution is for the user to enter a password enough times to
213 force a wipe.
214
215 Note also that there is no need to worry about migration. If this data is
216 wrong, we simply won't recognise a right password, and will continue to
217 prompt. On the first password change, this value will be populated and
218 then we will be OK.
219 */
220 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
221
222 /* sha of this structure with this element set to zero
223 Used when encrypting on reboot to validate structure before doing something
224 fatal
225 */
226 unsigned char sha256[SHA256_DIGEST_LENGTH];
227};
228
229/* Persistant data that should be available before decryption.
230 * Things like airplane mode, locale and timezone are kept
231 * here and can be retrieved by the CryptKeeper UI to properly
232 * configure the phone before asking for the password
233 * This is only valid if the major and minor version above
234 * is set to 1.1 or higher.
235 *
236 * This is a 4K structure. There are 2 copies, and the code alternates
237 * writing one and then clearing the previous one. The reading
238 * code reads the first valid copy it finds, based on the magic number.
239 * The absolute offset to the first of the two copies is kept in rev 1.1
240 * and higher crypt_mnt_ftr structures.
241 */
242struct crypt_persist_entry {
243 char key[PROPERTY_KEY_MAX];
244 char val[PROPERTY_VALUE_MAX];
245};
246
247/* Should be exactly 4K in size */
248struct crypt_persist_data {
249 __le32 persist_magic;
250 __le32 persist_valid_entries;
251 __le32 persist_spare[30];
252 struct crypt_persist_entry persist_entry[0];
253};
254
255static int wait_and_unmount(const char* mountpoint, bool kill);
256
257typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
258 void* params);
259
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800260#define UNUSED __attribute__((unused))
261
Jason parks70a4b3f2011-01-28 10:10:47 -0600262#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800263
264constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
265constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700266constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800267
268// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700269static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600270
Paul Crowley14c8c072018-09-18 13:30:21 -0700271#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700272
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700273#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800274
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800275#define CRYPTO_BLOCK_DEVICE "userdata"
276
277#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
278
Ken Sumrall29d8da82011-05-18 17:20:07 -0700279#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700280#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700281
Ken Sumralle919efe2012-09-29 17:07:41 -0700282#define TABLE_LOAD_RETRIES 10
283
Shawn Willden47ba10d2014-09-03 17:07:06 -0600284#define RSA_KEY_SIZE 2048
285#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
286#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600287#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700288
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700289#define RETRY_MOUNT_ATTEMPTS 10
290#define RETRY_MOUNT_DELAY_SECONDS 1
291
Paul Crowley5afbc622017-11-27 09:42:17 -0800292#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
293
Paul Crowley73473332017-11-21 15:43:51 -0800294static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
295
Greg Kaiser59ad0182018-02-16 13:01:36 -0800296static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700297static char* saved_mount_point;
298static int master_key_saved = 0;
299static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800300
Paul Crowley220567c2020-02-07 12:45:20 -0800301constexpr CryptoType aes_128_cbc = CryptoType()
302 .set_config_name("AES-128-CBC")
303 .set_kernel_name("aes-cbc-essiv:sha256")
304 .set_keysize(16);
305
306constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
307
308static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
309 array_length(supported_crypto_types)),
310 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
311 "incompletely constructed.");
312
313static const CryptoType& get_crypto_type() {
314 // We only want to parse this read-only property once. But we need to wait
315 // until the system is initialized before we can read it. So we use a static
316 // scoped within this function to get it only once.
317 static CryptoType crypto_type =
318 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
319 aes_128_cbc, "ro.crypto.fde_algorithm");
320 return crypto_type;
321}
322
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800323const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800324 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800325}
326
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700327/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700328static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000329 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700330}
331
332/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700333static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800334 if (ftr->keymaster_blob_size) {
335 SLOGI("Already have key");
336 return 0;
337 }
338
Paul Crowley14c8c072018-09-18 13:30:21 -0700339 int rc = keymaster_create_key_for_cryptfs_scrypt(
340 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
341 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000342 if (rc) {
343 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800344 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000345 ftr->keymaster_blob_size = 0;
346 }
347 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700348 return -1;
349 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000350 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700351}
352
Shawn Willdene17a9c42014-09-08 13:04:08 -0600353/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700354static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
355 const size_t object_size, unsigned char** signature,
356 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600357 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600358 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600359 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600360
Shawn Willdene17a9c42014-09-08 13:04:08 -0600361 // To sign a message with RSA, the message must satisfy two
362 // constraints:
363 //
364 // 1. The message, when interpreted as a big-endian numeric value, must
365 // be strictly less than the public modulus of the RSA key. Note
366 // that because the most significant bit of the public modulus is
367 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
368 // key), an n-bit message with most significant bit 0 always
369 // satisfies this requirement.
370 //
371 // 2. The message must have the same length in bits as the public
372 // modulus of the RSA key. This requirement isn't mathematically
373 // necessary, but is necessary to ensure consistency in
374 // implementations.
375 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600376 case KDF_SCRYPT_KEYMASTER:
377 // This ensures the most significant byte of the signed message
378 // is zero. We could have zero-padded to the left instead, but
379 // this approach is slightly more robust against changes in
380 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600381 // so) because we really should be using a proper deterministic
382 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800383 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600384 SLOGI("Signing safely-padded object");
385 break;
386 default:
387 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000388 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600389 }
Paul Crowley73473332017-11-21 15:43:51 -0800390 for (;;) {
391 auto result = keymaster_sign_object_for_cryptfs_scrypt(
392 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
393 to_sign_size, signature, signature_size);
394 switch (result) {
395 case KeymasterSignResult::ok:
396 return 0;
397 case KeymasterSignResult::upgrade:
398 break;
399 default:
400 return -1;
401 }
402 SLOGD("Upgrading key");
403 if (keymaster_upgrade_key_for_cryptfs_scrypt(
404 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
405 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
406 &ftr->keymaster_blob_size) != 0) {
407 SLOGE("Failed to upgrade key");
408 return -1;
409 }
410 if (put_crypt_ftr_and_key(ftr) != 0) {
411 SLOGE("Failed to write upgraded key to disk");
412 }
413 SLOGD("Key upgraded successfully");
414 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600415}
416
Paul Lawrence399317e2014-03-10 13:20:50 -0700417/* Store password when userdata is successfully decrypted and mounted.
418 * Cleared by cryptfs_clear_password
419 *
420 * To avoid a double prompt at boot, we need to store the CryptKeeper
421 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
422 * Since the entire framework is torn down and rebuilt after encryption,
423 * we have to use a daemon or similar to store the password. Since vold
424 * is secured against IPC except from system processes, it seems a reasonable
425 * place to store this.
426 *
427 * password should be cleared once it has been used.
428 *
429 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800430 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700431static char* password = 0;
432static int password_expiry_time = 0;
433static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800434
Paul Crowley14c8c072018-09-18 13:30:21 -0700435enum class RebootType { reboot, recovery, shutdown };
436static void cryptfs_reboot(RebootType rt) {
437 switch (rt) {
438 case RebootType::reboot:
439 property_set(ANDROID_RB_PROPERTY, "reboot");
440 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800441
Paul Crowley14c8c072018-09-18 13:30:21 -0700442 case RebootType::recovery:
443 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
444 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800445
Paul Crowley14c8c072018-09-18 13:30:21 -0700446 case RebootType::shutdown:
447 property_set(ANDROID_RB_PROPERTY, "shutdown");
448 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700449 }
Paul Lawrence87999172014-02-20 12:21:31 -0800450
Ken Sumralladfba362013-06-04 16:37:52 -0700451 sleep(20);
452
453 /* Shouldn't get here, reboot should happen before sleep times out */
454 return;
455}
456
Kenny Rootc4c70f12013-06-14 12:11:38 -0700457/**
458 * Gets the default device scrypt parameters for key derivation time tuning.
459 * The parameters should lead to about one second derivation time for the
460 * given device.
461 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700462static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700463 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000464 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700465
Paul Crowley63c18d32016-02-10 14:02:47 +0000466 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
467 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
468 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
469 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700470 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000471 ftr->N_factor = Nf;
472 ftr->r_factor = rf;
473 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700474}
475
Tom Cherry4c5bde22019-01-29 14:34:01 -0800476static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800477 int fd, block_size;
478 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200479 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800480
Paul Crowley14c8c072018-09-18 13:30:21 -0700481 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800482 SLOGE("Cannot open device to get filesystem size ");
483 return 0;
484 }
485
486 if (lseek64(fd, 1024, SEEK_SET) < 0) {
487 SLOGE("Cannot seek to superblock");
488 return 0;
489 }
490
491 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
492 SLOGE("Cannot read superblock");
493 return 0;
494 }
495
496 close(fd);
497
Daniel Rosenberge82df162014-08-15 22:19:23 +0000498 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
499 SLOGE("Not a valid ext4 superblock");
500 return 0;
501 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800502 block_size = 1024 << sb.s_log_block_size;
503 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200504 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800505
506 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200507 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800508}
509
Tom Cherry4c5bde22019-01-29 14:34:01 -0800510static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
511 for (const auto& entry : fstab_default) {
512 if (!entry.fs_mgr_flags.vold_managed &&
513 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
514 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
515 if (key_loc != nullptr) {
516 *key_loc = entry.key_loc;
517 }
518 if (real_blk_device != nullptr) {
519 *real_blk_device = entry.blk_device;
520 }
521 return;
522 }
523 }
524}
525
Paul Crowley14c8c072018-09-18 13:30:21 -0700526static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
527 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200528 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700529 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700530 char key_loc[PROPERTY_VALUE_MAX];
531 char real_blkdev[PROPERTY_VALUE_MAX];
532 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533
Paul Crowley14c8c072018-09-18 13:30:21 -0700534 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800535 std::string key_loc;
536 std::string real_blkdev;
537 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700538
Tom Cherry4c5bde22019-01-29 14:34:01 -0800539 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200540 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700541 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
542 * encryption info footer and key, and plenty of bytes to spare for future
543 * growth.
544 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800545 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200546 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700547 cached_data = 1;
548 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800549 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700550 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700551 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800552 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700553 cached_off = 0;
554 cached_data = 1;
555 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557
Paul Crowley14c8c072018-09-18 13:30:21 -0700558 if (cached_data) {
559 if (metadata_fname) {
560 *metadata_fname = cached_metadata_fname;
561 }
562 if (off) {
563 *off = cached_off;
564 }
565 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700566 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700567
Paul Crowley14c8c072018-09-18 13:30:21 -0700568 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700569}
570
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800571/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700572static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800573 SHA256_CTX c;
574 SHA256_Init(&c);
575 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
576 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
577 SHA256_Final(crypt_ftr->sha256, &c);
578}
579
Ken Sumralle8744072011-01-18 22:01:55 -0800580/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800581 * update the failed mount count but not change the key.
582 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700583static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
584 int fd;
585 unsigned int cnt;
586 /* starting_off is set to the SEEK_SET offset
587 * where the crypto structure starts
588 */
589 off64_t starting_off;
590 int rc = -1;
591 char* fname = NULL;
592 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800593
Paul Crowley14c8c072018-09-18 13:30:21 -0700594 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800595
Paul Crowley14c8c072018-09-18 13:30:21 -0700596 if (get_crypt_ftr_info(&fname, &starting_off)) {
597 SLOGE("Unable to get crypt_ftr_info\n");
598 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800599 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700600 if (fname[0] != '/') {
601 SLOGE("Unexpected value for crypto key location\n");
602 return -1;
603 }
604 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
605 SLOGE("Cannot open footer file %s for put\n", fname);
606 return -1;
607 }
Ken Sumralle8744072011-01-18 22:01:55 -0800608
Paul Crowley14c8c072018-09-18 13:30:21 -0700609 /* Seek to the start of the crypt footer */
610 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
611 SLOGE("Cannot seek to real block device footer\n");
612 goto errout;
613 }
614
615 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
616 SLOGE("Cannot write real block device footer\n");
617 goto errout;
618 }
619
620 fstat(fd, &statbuf);
621 /* If the keys are kept on a raw block device, do not try to truncate it. */
622 if (S_ISREG(statbuf.st_mode)) {
623 if (ftruncate(fd, 0x4000)) {
624 SLOGE("Cannot set footer file size\n");
625 goto errout;
626 }
627 }
628
629 /* Success! */
630 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800631
632errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700633 close(fd);
634 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800635}
636
Paul Crowley14c8c072018-09-18 13:30:21 -0700637static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800638 struct crypt_mnt_ftr copy;
639 memcpy(&copy, crypt_ftr, sizeof(copy));
640 set_ftr_sha(&copy);
641 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
642}
643
Paul Crowley14c8c072018-09-18 13:30:21 -0700644static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700645 return TEMP_FAILURE_RETRY(read(fd, buff, len));
646}
647
Paul Crowley14c8c072018-09-18 13:30:21 -0700648static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700649 return TEMP_FAILURE_RETRY(write(fd, buff, len));
650}
651
Paul Crowley14c8c072018-09-18 13:30:21 -0700652static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700653 memset(pdata, 0, len);
654 pdata->persist_magic = PERSIST_DATA_MAGIC;
655 pdata->persist_valid_entries = 0;
656}
657
658/* A routine to update the passed in crypt_ftr to the lastest version.
659 * fd is open read/write on the device that holds the crypto footer and persistent
660 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
661 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
662 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700663static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700664 int orig_major = crypt_ftr->major_version;
665 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700666
Kenny Root7434b312013-06-14 11:29:53 -0700667 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700668 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700669 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670
Kenny Rootc4c70f12013-06-14 12:11:38 -0700671 SLOGW("upgrading crypto footer to 1.1");
672
Paul Crowley14c8c072018-09-18 13:30:21 -0700673 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700674 if (pdata == NULL) {
675 SLOGE("Cannot allocate persisent data\n");
676 return;
677 }
678 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
679
680 /* Need to initialize the persistent data area */
681 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
682 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100683 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700684 return;
685 }
686 /* Write all zeros to the first copy, making it invalid */
687 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
688
689 /* Write a valid but empty structure to the second copy */
690 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
691 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
692
693 /* Update the footer */
694 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
695 crypt_ftr->persist_data_offset[0] = pdata_offset;
696 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
697 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100698 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700699 }
700
Paul Lawrencef4faa572014-01-29 13:31:03 -0800701 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700702 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800703 /* But keep the old kdf_type.
704 * It will get updated later to KDF_SCRYPT after the password has been verified.
705 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700706 crypt_ftr->kdf_type = KDF_PBKDF2;
707 get_device_scrypt_params(crypt_ftr);
708 crypt_ftr->minor_version = 2;
709 }
710
Paul Lawrencef4faa572014-01-29 13:31:03 -0800711 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
712 SLOGW("upgrading crypto footer to 1.3");
713 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
714 crypt_ftr->minor_version = 3;
715 }
716
Kenny Root7434b312013-06-14 11:29:53 -0700717 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
718 if (lseek64(fd, offset, SEEK_SET) == -1) {
719 SLOGE("Cannot seek to crypt footer\n");
720 return;
721 }
722 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700724}
725
Paul Crowley14c8c072018-09-18 13:30:21 -0700726static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
727 int fd;
728 unsigned int cnt;
729 off64_t starting_off;
730 int rc = -1;
731 char* fname = NULL;
732 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700733
Paul Crowley14c8c072018-09-18 13:30:21 -0700734 if (get_crypt_ftr_info(&fname, &starting_off)) {
735 SLOGE("Unable to get crypt_ftr_info\n");
736 return -1;
737 }
738 if (fname[0] != '/') {
739 SLOGE("Unexpected value for crypto key location\n");
740 return -1;
741 }
742 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
743 SLOGE("Cannot open footer file %s for get\n", fname);
744 return -1;
745 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800746
Paul Crowley14c8c072018-09-18 13:30:21 -0700747 /* Make sure it's 16 Kbytes in length */
748 fstat(fd, &statbuf);
749 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
750 SLOGE("footer file %s is not the expected size!\n", fname);
751 goto errout;
752 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700753
Paul Crowley14c8c072018-09-18 13:30:21 -0700754 /* Seek to the start of the crypt footer */
755 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
756 SLOGE("Cannot seek to real block device footer\n");
757 goto errout;
758 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759
Paul Crowley14c8c072018-09-18 13:30:21 -0700760 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
761 SLOGE("Cannot read real block device footer\n");
762 goto errout;
763 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800764
Paul Crowley14c8c072018-09-18 13:30:21 -0700765 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
766 SLOGE("Bad magic for real block device %s\n", fname);
767 goto errout;
768 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800769
Paul Crowley14c8c072018-09-18 13:30:21 -0700770 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
771 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
772 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
773 goto errout;
774 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800775
Paul Crowley14c8c072018-09-18 13:30:21 -0700776 // We risk buffer overflows with oversized keys, so we just reject them.
777 // 0-sized keys are problematic (essentially by-passing encryption), and
778 // AES-CBC key wrapping only works for multiples of 16 bytes.
779 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
780 (crypt_ftr->keysize > MAX_KEY_LEN)) {
781 SLOGE(
782 "Invalid keysize (%u) for block device %s; Must be non-zero, "
783 "divisible by 16, and <= %d\n",
784 crypt_ftr->keysize, fname, MAX_KEY_LEN);
785 goto errout;
786 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800787
Paul Crowley14c8c072018-09-18 13:30:21 -0700788 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
789 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
790 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
791 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800792
Paul Crowley14c8c072018-09-18 13:30:21 -0700793 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
794 * copy on disk before returning.
795 */
796 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
797 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
798 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800799
Paul Crowley14c8c072018-09-18 13:30:21 -0700800 /* Success! */
801 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800802
803errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700804 close(fd);
805 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800806}
807
Paul Crowley14c8c072018-09-18 13:30:21 -0700808static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700809 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
810 crypt_ftr->persist_data_offset[1]) {
811 SLOGE("Crypt_ftr persist data regions overlap");
812 return -1;
813 }
814
815 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
816 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
817 return -1;
818 }
819
820 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700821 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700822 CRYPT_FOOTER_OFFSET) {
823 SLOGE("Persistent data extends past crypto footer");
824 return -1;
825 }
826
827 return 0;
828}
829
Paul Crowley14c8c072018-09-18 13:30:21 -0700830static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700831 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700832 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700833 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700834 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835 int found = 0;
836 int fd;
837 int ret;
838 int i;
839
840 if (persist_data) {
841 /* Nothing to do, we've already loaded or initialized it */
842 return 0;
843 }
844
Ken Sumrall160b4d62013-04-22 12:15:39 -0700845 /* If not encrypted, just allocate an empty table and initialize it */
846 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700847 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800848 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700849 if (pdata) {
850 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
851 persist_data = pdata;
852 return 0;
853 }
854 return -1;
855 }
856
Paul Crowley14c8c072018-09-18 13:30:21 -0700857 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700858 return -1;
859 }
860
Paul Crowley14c8c072018-09-18 13:30:21 -0700861 if ((crypt_ftr.major_version < 1) ||
862 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700863 SLOGE("Crypt_ftr version doesn't support persistent data");
864 return -1;
865 }
866
867 if (get_crypt_ftr_info(&fname, NULL)) {
868 return -1;
869 }
870
871 ret = validate_persistent_data_storage(&crypt_ftr);
872 if (ret) {
873 return -1;
874 }
875
Paul Crowley14c8c072018-09-18 13:30:21 -0700876 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700877 if (fd < 0) {
878 SLOGE("Cannot open %s metadata file", fname);
879 return -1;
880 }
881
Wei Wang4375f1b2017-02-24 17:43:01 -0800882 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800883 if (pdata == NULL) {
884 SLOGE("Cannot allocate memory for persistent data");
885 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700886 }
887
888 for (i = 0; i < 2; i++) {
889 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
890 SLOGE("Cannot seek to read persistent data on %s", fname);
891 goto err2;
892 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700893 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700894 SLOGE("Error reading persistent data on iteration %d", i);
895 goto err2;
896 }
897 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
898 found = 1;
899 break;
900 }
901 }
902
903 if (!found) {
904 SLOGI("Could not find valid persistent data, creating");
905 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
906 }
907
908 /* Success */
909 persist_data = pdata;
910 close(fd);
911 return 0;
912
913err2:
914 free(pdata);
915
916err:
917 close(fd);
918 return -1;
919}
920
Paul Crowley14c8c072018-09-18 13:30:21 -0700921static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700922 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700923 struct crypt_persist_data* pdata;
924 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700925 off64_t write_offset;
926 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700927 int fd;
928 int ret;
929
930 if (persist_data == NULL) {
931 SLOGE("No persistent data to save");
932 return -1;
933 }
934
Paul Crowley14c8c072018-09-18 13:30:21 -0700935 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700936 return -1;
937 }
938
Paul Crowley14c8c072018-09-18 13:30:21 -0700939 if ((crypt_ftr.major_version < 1) ||
940 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700941 SLOGE("Crypt_ftr version doesn't support persistent data");
942 return -1;
943 }
944
945 ret = validate_persistent_data_storage(&crypt_ftr);
946 if (ret) {
947 return -1;
948 }
949
950 if (get_crypt_ftr_info(&fname, NULL)) {
951 return -1;
952 }
953
Paul Crowley14c8c072018-09-18 13:30:21 -0700954 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700955 if (fd < 0) {
956 SLOGE("Cannot open %s metadata file", fname);
957 return -1;
958 }
959
Wei Wang4375f1b2017-02-24 17:43:01 -0800960 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700961 if (pdata == NULL) {
962 SLOGE("Cannot allocate persistant data");
963 goto err;
964 }
965
966 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
967 SLOGE("Cannot seek to read persistent data on %s", fname);
968 goto err2;
969 }
970
971 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700972 SLOGE("Error reading persistent data before save");
973 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700974 }
975
976 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
977 /* The first copy is the curent valid copy, so write to
978 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700979 write_offset = crypt_ftr.persist_data_offset[1];
980 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700981 } else {
982 /* The second copy must be the valid copy, so write to
983 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700984 write_offset = crypt_ftr.persist_data_offset[0];
985 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700986 }
987
988 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100989 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700990 SLOGE("Cannot seek to write persistent data");
991 goto err2;
992 }
993 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700994 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100995 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700996 SLOGE("Cannot seek to erase previous persistent data");
997 goto err2;
998 }
999 fsync(fd);
1000 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001001 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001002 SLOGE("Cannot write to erase previous persistent data");
1003 goto err2;
1004 }
1005 fsync(fd);
1006 } else {
1007 SLOGE("Cannot write to save persistent data");
1008 goto err2;
1009 }
1010
1011 /* Success */
1012 free(pdata);
1013 close(fd);
1014 return 0;
1015
1016err2:
1017 free(pdata);
1018err:
1019 close(fd);
1020 return -1;
1021}
1022
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001023/* Convert a binary key of specified length into an ascii hex string equivalent,
1024 * without the leading 0x and with null termination
1025 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001026static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1027 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001028 unsigned int i, a;
1029 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001030
Paul Crowley14c8c072018-09-18 13:30:21 -07001031 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001032 /* For each byte, write out two ascii hex digits */
1033 nibble = (master_key[i] >> 4) & 0xf;
1034 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001035
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001036 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001037 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001038 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001039
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001040 /* Add the null termination */
1041 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001042}
1043
Eric Biggersed45ec32019-01-25 10:47:55 -08001044/*
1045 * If the ro.crypto.fde_sector_size system property is set, append the
1046 * parameters to make dm-crypt use the specified crypto sector size and round
1047 * the crypto device size down to a crypto sector boundary.
1048 */
David Andersonb9224732019-05-13 13:02:54 -07001049static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001050 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001051 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001052
Eric Biggersed45ec32019-01-25 10:47:55 -08001053 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1054 unsigned int sector_size;
1055
1056 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1057 (sector_size & (sector_size - 1)) != 0) {
1058 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1059 DM_CRYPT_SECTOR_SIZE, value);
1060 return -1;
1061 }
1062
David Andersonb9224732019-05-13 13:02:54 -07001063 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001064
1065 // With this option, IVs will match the sector numbering, instead
1066 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001067 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001068
1069 // Round the crypto device size down to a crypto sector boundary.
1070 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001071 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001072 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001073}
1074
Paul Crowley5afbc622017-11-27 09:42:17 -08001075static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001076 const char* real_blk_name, std::string* crypto_blk_name,
1077 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001078 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001079
David Andersonb9224732019-05-13 13:02:54 -07001080 // We need two ASCII characters to represent each byte, and need space for
1081 // the '\0' terminator.
1082 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1083 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001084
David Andersonb9224732019-05-13 13:02:54 -07001085 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1086 (const char*)crypt_ftr->crypto_type_name,
1087 master_key_ascii, 0, real_blk_name, 0);
1088 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001089
Paul Crowley5afbc622017-11-27 09:42:17 -08001090 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001091 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001092 }
David Andersonb9224732019-05-13 13:02:54 -07001093 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001094 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001095 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001096 }
David Andersonb9224732019-05-13 13:02:54 -07001097
1098 DmTable table;
1099 table.AddTarget(std::move(target));
1100
1101 int load_count = 1;
1102 while (load_count < TABLE_LOAD_RETRIES) {
1103 if (dm.CreateDevice(name, table)) {
1104 break;
1105 }
1106 load_count++;
1107 }
1108
1109 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001110 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001111 return -1;
1112 }
1113 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001114 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1115 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001116
Paul Crowley81796e92020-02-07 11:27:49 -08001117 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001118 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1119 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001120 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121
Paul Crowleycfe39722018-10-30 15:59:24 -07001122 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001123 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001124 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001125 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001126 }
David Andersonb9224732019-05-13 13:02:54 -07001127 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001128}
1129
David Andersonb9224732019-05-13 13:02:54 -07001130static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001131 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001132 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001133 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1134 // to delete the device fails with EBUSY; for now, work around this by retrying.
1135 int tries = 5;
1136 while (tries-- > 0) {
1137 ret = dm.DeleteDevice(name);
1138 if (ret || errno != EBUSY) {
1139 break;
1140 }
1141 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1142 strerror(errno));
1143 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1144 }
1145 if (!ret) {
1146 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001147 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001148 }
David Andersonb9224732019-05-13 13:02:54 -07001149 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001150}
1151
Paul Crowley14c8c072018-09-18 13:30:21 -07001152static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1153 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001154 SLOGI("Using pbkdf2 for cryptfs KDF");
1155
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001157 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1158 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001159}
1160
Paul Crowley14c8c072018-09-18 13:30:21 -07001161static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001162 SLOGI("Using scrypt for cryptfs KDF");
1163
Paul Crowley14c8c072018-09-18 13:30:21 -07001164 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001165
1166 int N = 1 << ftr->N_factor;
1167 int r = 1 << ftr->r_factor;
1168 int p = 1 << ftr->p_factor;
1169
1170 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001171 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001172 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001173
Paul Crowley14c8c072018-09-18 13:30:21 -07001174 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001175}
1176
Paul Crowley14c8c072018-09-18 13:30:21 -07001177static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1178 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001179 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1180
1181 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001182 size_t signature_size;
1183 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001184 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001185
1186 int N = 1 << ftr->N_factor;
1187 int r = 1 << ftr->r_factor;
1188 int p = 1 << ftr->p_factor;
1189
Paul Crowley14c8c072018-09-18 13:30:21 -07001190 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001191 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001192
1193 if (rc) {
1194 SLOGE("scrypt failed");
1195 return -1;
1196 }
1197
Paul Crowley14c8c072018-09-18 13:30:21 -07001198 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001199 SLOGE("Signing failed");
1200 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001201 }
1202
Paul Crowley14c8c072018-09-18 13:30:21 -07001203 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1204 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001205 free(signature);
1206
1207 if (rc) {
1208 SLOGE("scrypt failed");
1209 return -1;
1210 }
1211
1212 return 0;
1213}
1214
Paul Crowley14c8c072018-09-18 13:30:21 -07001215static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1216 const unsigned char* decrypted_master_key,
1217 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1218 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001219 EVP_CIPHER_CTX e_ctx;
1220 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001221 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001222
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001223 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001224 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001225
1226 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001227 case KDF_SCRYPT_KEYMASTER:
1228 if (keymaster_create_key(crypt_ftr)) {
1229 SLOGE("keymaster_create_key failed");
1230 return -1;
1231 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001232
Paul Crowley14c8c072018-09-18 13:30:21 -07001233 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1234 SLOGE("scrypt failed");
1235 return -1;
1236 }
1237 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001238
Paul Crowley14c8c072018-09-18 13:30:21 -07001239 case KDF_SCRYPT:
1240 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1241 SLOGE("scrypt failed");
1242 return -1;
1243 }
1244 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001245
Paul Crowley14c8c072018-09-18 13:30:21 -07001246 default:
1247 SLOGE("Invalid kdf_type");
1248 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001249 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001250
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001252 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001253 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1254 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001255 SLOGE("EVP_EncryptInit failed\n");
1256 return -1;
1257 }
1258 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001259
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001261 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1262 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263 SLOGE("EVP_EncryptUpdate failed\n");
1264 return -1;
1265 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001266 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001267 SLOGE("EVP_EncryptFinal failed\n");
1268 return -1;
1269 }
1270
Greg Kaiser59ad0182018-02-16 13:01:36 -08001271 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001272 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1273 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001274 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001275
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001276 /* Store the scrypt of the intermediate key, so we can validate if it's a
1277 password error or mount error when things go wrong.
1278 Note there's no need to check for errors, since if this is incorrect, we
1279 simply won't wipe userdata, which is the correct default behavior
1280 */
1281 int N = 1 << crypt_ftr->N_factor;
1282 int r = 1 << crypt_ftr->r_factor;
1283 int p = 1 << crypt_ftr->p_factor;
1284
Paul Crowley14c8c072018-09-18 13:30:21 -07001285 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1286 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001287 sizeof(crypt_ftr->scrypted_intermediate_key));
1288
1289 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001290 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001291 }
1292
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001293 EVP_CIPHER_CTX_cleanup(&e_ctx);
1294
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001295 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296}
1297
Paul Crowley14c8c072018-09-18 13:30:21 -07001298static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1299 const unsigned char* encrypted_master_key, size_t keysize,
1300 unsigned char* decrypted_master_key, kdf_func kdf,
1301 void* kdf_params, unsigned char** intermediate_key,
1302 size_t* intermediate_key_size) {
1303 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1304 EVP_CIPHER_CTX d_ctx;
1305 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306
Paul Crowley14c8c072018-09-18 13:30:21 -07001307 /* Turn the password into an intermediate key and IV that can decrypt the
1308 master key */
1309 if (kdf(passwd, salt, ikey, kdf_params)) {
1310 SLOGE("kdf failed");
1311 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001312 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001313
Paul Crowley14c8c072018-09-18 13:30:21 -07001314 /* Initialize the decryption engine */
1315 EVP_CIPHER_CTX_init(&d_ctx);
1316 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1317 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1318 return -1;
1319 }
1320 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1321 /* Decrypt the master key */
1322 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1323 keysize)) {
1324 return -1;
1325 }
1326 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1327 return -1;
1328 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001329
Paul Crowley14c8c072018-09-18 13:30:21 -07001330 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1331 return -1;
1332 }
1333
1334 /* Copy intermediate key if needed by params */
1335 if (intermediate_key && intermediate_key_size) {
1336 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1337 if (*intermediate_key) {
1338 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1339 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1340 }
1341 }
1342
1343 EVP_CIPHER_CTX_cleanup(&d_ctx);
1344
1345 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001346}
1347
Paul Crowley14c8c072018-09-18 13:30:21 -07001348static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001349 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001350 *kdf = scrypt_keymaster;
1351 *kdf_params = ftr;
1352 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001353 *kdf = scrypt;
1354 *kdf_params = ftr;
1355 } else {
1356 *kdf = pbkdf2;
1357 *kdf_params = NULL;
1358 }
1359}
1360
Paul Crowley14c8c072018-09-18 13:30:21 -07001361static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1362 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1363 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001364 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001365 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001366 int ret;
1367
1368 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001369 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1370 decrypted_master_key, kdf, kdf_params, intermediate_key,
1371 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001372 if (ret != 0) {
1373 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001374 }
1375
1376 return ret;
1377}
1378
Paul Crowley14c8c072018-09-18 13:30:21 -07001379static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1380 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001381 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001382
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001383 /* Get some random bits for a key and salt */
1384 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1385 return -1;
1386 }
1387 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1388 return -1;
1389 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001390
1391 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001392 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001393}
1394
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001395static void ensure_subdirectory_unmounted(const char *prefix) {
1396 std::vector<std::string> umount_points;
1397 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1398 if (!mnts) {
1399 SLOGW("could not read mount files");
1400 return;
1401 }
1402
1403 //Find sudirectory mount point
1404 mntent* mentry;
1405 std::string top_directory(prefix);
1406 if (!android::base::EndsWith(prefix, "/")) {
1407 top_directory = top_directory + "/";
1408 }
1409 while ((mentry = getmntent(mnts.get())) != nullptr) {
1410 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1411 continue;
1412 }
1413
1414 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1415 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1416 umount_points.push_back(mentry->mnt_dir);
1417 }
1418 }
1419
1420 //Sort by path length to umount longest path first
1421 std::sort(std::begin(umount_points), std::end(umount_points),
1422 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1423
1424 for (std::string& mount_point : umount_points) {
1425 umount(mount_point.c_str());
1426 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1427 }
1428}
1429
Paul Crowley73be12d2020-02-03 12:22:03 -08001430static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001431 int i, err, rc;
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001432
1433 // Subdirectory mount will cause a failure of umount.
1434 ensure_subdirectory_unmounted(mountpoint);
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001435#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001436
1437 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001438 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001439 if (umount(mountpoint) == 0) {
1440 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001442
1443 if (errno == EINVAL) {
1444 /* EINVAL is returned if the directory is not a mountpoint,
1445 * i.e. there is no filesystem mounted there. So just get out.
1446 */
1447 break;
1448 }
1449
1450 err = errno;
1451
1452 /* If allowed, be increasingly aggressive before the last two retries */
1453 if (kill) {
1454 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1455 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001456 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001457 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1458 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001459 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001460 }
1461 }
1462
1463 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001464 }
1465
1466 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001467 SLOGD("unmounting %s succeeded\n", mountpoint);
1468 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001469 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001470 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1471 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1472 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001473 }
1474
1475 return rc;
1476}
1477
Paul Crowley14c8c072018-09-18 13:30:21 -07001478static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001479 // NOTE: post_fs_data results in init calling back around to vold, so all
1480 // callers to this method must be async
1481
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001482 /* Do the prep of the /data filesystem */
1483 property_set("vold.post_fs_data_done", "0");
1484 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001485 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001486
Ken Sumrallc5872692013-05-14 15:26:31 -07001487 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001488 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001489 /* We timed out to prep /data in time. Continue wait. */
1490 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001491 }
Wei Wang42e38102017-06-07 10:46:12 -07001492 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001493}
1494
Paul Crowley14c8c072018-09-18 13:30:21 -07001495static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001496 // Mark the footer as bad
1497 struct crypt_mnt_ftr crypt_ftr;
1498 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1499 SLOGE("Failed to get crypto footer - panic");
1500 return;
1501 }
1502
1503 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1504 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1505 SLOGE("Failed to set crypto footer - panic");
1506 return;
1507 }
1508}
1509
Paul Crowley14c8c072018-09-18 13:30:21 -07001510static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001511 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001512 SLOGE("Failed to mount tmpfs on data - panic");
1513 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001514 }
1515
1516 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1517 SLOGE("Failed to trigger post fs data - panic");
1518 return;
1519 }
1520
1521 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1522 SLOGE("Failed to trigger restart min framework - panic");
1523 return;
1524 }
1525}
1526
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001527/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001528static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001529 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001530 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001531 static int restart_successful = 0;
1532
1533 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001534 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001535 SLOGE("Encrypted filesystem not validated, aborting");
1536 return -1;
1537 }
1538
1539 if (restart_successful) {
1540 SLOGE("System already restarted with encrypted disk, aborting");
1541 return -1;
1542 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001543
Paul Lawrencef4faa572014-01-29 13:31:03 -08001544 if (restart_main) {
1545 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001546 * start all services in one of these classes: core, early_hal, hal,
1547 * main and late_start. To get to the minimal UI for PIN entry, we
1548 * need to start core, early_hal, hal and main. When we want to
1549 * shutdown the framework again, we need to stop most of the services in
1550 * these classes, but only those services that were started after
1551 * /data was mounted. This excludes critical services like vold and
1552 * ueventd, which need to keep running. We could possible stop
1553 * even fewer services, but because we want services to pick up APEX
1554 * libraries from the real /data, restarting is better, as it makes
1555 * these devices consistent with FBE devices and lets them use the
1556 * most recent code.
1557 *
1558 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001559 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001560 * We then restart the class core, hal, main, and also the class
1561 * late_start.
1562 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001563 * At the moment, I've only put a few things in late_start that I know
1564 * are not needed to bring up the framework, and that also cause problems
1565 * with unmounting the tmpfs /data, but I hope to add add more services
1566 * to the late_start class as we optimize this to decrease the delay
1567 * till the user is asked for the password to the filesystem.
1568 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001570 /* The init files are setup to stop the right set of services when
1571 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001572 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001573 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001574 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001575
Paul Lawrencef4faa572014-01-29 13:31:03 -08001576 /* Ugh, shutting down the framework is not synchronous, so until it
1577 * can be fixed, this horrible hack will wait a moment for it all to
1578 * shut down before proceeding. Without it, some devices cannot
1579 * restart the graphics services.
1580 */
1581 sleep(2);
1582 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001583
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 /* Now that the framework is shutdown, we should be able to umount()
1585 * the tmpfs filesystem, and mount the real one.
1586 */
1587
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001588 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1589 if (strlen(crypto_blkdev) == 0) {
1590 SLOGE("fs_crypto_blkdev not set\n");
1591 return -1;
1592 }
1593
Paul Crowley14c8c072018-09-18 13:30:21 -07001594 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001595 /* If ro.crypto.readonly is set to 1, mount the decrypted
1596 * filesystem readonly. This is used when /data is mounted by
1597 * recovery mode.
1598 */
1599 char ro_prop[PROPERTY_VALUE_MAX];
1600 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001601 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001602 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1603 if (entry != nullptr) {
1604 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001605 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001606 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001607
Ken Sumralle5032c42012-04-01 23:58:44 -07001608 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001609 int retries = RETRY_MOUNT_ATTEMPTS;
1610 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001611
1612 /*
1613 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1614 * partitions in the fsck domain.
1615 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001616 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001617 SLOGE("Failed to setexeccon");
1618 return -1;
1619 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001620 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001621 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Paul Lawrence3fe93112020-06-12 08:12:48 -07001622 needs_cp, false)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001623 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1624 /* TODO: invoke something similar to
1625 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1626 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001627 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001628 if (--retries) {
1629 sleep(RETRY_MOUNT_DELAY_SECONDS);
1630 } else {
1631 /* Let's hope that a reboot clears away whatever is keeping
1632 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001633 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001634 }
1635 } else {
1636 SLOGE("Failed to mount decrypted data");
1637 cryptfs_set_corrupt();
1638 cryptfs_trigger_restart_min_framework();
1639 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001640 if (setexeccon(NULL)) {
1641 SLOGE("Failed to setexeccon");
1642 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001643 return -1;
1644 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001645 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001646 if (setexeccon(NULL)) {
1647 SLOGE("Failed to setexeccon");
1648 return -1;
1649 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001650
Ken Sumralle5032c42012-04-01 23:58:44 -07001651 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001652 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001653 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001654
1655 /* startup service classes main and late_start */
1656 property_set("vold.decrypt", "trigger_restart_framework");
1657 SLOGD("Just triggered restart_framework\n");
1658
1659 /* Give it a few moments to get started */
1660 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001661 }
1662
Ken Sumrall0cc16632011-01-18 20:32:26 -08001663 if (rc == 0) {
1664 restart_successful = 1;
1665 }
1666
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001667 return rc;
1668}
1669
Paul Crowley14c8c072018-09-18 13:30:21 -07001670int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001671 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001672 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001673 SLOGE("cryptfs_restart not valid for file encryption:");
1674 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001675 }
1676
Paul Lawrencef4faa572014-01-29 13:31:03 -08001677 /* Call internal implementation forcing a restart of main service group */
1678 return cryptfs_restart_internal(1);
1679}
1680
Paul Crowley14c8c072018-09-18 13:30:21 -07001681static int do_crypto_complete(const char* mount_point) {
1682 struct crypt_mnt_ftr crypt_ftr;
1683 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001684
Paul Crowley14c8c072018-09-18 13:30:21 -07001685 property_get("ro.crypto.state", encrypted_state, "");
1686 if (strcmp(encrypted_state, "encrypted")) {
1687 SLOGE("not running with encryption, aborting");
1688 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001689 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001690
Paul Crowley14c8c072018-09-18 13:30:21 -07001691 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001692 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001693 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1694 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001695
Paul Crowley14c8c072018-09-18 13:30:21 -07001696 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001697 std::string key_loc;
1698 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001699
Paul Crowley14c8c072018-09-18 13:30:21 -07001700 /*
1701 * Only report this error if key_loc is a file and it exists.
1702 * If the device was never encrypted, and /data is not mountable for
1703 * some reason, returning 1 should prevent the UI from presenting the
1704 * a "enter password" screen, or worse, a "press button to wipe the
1705 * device" screen.
1706 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001707 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001708 SLOGE("master key file does not exist, aborting");
1709 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1710 } else {
1711 SLOGE("Error getting crypt footer and key\n");
1712 return CRYPTO_COMPLETE_BAD_METADATA;
1713 }
1714 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001715
Paul Crowley14c8c072018-09-18 13:30:21 -07001716 // Test for possible error flags
1717 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1718 SLOGE("Encryption process is partway completed\n");
1719 return CRYPTO_COMPLETE_PARTIAL;
1720 }
1721
1722 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1723 SLOGE("Encryption process was interrupted but cannot continue\n");
1724 return CRYPTO_COMPLETE_INCONSISTENT;
1725 }
1726
1727 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1728 SLOGE("Encryption is successful but data is corrupt\n");
1729 return CRYPTO_COMPLETE_CORRUPT;
1730 }
1731
1732 /* We passed the test! We shall diminish, and return to the west */
1733 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001734}
1735
Paul Crowley14c8c072018-09-18 13:30:21 -07001736static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1737 const char* mount_point, const char* label) {
1738 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001739 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001740 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001741 char tmp_mount_point[64];
1742 unsigned int orig_failed_decrypt_count;
1743 int rc;
1744 int use_keymaster = 0;
1745 int upgrade = 0;
1746 unsigned char* intermediate_key = 0;
1747 size_t intermediate_key_size = 0;
1748 int N = 1 << crypt_ftr->N_factor;
1749 int r = 1 << crypt_ftr->r_factor;
1750 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001751
Paul Crowley14c8c072018-09-18 13:30:21 -07001752 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1753 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001754
Paul Crowley14c8c072018-09-18 13:30:21 -07001755 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1756 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1757 &intermediate_key_size)) {
1758 SLOGE("Failed to decrypt master key\n");
1759 rc = -1;
1760 goto errout;
1761 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001762 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001763
Tom Cherry4c5bde22019-01-29 14:34:01 -08001764 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001765
Paul Crowley14c8c072018-09-18 13:30:21 -07001766 // Create crypto block device - all (non fatal) code paths
1767 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001768 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001769 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001770 SLOGE("Error creating decrypted block device\n");
1771 rc = -1;
1772 goto errout;
1773 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001774
Paul Crowley14c8c072018-09-18 13:30:21 -07001775 /* Work out if the problem is the password or the data */
1776 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001777
Paul Crowley14c8c072018-09-18 13:30:21 -07001778 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1779 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1780 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001781
Paul Crowley14c8c072018-09-18 13:30:21 -07001782 // Does the key match the crypto footer?
1783 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1784 sizeof(scrypted_intermediate_key)) == 0) {
1785 SLOGI("Password matches");
1786 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001787 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001788 /* Try mounting the file system anyway, just in case the problem's with
1789 * the footer, not the key. */
1790 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1791 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001792 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1793 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001794 SLOGE("Error temp mounting decrypted block device\n");
1795 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001796
Paul Crowley14c8c072018-09-18 13:30:21 -07001797 rc = ++crypt_ftr->failed_decrypt_count;
1798 put_crypt_ftr_and_key(crypt_ftr);
1799 } else {
1800 /* Success! */
1801 SLOGI("Password did not match but decrypted drive mounted - continue");
1802 umount(tmp_mount_point);
1803 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001804 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001805 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001806
Paul Crowley14c8c072018-09-18 13:30:21 -07001807 if (rc == 0) {
1808 crypt_ftr->failed_decrypt_count = 0;
1809 if (orig_failed_decrypt_count != 0) {
1810 put_crypt_ftr_and_key(crypt_ftr);
1811 }
1812
1813 /* Save the name of the crypto block device
1814 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001815 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001816
1817 /* Also save a the master key so we can reencrypted the key
1818 * the key when we want to change the password on it. */
1819 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1820 saved_mount_point = strdup(mount_point);
1821 master_key_saved = 1;
1822 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1823 rc = 0;
1824
1825 // Upgrade if we're not using the latest KDF.
1826 use_keymaster = keymaster_check_compatibility();
1827 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1828 // Don't allow downgrade
1829 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1830 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1831 upgrade = 1;
1832 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1833 crypt_ftr->kdf_type = KDF_SCRYPT;
1834 upgrade = 1;
1835 }
1836
1837 if (upgrade) {
1838 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1839 crypt_ftr->master_key, crypt_ftr);
1840 if (!rc) {
1841 rc = put_crypt_ftr_and_key(crypt_ftr);
1842 }
1843 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1844
1845 // Do not fail even if upgrade failed - machine is bootable
1846 // Note that if this code is ever hit, there is a *serious* problem
1847 // since KDFs should never fail. You *must* fix the kdf before
1848 // proceeding!
1849 if (rc) {
1850 SLOGW(
1851 "Upgrade failed with error %d,"
1852 " but continuing with previous state",
1853 rc);
1854 rc = 0;
1855 }
1856 }
1857 }
1858
1859errout:
1860 if (intermediate_key) {
1861 memset(intermediate_key, 0, intermediate_key_size);
1862 free(intermediate_key);
1863 }
1864 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001865}
1866
Ken Sumrall29d8da82011-05-18 17:20:07 -07001867/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001868 * Called by vold when it's asked to mount an encrypted external
1869 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001870 * as any metadata is been stored in a separate, small partition. We
1871 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001872 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001873int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001874 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001875 auto crypto_type = get_crypto_type();
1876 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001877 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001878 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001879 return -1;
1880 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001881 uint64_t nr_sec = 0;
1882 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001883 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001884 return -1;
1885 }
1886
Jeff Sharkey9c484982015-03-31 10:35:33 -07001887 struct crypt_mnt_ftr ext_crypt_ftr;
1888 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1889 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001890 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1891 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001892 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001893 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001894 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001895 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1896 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001897
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001898 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1899 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001900}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001901
Paul Crowley14c8c072018-09-18 13:30:21 -07001902int cryptfs_crypto_complete(void) {
1903 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001904}
1905
Paul Crowley14c8c072018-09-18 13:30:21 -07001906int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001907 char encrypted_state[PROPERTY_VALUE_MAX];
1908 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001909 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1910 SLOGE(
1911 "encrypted fs already validated or not running with encryption,"
1912 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001913 return -1;
1914 }
1915
1916 if (get_crypt_ftr_and_key(crypt_ftr)) {
1917 SLOGE("Error getting crypt footer and key");
1918 return -1;
1919 }
1920
1921 return 0;
1922}
1923
Paul Crowley14c8c072018-09-18 13:30:21 -07001924int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001925 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001926 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001927 SLOGE("cryptfs_check_passwd not valid for file encryption");
1928 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001929 }
1930
Paul Lawrencef4faa572014-01-29 13:31:03 -08001931 struct crypt_mnt_ftr crypt_ftr;
1932 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001933
Paul Lawrencef4faa572014-01-29 13:31:03 -08001934 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001935 if (rc) {
1936 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001937 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001938 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001939
Paul Crowley14c8c072018-09-18 13:30:21 -07001940 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001941 if (rc) {
1942 SLOGE("Password did not match");
1943 return rc;
1944 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001945
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001946 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1947 // Here we have a default actual password but a real password
1948 // we must test against the scrypted value
1949 // First, we must delete the crypto block device that
1950 // test_mount_encrypted_fs leaves behind as a side effect
1951 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001952 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1953 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001954 if (rc) {
1955 SLOGE("Default password did not match on reboot encryption");
1956 return rc;
1957 }
1958
1959 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1960 put_crypt_ftr_and_key(&crypt_ftr);
1961 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1962 if (rc) {
1963 SLOGE("Could not change password on reboot encryption");
1964 return rc;
1965 }
1966 }
1967
1968 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001969 cryptfs_clear_password();
1970 password = strdup(passwd);
1971 struct timespec now;
1972 clock_gettime(CLOCK_BOOTTIME, &now);
1973 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001974 }
1975
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001976 return rc;
1977}
1978
Paul Crowley14c8c072018-09-18 13:30:21 -07001979int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001980 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001981 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001982 char encrypted_state[PROPERTY_VALUE_MAX];
1983 int rc;
1984
1985 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001986 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001987 SLOGE("device not encrypted, aborting");
1988 return -2;
1989 }
1990
1991 if (!master_key_saved) {
1992 SLOGE("encrypted fs not yet mounted, aborting");
1993 return -1;
1994 }
1995
1996 if (!saved_mount_point) {
1997 SLOGE("encrypted fs failed to save mount point, aborting");
1998 return -1;
1999 }
2000
Ken Sumrall160b4d62013-04-22 12:15:39 -07002001 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002002 SLOGE("Error getting crypt footer and key\n");
2003 return -1;
2004 }
2005
2006 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2007 /* If the device has no password, then just say the password is valid */
2008 rc = 0;
2009 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002010 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002011 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2012 /* They match, the password is correct */
2013 rc = 0;
2014 } else {
2015 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2016 sleep(1);
2017 rc = 1;
2018 }
2019 }
2020
2021 return rc;
2022}
2023
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002024/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002025 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002026 * Presumably, at a minimum, the caller will update the
2027 * filesystem size and crypto_type_name after calling this function.
2028 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002029static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002030 off64_t off;
2031
2032 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002033 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002034 ftr->major_version = CURRENT_MAJOR_VERSION;
2035 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002036 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002037 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002038
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002039 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002040 case 1:
2041 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2042 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002043
Paul Crowley14c8c072018-09-18 13:30:21 -07002044 case 0:
2045 ftr->kdf_type = KDF_SCRYPT;
2046 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002047
Paul Crowley14c8c072018-09-18 13:30:21 -07002048 default:
2049 SLOGE("keymaster_check_compatibility failed");
2050 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002051 }
2052
Kenny Rootc4c70f12013-06-14 12:11:38 -07002053 get_device_scrypt_params(ftr);
2054
Ken Sumrall160b4d62013-04-22 12:15:39 -07002055 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2056 if (get_crypt_ftr_info(NULL, &off) == 0) {
2057 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002058 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002059 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002060
2061 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002062}
2063
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002064#define FRAMEWORK_BOOT_WAIT 60
2065
Paul Crowley81796e92020-02-07 11:27:49 -08002066static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
Eric Biggersc01995e2020-11-03 14:11:00 -08002067 const char* real_blkdev) {
Tim Murray8439dc92014-12-15 11:56:11 -08002068 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002069
Eric Biggersc01995e2020-11-03 14:11:00 -08002070 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002071
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002072 if (rc == ENABLE_INPLACE_ERR_DEV) {
2073 /* Hack for b/17898962 */
2074 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2075 cryptfs_reboot(RebootType::reboot);
2076 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002077
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002078 if (!rc) {
Eric Biggersc01995e2020-11-03 14:11:00 -08002079 crypt_ftr->encrypted_upto = crypt_ftr->fs_size;
Paul Lawrence87999172014-02-20 12:21:31 -08002080
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002081 /* The inplace routine never actually sets the progress to 100% due
2082 * to the round down nature of integer division, so set it here */
2083 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002084 }
2085
2086 return rc;
2087}
2088
Paul Crowleyb64933a2017-10-31 08:25:55 -07002089static int vold_unmountAll(void) {
2090 VolumeManager* vm = VolumeManager::Instance();
2091 return vm->unmountAll();
2092}
2093
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002094int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002095 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002096 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002097 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002098 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002099 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002100 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002101 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002102 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002103 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002104 int num_vols;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002105 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002106 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002107 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002108
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002109 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Eric Biggersc01995e2020-11-03 14:11:00 -08002110 if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002111 if (!check_ftr_sha(&crypt_ftr)) {
2112 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2113 put_crypt_ftr_and_key(&crypt_ftr);
2114 goto error_unencrypted;
2115 }
2116
2117 /* Doing a reboot-encryption*/
2118 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2119 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2120 rebootEncryption = true;
2121 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002122 } else {
2123 // We don't want to accidentally reference invalid data.
2124 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002125 }
2126
2127 property_get("ro.crypto.state", encrypted_state, "");
Eric Biggersc01995e2020-11-03 14:11:00 -08002128 if (!strcmp(encrypted_state, "encrypted")) {
Paul Lawrence87999172014-02-20 12:21:31 -08002129 SLOGE("Device is already running encrypted, aborting");
2130 goto error_unencrypted;
2131 }
2132
Tom Cherry4c5bde22019-01-29 14:34:01 -08002133 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002134
Ken Sumrall3ed82362011-01-28 23:31:16 -08002135 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002136 uint64_t nr_sec;
2137 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002138 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002139 goto error_unencrypted;
2140 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002141
2142 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002143 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002144 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002145 fs_size_sec = get_fs_size(real_blkdev.c_str());
2146 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002147
Paul Lawrence87999172014-02-20 12:21:31 -08002148 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002149
2150 if (fs_size_sec > max_fs_size_sec) {
2151 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2152 goto error_unencrypted;
2153 }
2154 }
2155
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002156 /* Get a wakelock as this may take a while, and we don't want the
2157 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2158 * wants to keep the screen on, it can grab a full wakelock.
2159 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002160 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002161 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002162
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002163 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002164 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002165 */
2166 property_set("vold.decrypt", "trigger_shutdown_framework");
2167 SLOGD("Just asked init to shut down class main\n");
2168
Jeff Sharkey9c484982015-03-31 10:35:33 -07002169 /* Ask vold to unmount all devices that it manages */
2170 if (vold_unmountAll()) {
2171 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002172 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002173
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002174 /* no_ui means we are being called from init, not settings.
2175 Now we always reboot from settings, so !no_ui means reboot
2176 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002177 if (!no_ui) {
2178 /* Try fallback, which is to reboot and try there */
2179 onlyCreateHeader = true;
2180 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2181 if (breadcrumb == 0) {
2182 SLOGE("Failed to create breadcrumb file");
2183 goto error_shutting_down;
2184 }
2185 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002186 }
2187
2188 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002189 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002190 /* Now that /data is unmounted, we need to mount a tmpfs
2191 * /data, set a property saying we're doing inplace encryption,
2192 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002193 */
xzj7e38a3a2018-10-12 10:17:11 +08002194 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002195 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002196 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002197 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002198 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002199 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002201 /* restart the framework. */
2202 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002203 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002204
Ken Sumrall92736ef2012-10-17 20:57:14 -07002205 /* Ugh, shutting down the framework is not synchronous, so until it
2206 * can be fixed, this horrible hack will wait a moment for it all to
2207 * shut down before proceeding. Without it, some devices cannot
2208 * restart the graphics services.
2209 */
2210 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002211 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002212
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002213 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002214 /* Initialize a crypt_mnt_ftr for the partition */
Eric Biggersc01995e2020-11-03 14:11:00 -08002215 if (!rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002216 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2217 goto error_shutting_down;
2218 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002219
Tom Cherry4c5bde22019-01-29 14:34:01 -08002220 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002221 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002222 } else {
2223 crypt_ftr.fs_size = nr_sec;
2224 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002225 /* At this point, we are in an inconsistent state. Until we successfully
2226 complete encryption, a reboot will leave us broken. So mark the
2227 encryption failed in case that happens.
2228 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002229 if (onlyCreateHeader) {
2230 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2231 } else {
2232 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2233 }
Paul Lawrence87999172014-02-20 12:21:31 -08002234 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002235 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002236 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002237
Paul Lawrence87999172014-02-20 12:21:31 -08002238 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002239 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2240 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002241 SLOGE("Cannot create encrypted master key\n");
2242 goto error_shutting_down;
2243 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002244
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002245 /* Replace scrypted intermediate key if we are preparing for a reboot */
2246 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002247 unsigned char fake_master_key[MAX_KEY_LEN];
2248 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002249 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002250 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2251 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002252 }
2253
Paul Lawrence87999172014-02-20 12:21:31 -08002254 /* Write the key to the end of the partition */
2255 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002256
Paul Lawrence87999172014-02-20 12:21:31 -08002257 /* If any persistent data has been remembered, save it.
2258 * If none, create a valid empty table and save that.
2259 */
2260 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002261 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2262 if (pdata) {
2263 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2264 persist_data = pdata;
2265 }
Paul Lawrence87999172014-02-20 12:21:31 -08002266 }
2267 if (persist_data) {
2268 save_persistent_data();
2269 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002270 }
2271
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002272 if (onlyCreateHeader) {
2273 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002274 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002275 }
2276
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002277 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002278 /* startup service classes main and late_start */
2279 property_set("vold.decrypt", "trigger_restart_min_framework");
2280 SLOGD("Just triggered restart_min_framework\n");
2281
2282 /* OK, the framework is restarted and will soon be showing a
2283 * progress bar. Time to setup an encrypted mapping, and
2284 * either write a new filesystem, or encrypt in place updating
2285 * the progress bar as we work.
2286 */
2287 }
2288
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002289 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Eric Biggers88f993b2020-11-03 14:11:00 -08002290 rc = create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(),
2291 &crypto_blkdev, CRYPTO_BLOCK_DEVICE, 0);
2292 if (!rc) {
2293 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data());
Ken Sumrall29d8da82011-05-18 17:20:07 -07002294
Eric Biggers88f993b2020-11-03 14:11:00 -08002295 /* Undo the dm-crypt mapping whether we succeed or not */
2296 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2297 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002298
Paul Crowley14c8c072018-09-18 13:30:21 -07002299 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002300 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002301 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002302
Paul Lawrence6bfed202014-07-28 12:47:22 -07002303 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002304
Eric Biggersc01995e2020-11-03 14:11:00 -08002305 char value[PROPERTY_VALUE_MAX];
2306 property_get("ro.crypto.state", value, "");
2307 if (!strcmp(value, "")) {
2308 /* default encryption - continue first boot sequence */
2309 property_set("ro.crypto.state", "encrypted");
2310 property_set("ro.crypto.type", "block");
2311 wakeLock.reset(nullptr);
2312 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2313 // Bring up cryptkeeper that will check the password and set it
2314 property_set("vold.decrypt", "trigger_shutdown_framework");
2315 sleep(2);
2316 property_set("vold.encrypt_progress", "");
2317 cryptfs_trigger_restart_min_framework();
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002318 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002319 cryptfs_check_passwd(DEFAULT_PASSWORD);
2320 cryptfs_restart_internal(1);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002321 }
Eric Biggersc01995e2020-11-03 14:11:00 -08002322 return 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002323 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002324 sleep(2); /* Give the UI a chance to show 100% progress */
2325 cryptfs_reboot(RebootType::reboot);
Paul Lawrence87999172014-02-20 12:21:31 -08002326 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002327 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002328 char value[PROPERTY_VALUE_MAX];
2329
Ken Sumrall319369a2012-06-27 16:30:18 -07002330 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002331 if (!strcmp(value, "1")) {
2332 /* wipe data if encryption failed */
2333 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002334 std::string err;
2335 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002336 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002337 if (!write_bootloader_message(options, &err)) {
2338 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002339 }
Josh Gaofec44372017-08-28 13:22:55 -07002340 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002341 } else {
2342 /* set property to trigger dialog */
2343 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002344 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002345 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002346 }
2347
Ken Sumrall3ed82362011-01-28 23:31:16 -08002348 /* hrm, the encrypt step claims success, but the reboot failed.
2349 * This should not happen.
2350 * Set the property and return. Hope the framework can deal with it.
2351 */
2352 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002353 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002354
2355error_unencrypted:
2356 property_set("vold.encrypt_progress", "error_not_encrypted");
2357 return -1;
2358
2359error_shutting_down:
2360 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2361 * but the framework is stopped and not restarted to show the error, so it's up to
2362 * vold to restart the system.
2363 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002364 SLOGE(
2365 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2366 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002367 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002368
2369 /* shouldn't get here */
2370 property_set("vold.encrypt_progress", "error_shutting_down");
2371 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002372}
2373
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002374int cryptfs_enable(int type, const char* passwd, int no_ui) {
2375 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002376}
2377
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002378int cryptfs_enable_default(int no_ui) {
2379 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002380}
2381
Paul Crowley14c8c072018-09-18 13:30:21 -07002382int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002383 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002384 SLOGE("cryptfs_changepw not valid for file encryption");
2385 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002386 }
2387
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002388 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002389 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002390
2391 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002392 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002393 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002394 return -1;
2395 }
2396
Paul Lawrencef4faa572014-01-29 13:31:03 -08002397 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2398 SLOGE("Invalid crypt_type %d", crypt_type);
2399 return -1;
2400 }
2401
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002402 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002403 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002404 SLOGE("Error getting crypt footer and key");
2405 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002406 }
2407
Paul Lawrencef4faa572014-01-29 13:31:03 -08002408 crypt_ftr.crypt_type = crypt_type;
2409
Paul Crowley14c8c072018-09-18 13:30:21 -07002410 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2411 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002412 if (rc) {
2413 SLOGE("Encrypt master key failed: %d", rc);
2414 return -1;
2415 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002416 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002417 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002418
2419 return 0;
2420}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002421
Rubin Xu85c01f92014-10-13 12:49:54 +01002422static unsigned int persist_get_max_entries(int encrypted) {
2423 struct crypt_mnt_ftr crypt_ftr;
2424 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002425
2426 /* If encrypted, use the values from the crypt_ftr, otherwise
2427 * use the values for the current spec.
2428 */
2429 if (encrypted) {
2430 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002431 /* Something is wrong, assume no space for entries */
2432 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002433 }
2434 dsize = crypt_ftr.persist_data_size;
2435 } else {
2436 dsize = CRYPT_PERSIST_DATA_SIZE;
2437 }
2438
Rubin Xuf83cc612018-10-09 16:13:38 +01002439 if (dsize > sizeof(struct crypt_persist_data)) {
2440 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2441 } else {
2442 return 0;
2443 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002444}
2445
Paul Crowley14c8c072018-09-18 13:30:21 -07002446static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002447 unsigned int i;
2448
2449 if (persist_data == NULL) {
2450 return -1;
2451 }
2452 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2453 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2454 /* We found it! */
2455 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2456 return 0;
2457 }
2458 }
2459
2460 return -1;
2461}
2462
Paul Crowley14c8c072018-09-18 13:30:21 -07002463static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002464 unsigned int i;
2465 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002466 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002467
2468 if (persist_data == NULL) {
2469 return -1;
2470 }
2471
Rubin Xu85c01f92014-10-13 12:49:54 +01002472 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002473
2474 num = persist_data->persist_valid_entries;
2475
2476 for (i = 0; i < num; i++) {
2477 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2478 /* We found an existing entry, update it! */
2479 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2480 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2481 return 0;
2482 }
2483 }
2484
2485 /* We didn't find it, add it to the end, if there is room */
2486 if (persist_data->persist_valid_entries < max_persistent_entries) {
2487 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2488 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2489 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2490 persist_data->persist_valid_entries++;
2491 return 0;
2492 }
2493
2494 return -1;
2495}
2496
Rubin Xu85c01f92014-10-13 12:49:54 +01002497/**
2498 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2499 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2500 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002501int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002502 std::string key_ = key;
2503 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002504
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002505 std::string parsed_field;
2506 unsigned parsed_index;
2507
2508 std::string::size_type split = key_.find_last_of('_');
2509 if (split == std::string::npos) {
2510 parsed_field = key_;
2511 parsed_index = 0;
2512 } else {
2513 parsed_field = key_.substr(0, split);
2514 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002515 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002516
2517 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002518}
2519
2520/*
2521 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2522 * remaining entries starting from index will be deleted.
2523 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2524 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2525 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2526 *
2527 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002528static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002529 unsigned int i;
2530 unsigned int j;
2531 unsigned int num;
2532
2533 if (persist_data == NULL) {
2534 return PERSIST_DEL_KEY_ERROR_OTHER;
2535 }
2536
2537 num = persist_data->persist_valid_entries;
2538
Paul Crowley14c8c072018-09-18 13:30:21 -07002539 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002540 // Filter out to-be-deleted entries in place.
2541 for (i = 0; i < num; i++) {
2542 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2543 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2544 j++;
2545 }
2546 }
2547
2548 if (j < num) {
2549 persist_data->persist_valid_entries = j;
2550 // Zeroise the remaining entries
2551 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2552 return PERSIST_DEL_KEY_OK;
2553 } else {
2554 // Did not find an entry matching the given fieldname
2555 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2556 }
2557}
2558
Paul Crowley14c8c072018-09-18 13:30:21 -07002559static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002560 unsigned int i;
2561 unsigned int count;
2562
2563 if (persist_data == NULL) {
2564 return -1;
2565 }
2566
2567 count = 0;
2568 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2569 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2570 count++;
2571 }
2572 }
2573
2574 return count;
2575}
2576
Ken Sumrall160b4d62013-04-22 12:15:39 -07002577/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002578int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002579 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002580 SLOGE("Cannot get field when file encrypted");
2581 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002582 }
2583
Ken Sumrall160b4d62013-04-22 12:15:39 -07002584 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002585 /* CRYPTO_GETFIELD_OK is success,
2586 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2587 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2588 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002589 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002590 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2591 int i;
2592 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002593
2594 if (persist_data == NULL) {
2595 load_persistent_data();
2596 if (persist_data == NULL) {
2597 SLOGE("Getfield error, cannot load persistent data");
2598 goto out;
2599 }
2600 }
2601
Rubin Xu85c01f92014-10-13 12:49:54 +01002602 // Read value from persistent entries. If the original value is split into multiple entries,
2603 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002604 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002605 // 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 -07002606 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002607 // value too small
2608 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2609 goto out;
2610 }
2611 rc = CRYPTO_GETFIELD_OK;
2612
2613 for (i = 1; /* break explicitly */; i++) {
2614 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002615 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002616 // If the fieldname is very long, we stop as soon as it begins to overflow the
2617 // maximum field length. At this point we have in fact fully read out the original
2618 // value because cryptfs_setfield would not allow fields with longer names to be
2619 // written in the first place.
2620 break;
2621 }
2622 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002623 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2624 // value too small.
2625 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2626 goto out;
2627 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002628 } else {
2629 // Exhaust all entries.
2630 break;
2631 }
2632 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002633 } else {
2634 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002635 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002636 }
2637
2638out:
2639 return rc;
2640}
2641
2642/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002643int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002644 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002645 SLOGE("Cannot set field when file encrypted");
2646 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002647 }
2648
Ken Sumrall160b4d62013-04-22 12:15:39 -07002649 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002650 /* 0 is success, negative values are error */
2651 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002652 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002653 unsigned int field_id;
2654 char temp_field[PROPERTY_KEY_MAX];
2655 unsigned int num_entries;
2656 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002657
2658 if (persist_data == NULL) {
2659 load_persistent_data();
2660 if (persist_data == NULL) {
2661 SLOGE("Setfield error, cannot load persistent data");
2662 goto out;
2663 }
2664 }
2665
2666 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002667 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002668 encrypted = 1;
2669 }
2670
Rubin Xu85c01f92014-10-13 12:49:54 +01002671 // Compute the number of entries required to store value, each entry can store up to
2672 // (PROPERTY_VALUE_MAX - 1) chars
2673 if (strlen(value) == 0) {
2674 // Empty value also needs one entry to store.
2675 num_entries = 1;
2676 } else {
2677 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2678 }
2679
2680 max_keylen = strlen(fieldname);
2681 if (num_entries > 1) {
2682 // Need an extra "_%d" suffix.
2683 max_keylen += 1 + log10(num_entries);
2684 }
2685 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2686 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002687 goto out;
2688 }
2689
Rubin Xu85c01f92014-10-13 12:49:54 +01002690 // Make sure we have enough space to write the new value
2691 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2692 persist_get_max_entries(encrypted)) {
2693 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2694 goto out;
2695 }
2696
2697 // Now that we know persist_data has enough space for value, let's delete the old field first
2698 // to make up space.
2699 persist_del_keys(fieldname, 0);
2700
2701 if (persist_set_key(fieldname, value, encrypted)) {
2702 // fail to set key, should not happen as we have already checked the available space
2703 SLOGE("persist_set_key() error during setfield()");
2704 goto out;
2705 }
2706
2707 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002708 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002709
2710 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2711 // fail to set key, should not happen as we have already checked the available space.
2712 SLOGE("persist_set_key() error during setfield()");
2713 goto out;
2714 }
2715 }
2716
Ken Sumrall160b4d62013-04-22 12:15:39 -07002717 /* If we are running encrypted, save the persistent data now */
2718 if (encrypted) {
2719 if (save_persistent_data()) {
2720 SLOGE("Setfield error, cannot save persistent data");
2721 goto out;
2722 }
2723 }
2724
Rubin Xu85c01f92014-10-13 12:49:54 +01002725 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002726
2727out:
2728 return rc;
2729}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002730
2731/* Checks userdata. Attempt to mount the volume if default-
2732 * encrypted.
2733 * On success trigger next init phase and return 0.
2734 * Currently do not handle failure - see TODO below.
2735 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002736int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002737 int crypt_type = cryptfs_get_password_type();
2738 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2739 SLOGE("Bad crypt type - error");
2740 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002741 SLOGD(
2742 "Password is not default - "
2743 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002744 property_set("vold.decrypt", "trigger_restart_min_framework");
2745 return 0;
2746 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2747 SLOGD("Password is default - restarting filesystem");
2748 cryptfs_restart_internal(0);
2749 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002750 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002751 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002752 }
2753
Paul Lawrence6bfed202014-07-28 12:47:22 -07002754 /** Corrupt. Allow us to boot into framework, which will detect bad
2755 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002756 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002757 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002758 return 0;
2759}
2760
2761/* Returns type of the password, default, pattern, pin or password.
2762 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002763int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002764 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002765 SLOGE("cryptfs_get_password_type not valid for file encryption");
2766 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002767 }
2768
Paul Lawrencef4faa572014-01-29 13:31:03 -08002769 struct crypt_mnt_ftr crypt_ftr;
2770
2771 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2772 SLOGE("Error getting crypt footer and key\n");
2773 return -1;
2774 }
2775
Paul Lawrence6bfed202014-07-28 12:47:22 -07002776 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2777 return -1;
2778 }
2779
Paul Lawrencef4faa572014-01-29 13:31:03 -08002780 return crypt_ftr.crypt_type;
2781}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002782
Paul Crowley14c8c072018-09-18 13:30:21 -07002783const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002784 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002785 SLOGE("cryptfs_get_password not valid for file encryption");
2786 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002787 }
2788
Paul Lawrence399317e2014-03-10 13:20:50 -07002789 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002790 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002791 if (now.tv_sec < password_expiry_time) {
2792 return password;
2793 } else {
2794 cryptfs_clear_password();
2795 return 0;
2796 }
2797}
2798
Paul Crowley14c8c072018-09-18 13:30:21 -07002799void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002800 if (password) {
2801 size_t len = strlen(password);
2802 memset(password, 0, len);
2803 free(password);
2804 password = 0;
2805 password_expiry_time = 0;
2806 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002807}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002808
Paul Crowley14c8c072018-09-18 13:30:21 -07002809int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002810 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2811 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002812}