blob: faed65be36fac5ea64d05903f8abd2547eb7a0ae [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
Eric Biggersf038c5f2020-11-03 14:11:02 -080093#define CRYPT_SECTOR_SIZE 512
94
Paul Crowley73be12d2020-02-03 12:22:03 -080095#define MAX_CRYPTO_TYPE_NAME_LEN 64
96
97#define MAX_KEY_LEN 48
98#define SALT_LEN 16
99#define SCRYPT_LEN 32
100
101/* definitions of flags in the structure below */
102#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
Eric Biggersc01995e2020-11-03 14:11:00 -0800103#define CRYPT_ENCRYPTION_IN_PROGRESS 0x2 /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800104#define CRYPT_INCONSISTENT_STATE \
105 0x4 /* Set when starting encryption, clear when \
106 exit cleanly, either through success or \
107 correctly marked partial encryption */
108#define CRYPT_DATA_CORRUPT \
109 0x8 /* Set when encryption is fine, but the \
110 underlying volume is corrupt */
111#define CRYPT_FORCE_ENCRYPTION \
112 0x10 /* Set when it is time to encrypt this \
113 volume on boot. Everything in this \
114 structure is set up correctly as \
115 though device is encrypted except \
116 that the master key is encrypted with the \
117 default password. */
118#define CRYPT_FORCE_COMPLETE \
119 0x20 /* Set when the above encryption cycle is \
120 complete. On next cryptkeeper entry, match \
121 the password. If it matches fix the master \
122 key and remove this flag. */
123
124/* Allowed values for type in the structure below */
125#define CRYPT_TYPE_PASSWORD \
126 0 /* master_key is encrypted with a password \
127 * Must be zero to be compatible with pre-L \
128 * devices where type is always password.*/
129#define CRYPT_TYPE_DEFAULT \
130 1 /* master_key is encrypted with default \
131 * password */
132#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
133#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
134#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
135
136#define CRYPT_MNT_MAGIC 0xD0B5B1C4
137#define PERSIST_DATA_MAGIC 0xE950CD44
138
139/* Key Derivation Function algorithms */
140#define KDF_PBKDF2 1
141#define KDF_SCRYPT 2
142/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
143#define KDF_SCRYPT_KEYMASTER 5
144
145/* Maximum allowed keymaster blob size. */
146#define KEYMASTER_BLOB_SIZE 2048
147
148/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
149#define __le8 unsigned char
150
151#if !defined(SHA256_DIGEST_LENGTH)
152#define SHA256_DIGEST_LENGTH 32
153#endif
154
155/* This structure starts 16,384 bytes before the end of a hardware
156 * partition that is encrypted, or in a separate partition. It's location
157 * is specified by a property set in init.<device>.rc.
158 * The structure allocates 48 bytes for a key, but the real key size is
159 * specified in the struct. Currently, the code is hardcoded to use 128
160 * bit keys.
161 * The fields after salt are only valid in rev 1.1 and later stuctures.
162 * Obviously, the filesystem does not include the last 16 kbytes
163 * of the partition if the crypt_mnt_ftr lives at the end of the
164 * partition.
165 */
166
167struct crypt_mnt_ftr {
168 __le32 magic; /* See above */
169 __le16 major_version;
170 __le16 minor_version;
171 __le32 ftr_size; /* in bytes, not including key following */
172 __le32 flags; /* See above */
173 __le32 keysize; /* in bytes */
174 __le32 crypt_type; /* how master_key is encrypted. Must be a
175 * CRYPT_TYPE_XXX value */
176 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
177 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
178 mount, set to 0 on successful mount */
179 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
180 needed to decrypt this
181 partition, null terminated */
182 __le32 spare2; /* ignored */
183 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
184 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
185 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
186 * on device with that info, either the footer of the
187 * real_blkdevice or the metadata partition. */
188
189 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
190 * persistent data table*/
191
192 __le8 kdf_type; /* The key derivation function used. */
193
194 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
195 __le8 N_factor; /* (1 << N) */
196 __le8 r_factor; /* (1 << r) */
197 __le8 p_factor; /* (1 << p) */
Eric Biggersc01995e2020-11-03 14:11:00 -0800198 __le64 encrypted_upto; /* no longer used */
199 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* no longer used */
Paul Crowley73be12d2020-02-03 12:22:03 -0800200
201 /* key_master key, used to sign the derived key which is then used to generate
202 * the intermediate key
203 * This key should be used for no other purposes! We use this key to sign unpadded
204 * data, which is acceptable but only if the key is not reused elsewhere. */
205 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
206 __le32 keymaster_blob_size;
207
208 /* Store scrypt of salted intermediate key. When decryption fails, we can
209 check if this matches, and if it does, we know that the problem is with the
210 drive, and there is no point in asking the user for more passwords.
211
212 Note that if any part of this structure is corrupt, this will not match and
213 we will continue to believe the user entered the wrong password. In that
214 case the only solution is for the user to enter a password enough times to
215 force a wipe.
216
217 Note also that there is no need to worry about migration. If this data is
218 wrong, we simply won't recognise a right password, and will continue to
219 prompt. On the first password change, this value will be populated and
220 then we will be OK.
221 */
222 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
223
224 /* sha of this structure with this element set to zero
225 Used when encrypting on reboot to validate structure before doing something
226 fatal
227 */
228 unsigned char sha256[SHA256_DIGEST_LENGTH];
229};
230
231/* Persistant data that should be available before decryption.
232 * Things like airplane mode, locale and timezone are kept
233 * here and can be retrieved by the CryptKeeper UI to properly
234 * configure the phone before asking for the password
235 * This is only valid if the major and minor version above
236 * is set to 1.1 or higher.
237 *
238 * This is a 4K structure. There are 2 copies, and the code alternates
239 * writing one and then clearing the previous one. The reading
240 * code reads the first valid copy it finds, based on the magic number.
241 * The absolute offset to the first of the two copies is kept in rev 1.1
242 * and higher crypt_mnt_ftr structures.
243 */
244struct crypt_persist_entry {
245 char key[PROPERTY_KEY_MAX];
246 char val[PROPERTY_VALUE_MAX];
247};
248
249/* Should be exactly 4K in size */
250struct crypt_persist_data {
251 __le32 persist_magic;
252 __le32 persist_valid_entries;
253 __le32 persist_spare[30];
254 struct crypt_persist_entry persist_entry[0];
255};
256
257static int wait_and_unmount(const char* mountpoint, bool kill);
258
259typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
260 void* params);
261
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800262#define UNUSED __attribute__((unused))
263
Jason parks70a4b3f2011-01-28 10:10:47 -0600264#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800265
266constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
267constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700268constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800269
270// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700271static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600272
Paul Crowley14c8c072018-09-18 13:30:21 -0700273#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700274
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700275#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800276
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800277#define CRYPTO_BLOCK_DEVICE "userdata"
278
279#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
280
Ken Sumrall29d8da82011-05-18 17:20:07 -0700281#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700282#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700283
Ken Sumralle919efe2012-09-29 17:07:41 -0700284#define TABLE_LOAD_RETRIES 10
285
Shawn Willden47ba10d2014-09-03 17:07:06 -0600286#define RSA_KEY_SIZE 2048
287#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
288#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600289#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700290
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700291#define RETRY_MOUNT_ATTEMPTS 10
292#define RETRY_MOUNT_DELAY_SECONDS 1
293
Paul Crowley5afbc622017-11-27 09:42:17 -0800294#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
295
Paul Crowley73473332017-11-21 15:43:51 -0800296static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
297
Greg Kaiser59ad0182018-02-16 13:01:36 -0800298static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700299static char* saved_mount_point;
300static int master_key_saved = 0;
301static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800302
Paul Crowley220567c2020-02-07 12:45:20 -0800303constexpr CryptoType aes_128_cbc = CryptoType()
304 .set_config_name("AES-128-CBC")
305 .set_kernel_name("aes-cbc-essiv:sha256")
306 .set_keysize(16);
307
308constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
309
310static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
311 array_length(supported_crypto_types)),
312 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
313 "incompletely constructed.");
314
315static const CryptoType& get_crypto_type() {
316 // We only want to parse this read-only property once. But we need to wait
317 // until the system is initialized before we can read it. So we use a static
318 // scoped within this function to get it only once.
319 static CryptoType crypto_type =
320 lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
321 aes_128_cbc, "ro.crypto.fde_algorithm");
322 return crypto_type;
323}
324
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800325const KeyGeneration cryptfs_get_keygen() {
Paul Crowley249c2fb2020-02-07 12:51:56 -0800326 return KeyGeneration{get_crypto_type().get_keysize(), true, false};
Paul Crowleyb3d018a2020-02-12 11:04:05 -0800327}
328
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700329/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700330static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000331 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700332}
333
334/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700335static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800336 if (ftr->keymaster_blob_size) {
337 SLOGI("Already have key");
338 return 0;
339 }
340
Paul Crowley14c8c072018-09-18 13:30:21 -0700341 int rc = keymaster_create_key_for_cryptfs_scrypt(
342 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
343 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000344 if (rc) {
345 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800346 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000347 ftr->keymaster_blob_size = 0;
348 }
349 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700350 return -1;
351 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000352 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700353}
354
Shawn Willdene17a9c42014-09-08 13:04:08 -0600355/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700356static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
357 const size_t object_size, unsigned char** signature,
358 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600359 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600360 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600361 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600362
Shawn Willdene17a9c42014-09-08 13:04:08 -0600363 // To sign a message with RSA, the message must satisfy two
364 // constraints:
365 //
366 // 1. The message, when interpreted as a big-endian numeric value, must
367 // be strictly less than the public modulus of the RSA key. Note
368 // that because the most significant bit of the public modulus is
369 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
370 // key), an n-bit message with most significant bit 0 always
371 // satisfies this requirement.
372 //
373 // 2. The message must have the same length in bits as the public
374 // modulus of the RSA key. This requirement isn't mathematically
375 // necessary, but is necessary to ensure consistency in
376 // implementations.
377 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600378 case KDF_SCRYPT_KEYMASTER:
379 // This ensures the most significant byte of the signed message
380 // is zero. We could have zero-padded to the left instead, but
381 // this approach is slightly more robust against changes in
382 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600383 // so) because we really should be using a proper deterministic
384 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800385 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600386 SLOGI("Signing safely-padded object");
387 break;
388 default:
389 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000390 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600391 }
Paul Crowley73473332017-11-21 15:43:51 -0800392 for (;;) {
393 auto result = keymaster_sign_object_for_cryptfs_scrypt(
394 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
395 to_sign_size, signature, signature_size);
396 switch (result) {
397 case KeymasterSignResult::ok:
398 return 0;
399 case KeymasterSignResult::upgrade:
400 break;
401 default:
402 return -1;
403 }
404 SLOGD("Upgrading key");
405 if (keymaster_upgrade_key_for_cryptfs_scrypt(
406 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
407 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
408 &ftr->keymaster_blob_size) != 0) {
409 SLOGE("Failed to upgrade key");
410 return -1;
411 }
412 if (put_crypt_ftr_and_key(ftr) != 0) {
413 SLOGE("Failed to write upgraded key to disk");
414 }
415 SLOGD("Key upgraded successfully");
416 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600417}
418
Paul Lawrence399317e2014-03-10 13:20:50 -0700419/* Store password when userdata is successfully decrypted and mounted.
420 * Cleared by cryptfs_clear_password
421 *
422 * To avoid a double prompt at boot, we need to store the CryptKeeper
423 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
424 * Since the entire framework is torn down and rebuilt after encryption,
425 * we have to use a daemon or similar to store the password. Since vold
426 * is secured against IPC except from system processes, it seems a reasonable
427 * place to store this.
428 *
429 * password should be cleared once it has been used.
430 *
431 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800432 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700433static char* password = 0;
434static int password_expiry_time = 0;
435static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800436
Paul Crowley14c8c072018-09-18 13:30:21 -0700437enum class RebootType { reboot, recovery, shutdown };
438static void cryptfs_reboot(RebootType rt) {
439 switch (rt) {
440 case RebootType::reboot:
441 property_set(ANDROID_RB_PROPERTY, "reboot");
442 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800443
Paul Crowley14c8c072018-09-18 13:30:21 -0700444 case RebootType::recovery:
445 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
446 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800447
Paul Crowley14c8c072018-09-18 13:30:21 -0700448 case RebootType::shutdown:
449 property_set(ANDROID_RB_PROPERTY, "shutdown");
450 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700451 }
Paul Lawrence87999172014-02-20 12:21:31 -0800452
Ken Sumralladfba362013-06-04 16:37:52 -0700453 sleep(20);
454
455 /* Shouldn't get here, reboot should happen before sleep times out */
456 return;
457}
458
Kenny Rootc4c70f12013-06-14 12:11:38 -0700459/**
460 * Gets the default device scrypt parameters for key derivation time tuning.
461 * The parameters should lead to about one second derivation time for the
462 * given device.
463 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700464static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700465 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000466 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700467
Paul Crowley63c18d32016-02-10 14:02:47 +0000468 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
469 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
470 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
471 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700472 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000473 ftr->N_factor = Nf;
474 ftr->r_factor = rf;
475 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700476}
477
Tom Cherry4c5bde22019-01-29 14:34:01 -0800478static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800479 int fd, block_size;
480 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200481 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800482
Paul Crowley14c8c072018-09-18 13:30:21 -0700483 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800484 SLOGE("Cannot open device to get filesystem size ");
485 return 0;
486 }
487
488 if (lseek64(fd, 1024, SEEK_SET) < 0) {
489 SLOGE("Cannot seek to superblock");
490 return 0;
491 }
492
493 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
494 SLOGE("Cannot read superblock");
495 return 0;
496 }
497
498 close(fd);
499
Daniel Rosenberge82df162014-08-15 22:19:23 +0000500 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
501 SLOGE("Not a valid ext4 superblock");
502 return 0;
503 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800504 block_size = 1024 << sb.s_log_block_size;
505 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200506 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800507
508 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200509 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800510}
511
Tom Cherry4c5bde22019-01-29 14:34:01 -0800512static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
513 for (const auto& entry : fstab_default) {
514 if (!entry.fs_mgr_flags.vold_managed &&
515 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
516 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
517 if (key_loc != nullptr) {
518 *key_loc = entry.key_loc;
519 }
520 if (real_blk_device != nullptr) {
521 *real_blk_device = entry.blk_device;
522 }
523 return;
524 }
525 }
526}
527
Paul Crowley14c8c072018-09-18 13:30:21 -0700528static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
529 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200530 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700531 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700532 char key_loc[PROPERTY_VALUE_MAX];
533 char real_blkdev[PROPERTY_VALUE_MAX];
534 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700535
Paul Crowley14c8c072018-09-18 13:30:21 -0700536 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800537 std::string key_loc;
538 std::string real_blkdev;
539 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700540
Tom Cherry4c5bde22019-01-29 14:34:01 -0800541 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200542 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700543 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
544 * encryption info footer and key, and plenty of bytes to spare for future
545 * growth.
546 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800547 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200548 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700549 cached_data = 1;
550 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800551 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700552 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700553 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800554 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700555 cached_off = 0;
556 cached_data = 1;
557 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700558 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559
Paul Crowley14c8c072018-09-18 13:30:21 -0700560 if (cached_data) {
561 if (metadata_fname) {
562 *metadata_fname = cached_metadata_fname;
563 }
564 if (off) {
565 *off = cached_off;
566 }
567 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700568 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700569
Paul Crowley14c8c072018-09-18 13:30:21 -0700570 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700571}
572
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800573/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700574static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800575 SHA256_CTX c;
576 SHA256_Init(&c);
577 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
578 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
579 SHA256_Final(crypt_ftr->sha256, &c);
580}
581
Ken Sumralle8744072011-01-18 22:01:55 -0800582/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800583 * update the failed mount count but not change the key.
584 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700585static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
586 int fd;
587 unsigned int cnt;
588 /* starting_off is set to the SEEK_SET offset
589 * where the crypto structure starts
590 */
591 off64_t starting_off;
592 int rc = -1;
593 char* fname = NULL;
594 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800595
Paul Crowley14c8c072018-09-18 13:30:21 -0700596 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800597
Paul Crowley14c8c072018-09-18 13:30:21 -0700598 if (get_crypt_ftr_info(&fname, &starting_off)) {
599 SLOGE("Unable to get crypt_ftr_info\n");
600 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800601 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700602 if (fname[0] != '/') {
603 SLOGE("Unexpected value for crypto key location\n");
604 return -1;
605 }
606 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
607 SLOGE("Cannot open footer file %s for put\n", fname);
608 return -1;
609 }
Ken Sumralle8744072011-01-18 22:01:55 -0800610
Paul Crowley14c8c072018-09-18 13:30:21 -0700611 /* Seek to the start of the crypt footer */
612 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
613 SLOGE("Cannot seek to real block device footer\n");
614 goto errout;
615 }
616
617 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
618 SLOGE("Cannot write real block device footer\n");
619 goto errout;
620 }
621
622 fstat(fd, &statbuf);
623 /* If the keys are kept on a raw block device, do not try to truncate it. */
624 if (S_ISREG(statbuf.st_mode)) {
625 if (ftruncate(fd, 0x4000)) {
626 SLOGE("Cannot set footer file size\n");
627 goto errout;
628 }
629 }
630
631 /* Success! */
632 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800633
634errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700635 close(fd);
636 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800637}
638
Paul Crowley14c8c072018-09-18 13:30:21 -0700639static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800640 struct crypt_mnt_ftr copy;
641 memcpy(&copy, crypt_ftr, sizeof(copy));
642 set_ftr_sha(&copy);
643 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
644}
645
Paul Crowley14c8c072018-09-18 13:30:21 -0700646static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700647 return TEMP_FAILURE_RETRY(read(fd, buff, len));
648}
649
Paul Crowley14c8c072018-09-18 13:30:21 -0700650static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700651 return TEMP_FAILURE_RETRY(write(fd, buff, len));
652}
653
Paul Crowley14c8c072018-09-18 13:30:21 -0700654static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700655 memset(pdata, 0, len);
656 pdata->persist_magic = PERSIST_DATA_MAGIC;
657 pdata->persist_valid_entries = 0;
658}
659
660/* A routine to update the passed in crypt_ftr to the lastest version.
661 * fd is open read/write on the device that holds the crypto footer and persistent
662 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
663 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
664 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700665static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700666 int orig_major = crypt_ftr->major_version;
667 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700668
Kenny Root7434b312013-06-14 11:29:53 -0700669 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700670 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700671 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700672
Kenny Rootc4c70f12013-06-14 12:11:38 -0700673 SLOGW("upgrading crypto footer to 1.1");
674
Paul Crowley14c8c072018-09-18 13:30:21 -0700675 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700676 if (pdata == NULL) {
677 SLOGE("Cannot allocate persisent data\n");
678 return;
679 }
680 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
681
682 /* Need to initialize the persistent data area */
683 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
684 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100685 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700686 return;
687 }
688 /* Write all zeros to the first copy, making it invalid */
689 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
690
691 /* Write a valid but empty structure to the second copy */
692 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
693 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
694
695 /* Update the footer */
696 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
697 crypt_ftr->persist_data_offset[0] = pdata_offset;
698 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
699 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100700 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700701 }
702
Paul Lawrencef4faa572014-01-29 13:31:03 -0800703 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700704 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800705 /* But keep the old kdf_type.
706 * It will get updated later to KDF_SCRYPT after the password has been verified.
707 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700708 crypt_ftr->kdf_type = KDF_PBKDF2;
709 get_device_scrypt_params(crypt_ftr);
710 crypt_ftr->minor_version = 2;
711 }
712
Paul Lawrencef4faa572014-01-29 13:31:03 -0800713 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
714 SLOGW("upgrading crypto footer to 1.3");
715 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
716 crypt_ftr->minor_version = 3;
717 }
718
Kenny Root7434b312013-06-14 11:29:53 -0700719 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
720 if (lseek64(fd, offset, SEEK_SET) == -1) {
721 SLOGE("Cannot seek to crypt footer\n");
722 return;
723 }
724 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700725 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700726}
727
Paul Crowley14c8c072018-09-18 13:30:21 -0700728static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
729 int fd;
730 unsigned int cnt;
731 off64_t starting_off;
732 int rc = -1;
733 char* fname = NULL;
734 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700735
Paul Crowley14c8c072018-09-18 13:30:21 -0700736 if (get_crypt_ftr_info(&fname, &starting_off)) {
737 SLOGE("Unable to get crypt_ftr_info\n");
738 return -1;
739 }
740 if (fname[0] != '/') {
741 SLOGE("Unexpected value for crypto key location\n");
742 return -1;
743 }
744 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
745 SLOGE("Cannot open footer file %s for get\n", fname);
746 return -1;
747 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800748
Paul Crowley14c8c072018-09-18 13:30:21 -0700749 /* Make sure it's 16 Kbytes in length */
750 fstat(fd, &statbuf);
751 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
752 SLOGE("footer file %s is not the expected size!\n", fname);
753 goto errout;
754 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700755
Paul Crowley14c8c072018-09-18 13:30:21 -0700756 /* Seek to the start of the crypt footer */
757 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
758 SLOGE("Cannot seek to real block device footer\n");
759 goto errout;
760 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761
Paul Crowley14c8c072018-09-18 13:30:21 -0700762 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
763 SLOGE("Cannot read real block device footer\n");
764 goto errout;
765 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800766
Paul Crowley14c8c072018-09-18 13:30:21 -0700767 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
768 SLOGE("Bad magic for real block device %s\n", fname);
769 goto errout;
770 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800771
Paul Crowley14c8c072018-09-18 13:30:21 -0700772 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
773 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
774 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
775 goto errout;
776 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800777
Paul Crowley14c8c072018-09-18 13:30:21 -0700778 // We risk buffer overflows with oversized keys, so we just reject them.
779 // 0-sized keys are problematic (essentially by-passing encryption), and
780 // AES-CBC key wrapping only works for multiples of 16 bytes.
781 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
782 (crypt_ftr->keysize > MAX_KEY_LEN)) {
783 SLOGE(
784 "Invalid keysize (%u) for block device %s; Must be non-zero, "
785 "divisible by 16, and <= %d\n",
786 crypt_ftr->keysize, fname, MAX_KEY_LEN);
787 goto errout;
788 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800789
Paul Crowley14c8c072018-09-18 13:30:21 -0700790 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
791 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
792 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
793 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800794
Paul Crowley14c8c072018-09-18 13:30:21 -0700795 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
796 * copy on disk before returning.
797 */
798 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
799 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
800 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800801
Paul Crowley14c8c072018-09-18 13:30:21 -0700802 /* Success! */
803 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800804
805errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700806 close(fd);
807 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800808}
809
Paul Crowley14c8c072018-09-18 13:30:21 -0700810static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700811 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
812 crypt_ftr->persist_data_offset[1]) {
813 SLOGE("Crypt_ftr persist data regions overlap");
814 return -1;
815 }
816
817 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
818 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
819 return -1;
820 }
821
822 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700823 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700824 CRYPT_FOOTER_OFFSET) {
825 SLOGE("Persistent data extends past crypto footer");
826 return -1;
827 }
828
829 return 0;
830}
831
Paul Crowley14c8c072018-09-18 13:30:21 -0700832static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700833 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700834 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700836 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700837 int found = 0;
838 int fd;
839 int ret;
840 int i;
841
842 if (persist_data) {
843 /* Nothing to do, we've already loaded or initialized it */
844 return 0;
845 }
846
Ken Sumrall160b4d62013-04-22 12:15:39 -0700847 /* If not encrypted, just allocate an empty table and initialize it */
848 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700849 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800850 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700851 if (pdata) {
852 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
853 persist_data = pdata;
854 return 0;
855 }
856 return -1;
857 }
858
Paul Crowley14c8c072018-09-18 13:30:21 -0700859 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700860 return -1;
861 }
862
Paul Crowley14c8c072018-09-18 13:30:21 -0700863 if ((crypt_ftr.major_version < 1) ||
864 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700865 SLOGE("Crypt_ftr version doesn't support persistent data");
866 return -1;
867 }
868
869 if (get_crypt_ftr_info(&fname, NULL)) {
870 return -1;
871 }
872
873 ret = validate_persistent_data_storage(&crypt_ftr);
874 if (ret) {
875 return -1;
876 }
877
Paul Crowley14c8c072018-09-18 13:30:21 -0700878 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700879 if (fd < 0) {
880 SLOGE("Cannot open %s metadata file", fname);
881 return -1;
882 }
883
Wei Wang4375f1b2017-02-24 17:43:01 -0800884 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800885 if (pdata == NULL) {
886 SLOGE("Cannot allocate memory for persistent data");
887 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700888 }
889
890 for (i = 0; i < 2; i++) {
891 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
892 SLOGE("Cannot seek to read persistent data on %s", fname);
893 goto err2;
894 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700895 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700896 SLOGE("Error reading persistent data on iteration %d", i);
897 goto err2;
898 }
899 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
900 found = 1;
901 break;
902 }
903 }
904
905 if (!found) {
906 SLOGI("Could not find valid persistent data, creating");
907 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
908 }
909
910 /* Success */
911 persist_data = pdata;
912 close(fd);
913 return 0;
914
915err2:
916 free(pdata);
917
918err:
919 close(fd);
920 return -1;
921}
922
Paul Crowley14c8c072018-09-18 13:30:21 -0700923static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700924 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700925 struct crypt_persist_data* pdata;
926 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700927 off64_t write_offset;
928 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700929 int fd;
930 int ret;
931
932 if (persist_data == NULL) {
933 SLOGE("No persistent data to save");
934 return -1;
935 }
936
Paul Crowley14c8c072018-09-18 13:30:21 -0700937 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700938 return -1;
939 }
940
Paul Crowley14c8c072018-09-18 13:30:21 -0700941 if ((crypt_ftr.major_version < 1) ||
942 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700943 SLOGE("Crypt_ftr version doesn't support persistent data");
944 return -1;
945 }
946
947 ret = validate_persistent_data_storage(&crypt_ftr);
948 if (ret) {
949 return -1;
950 }
951
952 if (get_crypt_ftr_info(&fname, NULL)) {
953 return -1;
954 }
955
Paul Crowley14c8c072018-09-18 13:30:21 -0700956 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700957 if (fd < 0) {
958 SLOGE("Cannot open %s metadata file", fname);
959 return -1;
960 }
961
Wei Wang4375f1b2017-02-24 17:43:01 -0800962 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700963 if (pdata == NULL) {
964 SLOGE("Cannot allocate persistant data");
965 goto err;
966 }
967
968 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
969 SLOGE("Cannot seek to read persistent data on %s", fname);
970 goto err2;
971 }
972
973 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700974 SLOGE("Error reading persistent data before save");
975 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700976 }
977
978 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
979 /* The first copy is the curent valid copy, so write to
980 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -0700981 write_offset = crypt_ftr.persist_data_offset[1];
982 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700983 } else {
984 /* The second copy must be the valid copy, so write to
985 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -0700986 write_offset = crypt_ftr.persist_data_offset[0];
987 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700988 }
989
990 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100991 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700992 SLOGE("Cannot seek to write persistent data");
993 goto err2;
994 }
995 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -0700996 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100997 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700998 SLOGE("Cannot seek to erase previous persistent data");
999 goto err2;
1000 }
1001 fsync(fd);
1002 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001003 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001004 SLOGE("Cannot write to erase previous persistent data");
1005 goto err2;
1006 }
1007 fsync(fd);
1008 } else {
1009 SLOGE("Cannot write to save persistent data");
1010 goto err2;
1011 }
1012
1013 /* Success */
1014 free(pdata);
1015 close(fd);
1016 return 0;
1017
1018err2:
1019 free(pdata);
1020err:
1021 close(fd);
1022 return -1;
1023}
1024
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001025/* Convert a binary key of specified length into an ascii hex string equivalent,
1026 * without the leading 0x and with null termination
1027 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001028static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1029 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001030 unsigned int i, a;
1031 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001032
Paul Crowley14c8c072018-09-18 13:30:21 -07001033 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001034 /* For each byte, write out two ascii hex digits */
1035 nibble = (master_key[i] >> 4) & 0xf;
1036 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001037
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001038 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001039 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001040 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001041
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001042 /* Add the null termination */
1043 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001044}
1045
Eric Biggersed45ec32019-01-25 10:47:55 -08001046/*
1047 * If the ro.crypto.fde_sector_size system property is set, append the
1048 * parameters to make dm-crypt use the specified crypto sector size and round
1049 * the crypto device size down to a crypto sector boundary.
1050 */
David Andersonb9224732019-05-13 13:02:54 -07001051static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001052 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001053 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001054
Eric Biggersed45ec32019-01-25 10:47:55 -08001055 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1056 unsigned int sector_size;
1057
1058 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1059 (sector_size & (sector_size - 1)) != 0) {
1060 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1061 DM_CRYPT_SECTOR_SIZE, value);
1062 return -1;
1063 }
1064
David Andersonb9224732019-05-13 13:02:54 -07001065 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001066
1067 // With this option, IVs will match the sector numbering, instead
1068 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001069 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001070
1071 // Round the crypto device size down to a crypto sector boundary.
1072 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001073 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001074 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001075}
1076
Paul Crowley5afbc622017-11-27 09:42:17 -08001077static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001078 const char* real_blk_name, std::string* crypto_blk_name,
1079 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001080 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001081
David Andersonb9224732019-05-13 13:02:54 -07001082 // We need two ASCII characters to represent each byte, and need space for
1083 // the '\0' terminator.
1084 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1085 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001086
David Andersonb9224732019-05-13 13:02:54 -07001087 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1088 (const char*)crypt_ftr->crypto_type_name,
1089 master_key_ascii, 0, real_blk_name, 0);
1090 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001091
Paul Crowley5afbc622017-11-27 09:42:17 -08001092 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001093 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001094 }
David Andersonb9224732019-05-13 13:02:54 -07001095 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001096 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001097 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001098 }
David Andersonb9224732019-05-13 13:02:54 -07001099
1100 DmTable table;
1101 table.AddTarget(std::move(target));
1102
1103 int load_count = 1;
1104 while (load_count < TABLE_LOAD_RETRIES) {
1105 if (dm.CreateDevice(name, table)) {
1106 break;
1107 }
1108 load_count++;
1109 }
1110
1111 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001112 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001113 return -1;
1114 }
1115 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001116 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1117 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118
Paul Crowley81796e92020-02-07 11:27:49 -08001119 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001120 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1121 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001122 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001123
Paul Crowleycfe39722018-10-30 15:59:24 -07001124 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001125 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001126 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001127 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001128 }
David Andersonb9224732019-05-13 13:02:54 -07001129 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130}
1131
David Andersonb9224732019-05-13 13:02:54 -07001132static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001133 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001134 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001135 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1136 // to delete the device fails with EBUSY; for now, work around this by retrying.
1137 int tries = 5;
1138 while (tries-- > 0) {
1139 ret = dm.DeleteDevice(name);
1140 if (ret || errno != EBUSY) {
1141 break;
1142 }
1143 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1144 strerror(errno));
1145 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1146 }
1147 if (!ret) {
1148 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001149 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001150 }
David Andersonb9224732019-05-13 13:02:54 -07001151 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001152}
1153
Paul Crowley14c8c072018-09-18 13:30:21 -07001154static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1155 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001156 SLOGI("Using pbkdf2 for cryptfs KDF");
1157
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001159 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1160 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001161}
1162
Paul Crowley14c8c072018-09-18 13:30:21 -07001163static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001164 SLOGI("Using scrypt for cryptfs KDF");
1165
Paul Crowley14c8c072018-09-18 13:30:21 -07001166 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001167
1168 int N = 1 << ftr->N_factor;
1169 int r = 1 << ftr->r_factor;
1170 int p = 1 << ftr->p_factor;
1171
1172 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001173 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001174 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001175
Paul Crowley14c8c072018-09-18 13:30:21 -07001176 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001177}
1178
Paul Crowley14c8c072018-09-18 13:30:21 -07001179static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1180 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001181 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1182
1183 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001184 size_t signature_size;
1185 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001186 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001187
1188 int N = 1 << ftr->N_factor;
1189 int r = 1 << ftr->r_factor;
1190 int p = 1 << ftr->p_factor;
1191
Paul Crowley14c8c072018-09-18 13:30:21 -07001192 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001193 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001194
1195 if (rc) {
1196 SLOGE("scrypt failed");
1197 return -1;
1198 }
1199
Paul Crowley14c8c072018-09-18 13:30:21 -07001200 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001201 SLOGE("Signing failed");
1202 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001203 }
1204
Paul Crowley14c8c072018-09-18 13:30:21 -07001205 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1206 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001207 free(signature);
1208
1209 if (rc) {
1210 SLOGE("scrypt failed");
1211 return -1;
1212 }
1213
1214 return 0;
1215}
1216
Paul Crowley14c8c072018-09-18 13:30:21 -07001217static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1218 const unsigned char* decrypted_master_key,
1219 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1220 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001221 EVP_CIPHER_CTX e_ctx;
1222 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001223 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001224
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001225 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001226 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001227
1228 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001229 case KDF_SCRYPT_KEYMASTER:
1230 if (keymaster_create_key(crypt_ftr)) {
1231 SLOGE("keymaster_create_key failed");
1232 return -1;
1233 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001234
Paul Crowley14c8c072018-09-18 13:30:21 -07001235 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1236 SLOGE("scrypt failed");
1237 return -1;
1238 }
1239 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001240
Paul Crowley14c8c072018-09-18 13:30:21 -07001241 case KDF_SCRYPT:
1242 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1243 SLOGE("scrypt failed");
1244 return -1;
1245 }
1246 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001247
Paul Crowley14c8c072018-09-18 13:30:21 -07001248 default:
1249 SLOGE("Invalid kdf_type");
1250 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001251 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001252
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001253 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001254 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001255 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1256 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001257 SLOGE("EVP_EncryptInit failed\n");
1258 return -1;
1259 }
1260 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001261
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001262 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001263 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1264 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001265 SLOGE("EVP_EncryptUpdate failed\n");
1266 return -1;
1267 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001268 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001269 SLOGE("EVP_EncryptFinal failed\n");
1270 return -1;
1271 }
1272
Greg Kaiser59ad0182018-02-16 13:01:36 -08001273 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001274 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1275 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001276 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001277
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001278 /* Store the scrypt of the intermediate key, so we can validate if it's a
1279 password error or mount error when things go wrong.
1280 Note there's no need to check for errors, since if this is incorrect, we
1281 simply won't wipe userdata, which is the correct default behavior
1282 */
1283 int N = 1 << crypt_ftr->N_factor;
1284 int r = 1 << crypt_ftr->r_factor;
1285 int p = 1 << crypt_ftr->p_factor;
1286
Paul Crowley14c8c072018-09-18 13:30:21 -07001287 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1288 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001289 sizeof(crypt_ftr->scrypted_intermediate_key));
1290
1291 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001292 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001293 }
1294
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001295 EVP_CIPHER_CTX_cleanup(&e_ctx);
1296
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001297 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001298}
1299
Paul Crowley14c8c072018-09-18 13:30:21 -07001300static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1301 const unsigned char* encrypted_master_key, size_t keysize,
1302 unsigned char* decrypted_master_key, kdf_func kdf,
1303 void* kdf_params, unsigned char** intermediate_key,
1304 size_t* intermediate_key_size) {
1305 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1306 EVP_CIPHER_CTX d_ctx;
1307 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001308
Paul Crowley14c8c072018-09-18 13:30:21 -07001309 /* Turn the password into an intermediate key and IV that can decrypt the
1310 master key */
1311 if (kdf(passwd, salt, ikey, kdf_params)) {
1312 SLOGE("kdf failed");
1313 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001314 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001315
Paul Crowley14c8c072018-09-18 13:30:21 -07001316 /* Initialize the decryption engine */
1317 EVP_CIPHER_CTX_init(&d_ctx);
1318 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1319 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1320 return -1;
1321 }
1322 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1323 /* Decrypt the master key */
1324 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1325 keysize)) {
1326 return -1;
1327 }
1328 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1329 return -1;
1330 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001331
Paul Crowley14c8c072018-09-18 13:30:21 -07001332 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1333 return -1;
1334 }
1335
1336 /* Copy intermediate key if needed by params */
1337 if (intermediate_key && intermediate_key_size) {
1338 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1339 if (*intermediate_key) {
1340 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1341 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1342 }
1343 }
1344
1345 EVP_CIPHER_CTX_cleanup(&d_ctx);
1346
1347 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001348}
1349
Paul Crowley14c8c072018-09-18 13:30:21 -07001350static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001351 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001352 *kdf = scrypt_keymaster;
1353 *kdf_params = ftr;
1354 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001355 *kdf = scrypt;
1356 *kdf_params = ftr;
1357 } else {
1358 *kdf = pbkdf2;
1359 *kdf_params = NULL;
1360 }
1361}
1362
Paul Crowley14c8c072018-09-18 13:30:21 -07001363static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1364 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1365 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001366 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001367 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001368 int ret;
1369
1370 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001371 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1372 decrypted_master_key, kdf, kdf_params, intermediate_key,
1373 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001374 if (ret != 0) {
1375 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001376 }
1377
1378 return ret;
1379}
1380
Paul Crowley14c8c072018-09-18 13:30:21 -07001381static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1382 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001383 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001384
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001385 /* Get some random bits for a key and salt */
1386 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1387 return -1;
1388 }
1389 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1390 return -1;
1391 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001392
1393 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001394 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001395}
1396
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001397static void ensure_subdirectory_unmounted(const char *prefix) {
1398 std::vector<std::string> umount_points;
1399 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
1400 if (!mnts) {
1401 SLOGW("could not read mount files");
1402 return;
1403 }
1404
1405 //Find sudirectory mount point
1406 mntent* mentry;
1407 std::string top_directory(prefix);
1408 if (!android::base::EndsWith(prefix, "/")) {
1409 top_directory = top_directory + "/";
1410 }
1411 while ((mentry = getmntent(mnts.get())) != nullptr) {
1412 if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
1413 continue;
1414 }
1415
1416 if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
1417 SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
1418 umount_points.push_back(mentry->mnt_dir);
1419 }
1420 }
1421
1422 //Sort by path length to umount longest path first
1423 std::sort(std::begin(umount_points), std::end(umount_points),
1424 [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
1425
1426 for (std::string& mount_point : umount_points) {
1427 umount(mount_point.c_str());
1428 SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
1429 }
1430}
1431
Paul Crowley73be12d2020-02-03 12:22:03 -08001432static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001433 int i, err, rc;
Hyangseok Chae3cf32332020-02-27 18:21:50 +09001434
1435 // Subdirectory mount will cause a failure of umount.
1436 ensure_subdirectory_unmounted(mountpoint);
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001437#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001438
1439 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001440 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001441 if (umount(mountpoint) == 0) {
1442 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001443 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001444
1445 if (errno == EINVAL) {
1446 /* EINVAL is returned if the directory is not a mountpoint,
1447 * i.e. there is no filesystem mounted there. So just get out.
1448 */
1449 break;
1450 }
1451
1452 err = errno;
1453
1454 /* If allowed, be increasingly aggressive before the last two retries */
1455 if (kill) {
1456 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1457 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001458 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001459 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1460 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001461 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001462 }
1463 }
1464
1465 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001466 }
1467
1468 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001469 SLOGD("unmounting %s succeeded\n", mountpoint);
1470 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001471 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001472 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1473 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1474 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001475 }
1476
1477 return rc;
1478}
1479
Paul Crowley14c8c072018-09-18 13:30:21 -07001480static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001481 // NOTE: post_fs_data results in init calling back around to vold, so all
1482 // callers to this method must be async
1483
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001484 /* Do the prep of the /data filesystem */
1485 property_set("vold.post_fs_data_done", "0");
1486 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001487 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001488
Ken Sumrallc5872692013-05-14 15:26:31 -07001489 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001490 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001491 /* We timed out to prep /data in time. Continue wait. */
1492 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001493 }
Wei Wang42e38102017-06-07 10:46:12 -07001494 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001495}
1496
Paul Crowley14c8c072018-09-18 13:30:21 -07001497static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001498 // Mark the footer as bad
1499 struct crypt_mnt_ftr crypt_ftr;
1500 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1501 SLOGE("Failed to get crypto footer - panic");
1502 return;
1503 }
1504
1505 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1506 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1507 SLOGE("Failed to set crypto footer - panic");
1508 return;
1509 }
1510}
1511
Paul Crowley14c8c072018-09-18 13:30:21 -07001512static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001513 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001514 SLOGE("Failed to mount tmpfs on data - panic");
1515 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001516 }
1517
1518 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1519 SLOGE("Failed to trigger post fs data - panic");
1520 return;
1521 }
1522
1523 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1524 SLOGE("Failed to trigger restart min framework - panic");
1525 return;
1526 }
1527}
1528
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001529/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001530static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001531 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001532 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001533 static int restart_successful = 0;
1534
1535 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001536 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001537 SLOGE("Encrypted filesystem not validated, aborting");
1538 return -1;
1539 }
1540
1541 if (restart_successful) {
1542 SLOGE("System already restarted with encrypted disk, aborting");
1543 return -1;
1544 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001545
Paul Lawrencef4faa572014-01-29 13:31:03 -08001546 if (restart_main) {
1547 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001548 * start all services in one of these classes: core, early_hal, hal,
1549 * main and late_start. To get to the minimal UI for PIN entry, we
1550 * need to start core, early_hal, hal and main. When we want to
1551 * shutdown the framework again, we need to stop most of the services in
1552 * these classes, but only those services that were started after
1553 * /data was mounted. This excludes critical services like vold and
1554 * ueventd, which need to keep running. We could possible stop
1555 * even fewer services, but because we want services to pick up APEX
1556 * libraries from the real /data, restarting is better, as it makes
1557 * these devices consistent with FBE devices and lets them use the
1558 * most recent code.
1559 *
1560 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001561 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001562 * We then restart the class core, hal, main, and also the class
1563 * late_start.
1564 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001565 * At the moment, I've only put a few things in late_start that I know
1566 * are not needed to bring up the framework, and that also cause problems
1567 * with unmounting the tmpfs /data, but I hope to add add more services
1568 * to the late_start class as we optimize this to decrease the delay
1569 * till the user is asked for the password to the filesystem.
1570 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001572 /* The init files are setup to stop the right set of services when
1573 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001574 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001575 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001576 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001577
Paul Lawrencef4faa572014-01-29 13:31:03 -08001578 /* Ugh, shutting down the framework is not synchronous, so until it
1579 * can be fixed, this horrible hack will wait a moment for it all to
1580 * shut down before proceeding. Without it, some devices cannot
1581 * restart the graphics services.
1582 */
1583 sleep(2);
1584 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001585
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001586 /* Now that the framework is shutdown, we should be able to umount()
1587 * the tmpfs filesystem, and mount the real one.
1588 */
1589
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001590 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1591 if (strlen(crypto_blkdev) == 0) {
1592 SLOGE("fs_crypto_blkdev not set\n");
1593 return -1;
1594 }
1595
Paul Crowley14c8c072018-09-18 13:30:21 -07001596 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001597 /* If ro.crypto.readonly is set to 1, mount the decrypted
1598 * filesystem readonly. This is used when /data is mounted by
1599 * recovery mode.
1600 */
1601 char ro_prop[PROPERTY_VALUE_MAX];
1602 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001603 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001604 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1605 if (entry != nullptr) {
1606 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001607 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001608 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001609
Ken Sumralle5032c42012-04-01 23:58:44 -07001610 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001611 int retries = RETRY_MOUNT_ATTEMPTS;
1612 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001613
1614 /*
1615 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1616 * partitions in the fsck domain.
1617 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001618 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001619 SLOGE("Failed to setexeccon");
1620 return -1;
1621 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001622 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001623 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Paul Lawrence3fe93112020-06-12 08:12:48 -07001624 needs_cp, false)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001625 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1626 /* TODO: invoke something similar to
1627 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1628 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001629 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001630 if (--retries) {
1631 sleep(RETRY_MOUNT_DELAY_SECONDS);
1632 } else {
1633 /* Let's hope that a reboot clears away whatever is keeping
1634 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001635 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001636 }
1637 } else {
1638 SLOGE("Failed to mount decrypted data");
1639 cryptfs_set_corrupt();
1640 cryptfs_trigger_restart_min_framework();
1641 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001642 if (setexeccon(NULL)) {
1643 SLOGE("Failed to setexeccon");
1644 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001645 return -1;
1646 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001647 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001648 if (setexeccon(NULL)) {
1649 SLOGE("Failed to setexeccon");
1650 return -1;
1651 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001652
Ken Sumralle5032c42012-04-01 23:58:44 -07001653 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001654 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001655 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001656
1657 /* startup service classes main and late_start */
1658 property_set("vold.decrypt", "trigger_restart_framework");
1659 SLOGD("Just triggered restart_framework\n");
1660
1661 /* Give it a few moments to get started */
1662 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001663 }
1664
Ken Sumrall0cc16632011-01-18 20:32:26 -08001665 if (rc == 0) {
1666 restart_successful = 1;
1667 }
1668
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001669 return rc;
1670}
1671
Paul Crowley14c8c072018-09-18 13:30:21 -07001672int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001673 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001674 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001675 SLOGE("cryptfs_restart not valid for file encryption:");
1676 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001677 }
1678
Paul Lawrencef4faa572014-01-29 13:31:03 -08001679 /* Call internal implementation forcing a restart of main service group */
1680 return cryptfs_restart_internal(1);
1681}
1682
Paul Crowley14c8c072018-09-18 13:30:21 -07001683static int do_crypto_complete(const char* mount_point) {
1684 struct crypt_mnt_ftr crypt_ftr;
1685 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001686
Paul Crowley14c8c072018-09-18 13:30:21 -07001687 property_get("ro.crypto.state", encrypted_state, "");
1688 if (strcmp(encrypted_state, "encrypted")) {
1689 SLOGE("not running with encryption, aborting");
1690 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001691 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001692
Paul Crowley14c8c072018-09-18 13:30:21 -07001693 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001694 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001695 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1696 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001697
Paul Crowley14c8c072018-09-18 13:30:21 -07001698 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001699 std::string key_loc;
1700 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001701
Paul Crowley14c8c072018-09-18 13:30:21 -07001702 /*
1703 * Only report this error if key_loc is a file and it exists.
1704 * If the device was never encrypted, and /data is not mountable for
1705 * some reason, returning 1 should prevent the UI from presenting the
1706 * a "enter password" screen, or worse, a "press button to wipe the
1707 * device" screen.
1708 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001709 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001710 SLOGE("master key file does not exist, aborting");
1711 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1712 } else {
1713 SLOGE("Error getting crypt footer and key\n");
1714 return CRYPTO_COMPLETE_BAD_METADATA;
1715 }
1716 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001717
Paul Crowley14c8c072018-09-18 13:30:21 -07001718 // Test for possible error flags
1719 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1720 SLOGE("Encryption process is partway completed\n");
1721 return CRYPTO_COMPLETE_PARTIAL;
1722 }
1723
1724 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1725 SLOGE("Encryption process was interrupted but cannot continue\n");
1726 return CRYPTO_COMPLETE_INCONSISTENT;
1727 }
1728
1729 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1730 SLOGE("Encryption is successful but data is corrupt\n");
1731 return CRYPTO_COMPLETE_CORRUPT;
1732 }
1733
1734 /* We passed the test! We shall diminish, and return to the west */
1735 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001736}
1737
Paul Crowley14c8c072018-09-18 13:30:21 -07001738static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1739 const char* mount_point, const char* label) {
1740 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001741 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001742 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001743 char tmp_mount_point[64];
1744 unsigned int orig_failed_decrypt_count;
1745 int rc;
1746 int use_keymaster = 0;
1747 int upgrade = 0;
1748 unsigned char* intermediate_key = 0;
1749 size_t intermediate_key_size = 0;
1750 int N = 1 << crypt_ftr->N_factor;
1751 int r = 1 << crypt_ftr->r_factor;
1752 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001753
Paul Crowley14c8c072018-09-18 13:30:21 -07001754 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1755 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001756
Paul Crowley14c8c072018-09-18 13:30:21 -07001757 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1758 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1759 &intermediate_key_size)) {
1760 SLOGE("Failed to decrypt master key\n");
1761 rc = -1;
1762 goto errout;
1763 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001764 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001765
Tom Cherry4c5bde22019-01-29 14:34:01 -08001766 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001767
Paul Crowley14c8c072018-09-18 13:30:21 -07001768 // Create crypto block device - all (non fatal) code paths
1769 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001770 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001771 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001772 SLOGE("Error creating decrypted block device\n");
1773 rc = -1;
1774 goto errout;
1775 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001776
Paul Crowley14c8c072018-09-18 13:30:21 -07001777 /* Work out if the problem is the password or the data */
1778 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001779
Paul Crowley14c8c072018-09-18 13:30:21 -07001780 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1781 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1782 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001783
Paul Crowley14c8c072018-09-18 13:30:21 -07001784 // Does the key match the crypto footer?
1785 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1786 sizeof(scrypted_intermediate_key)) == 0) {
1787 SLOGI("Password matches");
1788 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001789 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001790 /* Try mounting the file system anyway, just in case the problem's with
1791 * the footer, not the key. */
1792 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1793 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001794 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1795 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001796 SLOGE("Error temp mounting decrypted block device\n");
1797 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001798
Paul Crowley14c8c072018-09-18 13:30:21 -07001799 rc = ++crypt_ftr->failed_decrypt_count;
1800 put_crypt_ftr_and_key(crypt_ftr);
1801 } else {
1802 /* Success! */
1803 SLOGI("Password did not match but decrypted drive mounted - continue");
1804 umount(tmp_mount_point);
1805 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001806 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001807 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001808
Paul Crowley14c8c072018-09-18 13:30:21 -07001809 if (rc == 0) {
1810 crypt_ftr->failed_decrypt_count = 0;
1811 if (orig_failed_decrypt_count != 0) {
1812 put_crypt_ftr_and_key(crypt_ftr);
1813 }
1814
1815 /* Save the name of the crypto block device
1816 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001817 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001818
1819 /* Also save a the master key so we can reencrypted the key
1820 * the key when we want to change the password on it. */
1821 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1822 saved_mount_point = strdup(mount_point);
1823 master_key_saved = 1;
1824 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1825 rc = 0;
1826
1827 // Upgrade if we're not using the latest KDF.
1828 use_keymaster = keymaster_check_compatibility();
1829 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1830 // Don't allow downgrade
1831 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1832 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1833 upgrade = 1;
1834 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1835 crypt_ftr->kdf_type = KDF_SCRYPT;
1836 upgrade = 1;
1837 }
1838
1839 if (upgrade) {
1840 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1841 crypt_ftr->master_key, crypt_ftr);
1842 if (!rc) {
1843 rc = put_crypt_ftr_and_key(crypt_ftr);
1844 }
1845 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1846
1847 // Do not fail even if upgrade failed - machine is bootable
1848 // Note that if this code is ever hit, there is a *serious* problem
1849 // since KDFs should never fail. You *must* fix the kdf before
1850 // proceeding!
1851 if (rc) {
1852 SLOGW(
1853 "Upgrade failed with error %d,"
1854 " but continuing with previous state",
1855 rc);
1856 rc = 0;
1857 }
1858 }
1859 }
1860
1861errout:
1862 if (intermediate_key) {
1863 memset(intermediate_key, 0, intermediate_key_size);
1864 free(intermediate_key);
1865 }
1866 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001867}
1868
Ken Sumrall29d8da82011-05-18 17:20:07 -07001869/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001870 * Called by vold when it's asked to mount an encrypted external
1871 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001872 * as any metadata is been stored in a separate, small partition. We
1873 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001874 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001875int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001876 std::string* out_crypto_blkdev) {
Paul Crowley220567c2020-02-07 12:45:20 -08001877 auto crypto_type = get_crypto_type();
1878 if (key.size() != crypto_type.get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001879 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley220567c2020-02-07 12:45:20 -08001880 crypto_type.get_keysize());
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001881 return -1;
1882 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001883 uint64_t nr_sec = 0;
1884 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001885 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001886 return -1;
1887 }
1888
Jeff Sharkey9c484982015-03-31 10:35:33 -07001889 struct crypt_mnt_ftr ext_crypt_ftr;
1890 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1891 ext_crypt_ftr.fs_size = nr_sec;
Paul Crowley220567c2020-02-07 12:45:20 -08001892 ext_crypt_ftr.keysize = crypto_type.get_keysize();
1893 strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001894 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001895 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001896 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001897 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1898 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001899
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001900 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1901 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001902}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001903
Paul Crowley14c8c072018-09-18 13:30:21 -07001904int cryptfs_crypto_complete(void) {
1905 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001906}
1907
Paul Crowley14c8c072018-09-18 13:30:21 -07001908int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001909 char encrypted_state[PROPERTY_VALUE_MAX];
1910 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001911 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1912 SLOGE(
1913 "encrypted fs already validated or not running with encryption,"
1914 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001915 return -1;
1916 }
1917
1918 if (get_crypt_ftr_and_key(crypt_ftr)) {
1919 SLOGE("Error getting crypt footer and key");
1920 return -1;
1921 }
1922
1923 return 0;
1924}
1925
Paul Crowley14c8c072018-09-18 13:30:21 -07001926int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001927 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001928 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001929 SLOGE("cryptfs_check_passwd not valid for file encryption");
1930 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001931 }
1932
Paul Lawrencef4faa572014-01-29 13:31:03 -08001933 struct crypt_mnt_ftr crypt_ftr;
1934 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001935
Paul Lawrencef4faa572014-01-29 13:31:03 -08001936 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001937 if (rc) {
1938 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001939 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001940 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001941
Paul Crowley14c8c072018-09-18 13:30:21 -07001942 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001943 if (rc) {
1944 SLOGE("Password did not match");
1945 return rc;
1946 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001947
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001948 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1949 // Here we have a default actual password but a real password
1950 // we must test against the scrypted value
1951 // First, we must delete the crypto block device that
1952 // test_mount_encrypted_fs leaves behind as a side effect
1953 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001954 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1955 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001956 if (rc) {
1957 SLOGE("Default password did not match on reboot encryption");
1958 return rc;
1959 }
1960
1961 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1962 put_crypt_ftr_and_key(&crypt_ftr);
1963 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1964 if (rc) {
1965 SLOGE("Could not change password on reboot encryption");
1966 return rc;
1967 }
1968 }
1969
1970 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001971 cryptfs_clear_password();
1972 password = strdup(passwd);
1973 struct timespec now;
1974 clock_gettime(CLOCK_BOOTTIME, &now);
1975 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001976 }
1977
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001978 return rc;
1979}
1980
Paul Crowley14c8c072018-09-18 13:30:21 -07001981int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001982 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001983 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001984 char encrypted_state[PROPERTY_VALUE_MAX];
1985 int rc;
1986
1987 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001988 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001989 SLOGE("device not encrypted, aborting");
1990 return -2;
1991 }
1992
1993 if (!master_key_saved) {
1994 SLOGE("encrypted fs not yet mounted, aborting");
1995 return -1;
1996 }
1997
1998 if (!saved_mount_point) {
1999 SLOGE("encrypted fs failed to save mount point, aborting");
2000 return -1;
2001 }
2002
Ken Sumrall160b4d62013-04-22 12:15:39 -07002003 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002004 SLOGE("Error getting crypt footer and key\n");
2005 return -1;
2006 }
2007
2008 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2009 /* If the device has no password, then just say the password is valid */
2010 rc = 0;
2011 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002012 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002013 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2014 /* They match, the password is correct */
2015 rc = 0;
2016 } else {
2017 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2018 sleep(1);
2019 rc = 1;
2020 }
2021 }
2022
2023 return rc;
2024}
2025
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002026/* Initialize a crypt_mnt_ftr structure. The keysize is
Paul Crowley220567c2020-02-07 12:45:20 -08002027 * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002028 * Presumably, at a minimum, the caller will update the
2029 * filesystem size and crypto_type_name after calling this function.
2030 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002031static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002032 off64_t off;
2033
2034 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002035 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002036 ftr->major_version = CURRENT_MAJOR_VERSION;
2037 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002038 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Paul Crowley220567c2020-02-07 12:45:20 -08002039 ftr->keysize = get_crypto_type().get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002040
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002041 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002042 case 1:
2043 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2044 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002045
Paul Crowley14c8c072018-09-18 13:30:21 -07002046 case 0:
2047 ftr->kdf_type = KDF_SCRYPT;
2048 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002049
Paul Crowley14c8c072018-09-18 13:30:21 -07002050 default:
2051 SLOGE("keymaster_check_compatibility failed");
2052 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002053 }
2054
Kenny Rootc4c70f12013-06-14 12:11:38 -07002055 get_device_scrypt_params(ftr);
2056
Ken Sumrall160b4d62013-04-22 12:15:39 -07002057 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2058 if (get_crypt_ftr_info(NULL, &off) == 0) {
2059 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002060 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002061 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002062
2063 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002064}
2065
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002066#define FRAMEWORK_BOOT_WAIT 60
2067
Paul Crowleyb64933a2017-10-31 08:25:55 -07002068static int vold_unmountAll(void) {
2069 VolumeManager* vm = VolumeManager::Instance();
2070 return vm->unmountAll();
2071}
2072
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002073int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002074 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002075 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002076 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002077 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002078 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002079 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002080 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002081 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002082 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002083 int num_vols;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002084 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002085 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002086 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002087
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002088 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Eric Biggersc01995e2020-11-03 14:11:00 -08002089 if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002090 if (!check_ftr_sha(&crypt_ftr)) {
2091 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2092 put_crypt_ftr_and_key(&crypt_ftr);
2093 goto error_unencrypted;
2094 }
2095
2096 /* Doing a reboot-encryption*/
2097 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2098 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2099 rebootEncryption = true;
2100 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002101 } else {
2102 // We don't want to accidentally reference invalid data.
2103 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002104 }
2105
2106 property_get("ro.crypto.state", encrypted_state, "");
Eric Biggersc01995e2020-11-03 14:11:00 -08002107 if (!strcmp(encrypted_state, "encrypted")) {
Paul Lawrence87999172014-02-20 12:21:31 -08002108 SLOGE("Device is already running encrypted, aborting");
2109 goto error_unencrypted;
2110 }
2111
Tom Cherry4c5bde22019-01-29 14:34:01 -08002112 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002113
Ken Sumrall3ed82362011-01-28 23:31:16 -08002114 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002115 uint64_t nr_sec;
2116 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002117 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002118 goto error_unencrypted;
2119 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002120
2121 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002122 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002123 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002124 fs_size_sec = get_fs_size(real_blkdev.c_str());
2125 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002126
Paul Lawrence87999172014-02-20 12:21:31 -08002127 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002128
2129 if (fs_size_sec > max_fs_size_sec) {
2130 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2131 goto error_unencrypted;
2132 }
2133 }
2134
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002135 /* Get a wakelock as this may take a while, and we don't want the
2136 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2137 * wants to keep the screen on, it can grab a full wakelock.
2138 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002139 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002140 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002141
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002142 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002143 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002144 */
2145 property_set("vold.decrypt", "trigger_shutdown_framework");
2146 SLOGD("Just asked init to shut down class main\n");
2147
Jeff Sharkey9c484982015-03-31 10:35:33 -07002148 /* Ask vold to unmount all devices that it manages */
2149 if (vold_unmountAll()) {
2150 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002151 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002152
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002153 /* no_ui means we are being called from init, not settings.
2154 Now we always reboot from settings, so !no_ui means reboot
2155 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002156 if (!no_ui) {
2157 /* Try fallback, which is to reboot and try there */
2158 onlyCreateHeader = true;
2159 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2160 if (breadcrumb == 0) {
2161 SLOGE("Failed to create breadcrumb file");
2162 goto error_shutting_down;
2163 }
2164 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002165 }
2166
2167 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002168 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002169 /* Now that /data is unmounted, we need to mount a tmpfs
2170 * /data, set a property saying we're doing inplace encryption,
2171 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002172 */
xzj7e38a3a2018-10-12 10:17:11 +08002173 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002174 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002175 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002176 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002177 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002178 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002179
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002180 /* restart the framework. */
2181 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002182 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002183
Ken Sumrall92736ef2012-10-17 20:57:14 -07002184 /* Ugh, shutting down the framework is not synchronous, so until it
2185 * can be fixed, this horrible hack will wait a moment for it all to
2186 * shut down before proceeding. Without it, some devices cannot
2187 * restart the graphics services.
2188 */
2189 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002190 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002191
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002192 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002193 /* Initialize a crypt_mnt_ftr for the partition */
Eric Biggersc01995e2020-11-03 14:11:00 -08002194 if (!rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002195 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2196 goto error_shutting_down;
2197 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002198
Tom Cherry4c5bde22019-01-29 14:34:01 -08002199 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002200 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002201 } else {
2202 crypt_ftr.fs_size = nr_sec;
2203 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002204 /* At this point, we are in an inconsistent state. Until we successfully
2205 complete encryption, a reboot will leave us broken. So mark the
2206 encryption failed in case that happens.
2207 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002208 if (onlyCreateHeader) {
2209 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2210 } else {
2211 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2212 }
Paul Lawrence87999172014-02-20 12:21:31 -08002213 crypt_ftr.crypt_type = crypt_type;
Paul Crowley220567c2020-02-07 12:45:20 -08002214 strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002215 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002216
Paul Lawrence87999172014-02-20 12:21:31 -08002217 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002218 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2219 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002220 SLOGE("Cannot create encrypted master key\n");
2221 goto error_shutting_down;
2222 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002223
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002224 /* Replace scrypted intermediate key if we are preparing for a reboot */
2225 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002226 unsigned char fake_master_key[MAX_KEY_LEN];
2227 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002228 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002229 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2230 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002231 }
2232
Paul Lawrence87999172014-02-20 12:21:31 -08002233 /* Write the key to the end of the partition */
2234 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002235
Paul Lawrence87999172014-02-20 12:21:31 -08002236 /* If any persistent data has been remembered, save it.
2237 * If none, create a valid empty table and save that.
2238 */
2239 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002240 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2241 if (pdata) {
2242 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2243 persist_data = pdata;
2244 }
Paul Lawrence87999172014-02-20 12:21:31 -08002245 }
2246 if (persist_data) {
2247 save_persistent_data();
2248 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002249 }
2250
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002251 if (onlyCreateHeader) {
2252 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002253 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002254 }
2255
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002256 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002257 /* startup service classes main and late_start */
2258 property_set("vold.decrypt", "trigger_restart_min_framework");
2259 SLOGD("Just triggered restart_min_framework\n");
2260
2261 /* OK, the framework is restarted and will soon be showing a
2262 * progress bar. Time to setup an encrypted mapping, and
2263 * either write a new filesystem, or encrypt in place updating
2264 * the progress bar as we work.
2265 */
2266 }
2267
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002268 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Eric Biggers88f993b2020-11-03 14:11:00 -08002269 rc = create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(),
2270 &crypto_blkdev, CRYPTO_BLOCK_DEVICE, 0);
2271 if (!rc) {
Eric Biggersf038c5f2020-11-03 14:11:02 -08002272 if (encrypt_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size, true)) {
2273 crypt_ftr.encrypted_upto = crypt_ftr.fs_size;
2274 rc = 0;
2275 } else {
2276 rc = -1;
2277 }
Eric Biggers88f993b2020-11-03 14:11:00 -08002278 /* Undo the dm-crypt mapping whether we succeed or not */
2279 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2280 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002281
Paul Crowley14c8c072018-09-18 13:30:21 -07002282 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002283 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002284 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002285
Paul Lawrence6bfed202014-07-28 12:47:22 -07002286 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002287
Eric Biggersc01995e2020-11-03 14:11:00 -08002288 char value[PROPERTY_VALUE_MAX];
2289 property_get("ro.crypto.state", value, "");
2290 if (!strcmp(value, "")) {
2291 /* default encryption - continue first boot sequence */
2292 property_set("ro.crypto.state", "encrypted");
2293 property_set("ro.crypto.type", "block");
2294 wakeLock.reset(nullptr);
2295 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2296 // Bring up cryptkeeper that will check the password and set it
2297 property_set("vold.decrypt", "trigger_shutdown_framework");
2298 sleep(2);
2299 property_set("vold.encrypt_progress", "");
2300 cryptfs_trigger_restart_min_framework();
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002301 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002302 cryptfs_check_passwd(DEFAULT_PASSWORD);
2303 cryptfs_restart_internal(1);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002304 }
Eric Biggersc01995e2020-11-03 14:11:00 -08002305 return 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002306 } else {
Eric Biggersc01995e2020-11-03 14:11:00 -08002307 sleep(2); /* Give the UI a chance to show 100% progress */
2308 cryptfs_reboot(RebootType::reboot);
Paul Lawrence87999172014-02-20 12:21:31 -08002309 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002310 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002311 char value[PROPERTY_VALUE_MAX];
2312
Ken Sumrall319369a2012-06-27 16:30:18 -07002313 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002314 if (!strcmp(value, "1")) {
2315 /* wipe data if encryption failed */
2316 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002317 std::string err;
2318 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002319 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002320 if (!write_bootloader_message(options, &err)) {
2321 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002322 }
Josh Gaofec44372017-08-28 13:22:55 -07002323 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002324 } else {
2325 /* set property to trigger dialog */
2326 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002327 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002328 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002329 }
2330
Ken Sumrall3ed82362011-01-28 23:31:16 -08002331 /* hrm, the encrypt step claims success, but the reboot failed.
2332 * This should not happen.
2333 * Set the property and return. Hope the framework can deal with it.
2334 */
2335 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002336 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002337
2338error_unencrypted:
2339 property_set("vold.encrypt_progress", "error_not_encrypted");
2340 return -1;
2341
2342error_shutting_down:
2343 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2344 * but the framework is stopped and not restarted to show the error, so it's up to
2345 * vold to restart the system.
2346 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002347 SLOGE(
2348 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2349 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002350 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002351
2352 /* shouldn't get here */
2353 property_set("vold.encrypt_progress", "error_shutting_down");
2354 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002355}
2356
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002357int cryptfs_enable(int type, const char* passwd, int no_ui) {
2358 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002359}
2360
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002361int cryptfs_enable_default(int no_ui) {
2362 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002363}
2364
Paul Crowley14c8c072018-09-18 13:30:21 -07002365int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002366 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002367 SLOGE("cryptfs_changepw not valid for file encryption");
2368 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002369 }
2370
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002371 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002372 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002373
2374 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002375 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002376 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002377 return -1;
2378 }
2379
Paul Lawrencef4faa572014-01-29 13:31:03 -08002380 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2381 SLOGE("Invalid crypt_type %d", crypt_type);
2382 return -1;
2383 }
2384
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002385 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002386 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002387 SLOGE("Error getting crypt footer and key");
2388 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002389 }
2390
Paul Lawrencef4faa572014-01-29 13:31:03 -08002391 crypt_ftr.crypt_type = crypt_type;
2392
Paul Crowley14c8c072018-09-18 13:30:21 -07002393 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2394 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002395 if (rc) {
2396 SLOGE("Encrypt master key failed: %d", rc);
2397 return -1;
2398 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002399 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002400 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002401
2402 return 0;
2403}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002404
Rubin Xu85c01f92014-10-13 12:49:54 +01002405static unsigned int persist_get_max_entries(int encrypted) {
2406 struct crypt_mnt_ftr crypt_ftr;
2407 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002408
2409 /* If encrypted, use the values from the crypt_ftr, otherwise
2410 * use the values for the current spec.
2411 */
2412 if (encrypted) {
2413 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002414 /* Something is wrong, assume no space for entries */
2415 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002416 }
2417 dsize = crypt_ftr.persist_data_size;
2418 } else {
2419 dsize = CRYPT_PERSIST_DATA_SIZE;
2420 }
2421
Rubin Xuf83cc612018-10-09 16:13:38 +01002422 if (dsize > sizeof(struct crypt_persist_data)) {
2423 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2424 } else {
2425 return 0;
2426 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002427}
2428
Paul Crowley14c8c072018-09-18 13:30:21 -07002429static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002430 unsigned int i;
2431
2432 if (persist_data == NULL) {
2433 return -1;
2434 }
2435 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2436 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2437 /* We found it! */
2438 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2439 return 0;
2440 }
2441 }
2442
2443 return -1;
2444}
2445
Paul Crowley14c8c072018-09-18 13:30:21 -07002446static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002447 unsigned int i;
2448 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002449 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002450
2451 if (persist_data == NULL) {
2452 return -1;
2453 }
2454
Rubin Xu85c01f92014-10-13 12:49:54 +01002455 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002456
2457 num = persist_data->persist_valid_entries;
2458
2459 for (i = 0; i < num; i++) {
2460 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2461 /* We found an existing entry, update it! */
2462 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2463 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2464 return 0;
2465 }
2466 }
2467
2468 /* We didn't find it, add it to the end, if there is room */
2469 if (persist_data->persist_valid_entries < max_persistent_entries) {
2470 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2471 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2472 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2473 persist_data->persist_valid_entries++;
2474 return 0;
2475 }
2476
2477 return -1;
2478}
2479
Rubin Xu85c01f92014-10-13 12:49:54 +01002480/**
2481 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2482 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2483 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002484int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002485 std::string key_ = key;
2486 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002487
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002488 std::string parsed_field;
2489 unsigned parsed_index;
2490
2491 std::string::size_type split = key_.find_last_of('_');
2492 if (split == std::string::npos) {
2493 parsed_field = key_;
2494 parsed_index = 0;
2495 } else {
2496 parsed_field = key_.substr(0, split);
2497 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002498 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002499
2500 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002501}
2502
2503/*
2504 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2505 * remaining entries starting from index will be deleted.
2506 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2507 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2508 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2509 *
2510 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002511static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002512 unsigned int i;
2513 unsigned int j;
2514 unsigned int num;
2515
2516 if (persist_data == NULL) {
2517 return PERSIST_DEL_KEY_ERROR_OTHER;
2518 }
2519
2520 num = persist_data->persist_valid_entries;
2521
Paul Crowley14c8c072018-09-18 13:30:21 -07002522 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002523 // Filter out to-be-deleted entries in place.
2524 for (i = 0; i < num; i++) {
2525 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2526 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2527 j++;
2528 }
2529 }
2530
2531 if (j < num) {
2532 persist_data->persist_valid_entries = j;
2533 // Zeroise the remaining entries
2534 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2535 return PERSIST_DEL_KEY_OK;
2536 } else {
2537 // Did not find an entry matching the given fieldname
2538 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2539 }
2540}
2541
Paul Crowley14c8c072018-09-18 13:30:21 -07002542static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002543 unsigned int i;
2544 unsigned int count;
2545
2546 if (persist_data == NULL) {
2547 return -1;
2548 }
2549
2550 count = 0;
2551 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2552 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2553 count++;
2554 }
2555 }
2556
2557 return count;
2558}
2559
Ken Sumrall160b4d62013-04-22 12:15:39 -07002560/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002561int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002562 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002563 SLOGE("Cannot get field when file encrypted");
2564 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002565 }
2566
Ken Sumrall160b4d62013-04-22 12:15:39 -07002567 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002568 /* CRYPTO_GETFIELD_OK is success,
2569 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2570 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2571 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002572 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002573 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2574 int i;
2575 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002576
2577 if (persist_data == NULL) {
2578 load_persistent_data();
2579 if (persist_data == NULL) {
2580 SLOGE("Getfield error, cannot load persistent data");
2581 goto out;
2582 }
2583 }
2584
Rubin Xu85c01f92014-10-13 12:49:54 +01002585 // Read value from persistent entries. If the original value is split into multiple entries,
2586 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002587 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002588 // 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 -07002589 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002590 // value too small
2591 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2592 goto out;
2593 }
2594 rc = CRYPTO_GETFIELD_OK;
2595
2596 for (i = 1; /* break explicitly */; i++) {
2597 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002598 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002599 // If the fieldname is very long, we stop as soon as it begins to overflow the
2600 // maximum field length. At this point we have in fact fully read out the original
2601 // value because cryptfs_setfield would not allow fields with longer names to be
2602 // written in the first place.
2603 break;
2604 }
2605 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002606 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2607 // value too small.
2608 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2609 goto out;
2610 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002611 } else {
2612 // Exhaust all entries.
2613 break;
2614 }
2615 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002616 } else {
2617 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002618 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002619 }
2620
2621out:
2622 return rc;
2623}
2624
2625/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002626int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002627 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002628 SLOGE("Cannot set field when file encrypted");
2629 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002630 }
2631
Ken Sumrall160b4d62013-04-22 12:15:39 -07002632 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002633 /* 0 is success, negative values are error */
2634 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002635 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002636 unsigned int field_id;
2637 char temp_field[PROPERTY_KEY_MAX];
2638 unsigned int num_entries;
2639 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002640
2641 if (persist_data == NULL) {
2642 load_persistent_data();
2643 if (persist_data == NULL) {
2644 SLOGE("Setfield error, cannot load persistent data");
2645 goto out;
2646 }
2647 }
2648
2649 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002650 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002651 encrypted = 1;
2652 }
2653
Rubin Xu85c01f92014-10-13 12:49:54 +01002654 // Compute the number of entries required to store value, each entry can store up to
2655 // (PROPERTY_VALUE_MAX - 1) chars
2656 if (strlen(value) == 0) {
2657 // Empty value also needs one entry to store.
2658 num_entries = 1;
2659 } else {
2660 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2661 }
2662
2663 max_keylen = strlen(fieldname);
2664 if (num_entries > 1) {
2665 // Need an extra "_%d" suffix.
2666 max_keylen += 1 + log10(num_entries);
2667 }
2668 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2669 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002670 goto out;
2671 }
2672
Rubin Xu85c01f92014-10-13 12:49:54 +01002673 // Make sure we have enough space to write the new value
2674 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2675 persist_get_max_entries(encrypted)) {
2676 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2677 goto out;
2678 }
2679
2680 // Now that we know persist_data has enough space for value, let's delete the old field first
2681 // to make up space.
2682 persist_del_keys(fieldname, 0);
2683
2684 if (persist_set_key(fieldname, value, encrypted)) {
2685 // fail to set key, should not happen as we have already checked the available space
2686 SLOGE("persist_set_key() error during setfield()");
2687 goto out;
2688 }
2689
2690 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002691 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002692
2693 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2694 // fail to set key, should not happen as we have already checked the available space.
2695 SLOGE("persist_set_key() error during setfield()");
2696 goto out;
2697 }
2698 }
2699
Ken Sumrall160b4d62013-04-22 12:15:39 -07002700 /* If we are running encrypted, save the persistent data now */
2701 if (encrypted) {
2702 if (save_persistent_data()) {
2703 SLOGE("Setfield error, cannot save persistent data");
2704 goto out;
2705 }
2706 }
2707
Rubin Xu85c01f92014-10-13 12:49:54 +01002708 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002709
2710out:
2711 return rc;
2712}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002713
2714/* Checks userdata. Attempt to mount the volume if default-
2715 * encrypted.
2716 * On success trigger next init phase and return 0.
2717 * Currently do not handle failure - see TODO below.
2718 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002719int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002720 int crypt_type = cryptfs_get_password_type();
2721 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2722 SLOGE("Bad crypt type - error");
2723 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002724 SLOGD(
2725 "Password is not default - "
2726 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002727 property_set("vold.decrypt", "trigger_restart_min_framework");
2728 return 0;
2729 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2730 SLOGD("Password is default - restarting filesystem");
2731 cryptfs_restart_internal(0);
2732 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002733 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002734 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002735 }
2736
Paul Lawrence6bfed202014-07-28 12:47:22 -07002737 /** Corrupt. Allow us to boot into framework, which will detect bad
2738 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002739 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002740 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002741 return 0;
2742}
2743
2744/* Returns type of the password, default, pattern, pin or password.
2745 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002746int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002747 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002748 SLOGE("cryptfs_get_password_type not valid for file encryption");
2749 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002750 }
2751
Paul Lawrencef4faa572014-01-29 13:31:03 -08002752 struct crypt_mnt_ftr crypt_ftr;
2753
2754 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2755 SLOGE("Error getting crypt footer and key\n");
2756 return -1;
2757 }
2758
Paul Lawrence6bfed202014-07-28 12:47:22 -07002759 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2760 return -1;
2761 }
2762
Paul Lawrencef4faa572014-01-29 13:31:03 -08002763 return crypt_ftr.crypt_type;
2764}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002765
Paul Crowley14c8c072018-09-18 13:30:21 -07002766const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002767 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002768 SLOGE("cryptfs_get_password not valid for file encryption");
2769 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002770 }
2771
Paul Lawrence399317e2014-03-10 13:20:50 -07002772 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002773 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002774 if (now.tv_sec < password_expiry_time) {
2775 return password;
2776 } else {
2777 cryptfs_clear_password();
2778 return 0;
2779 }
2780}
2781
Paul Crowley14c8c072018-09-18 13:30:21 -07002782void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002783 if (password) {
2784 size_t len = strlen(password);
2785 memset(password, 0, len);
2786 free(password);
2787 password = 0;
2788 password_expiry_time = 0;
2789 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002790}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002791
Paul Crowley14c8c072018-09-18 13:30:21 -07002792int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002793 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2794 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002795}