blob: 64b72f0a3ecf7a23f87e8962b9b3274154f1d1ce [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"
Logan Chiend557d762018-05-02 11:36:45 +080022#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070023#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080024#include "Keymaster.h"
25#include "Process.h"
26#include "ScryptParameters.h"
Paul Crowleycfe39722018-10-30 15:59:24 -070027#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "VoldUtil.h"
29#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080030
Eric Biggersed45ec32019-01-25 10:47:55 -080031#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080032#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080033#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080034#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080035#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080036#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070037#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070039#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070040#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070041#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080042#include <log/log.h>
Logan Chiend557d762018-05-02 11:36:45 +080043#include <logwrap/logwrap.h>
44#include <openssl/evp.h>
45#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080046#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070047#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080048
49#include <ctype.h>
50#include <errno.h>
51#include <fcntl.h>
52#include <inttypes.h>
53#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080054#include <linux/kdev_t.h>
55#include <math.h>
56#include <stdio.h>
57#include <stdlib.h>
58#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080059#include <sys/mount.h>
60#include <sys/param.h>
61#include <sys/stat.h>
62#include <sys/types.h>
63#include <sys/wait.h>
64#include <time.h>
65#include <unistd.h>
66
Wei Wang4375f1b2017-02-24 17:43:01 -080067extern "C" {
68#include <crypto_scrypt.h>
69}
Mark Salyzyn3e971272014-01-21 13:27:04 -080070
Eric Biggersed45ec32019-01-25 10:47:55 -080071using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080072using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080073using android::fs_mgr::GetEntryForMountPoint;
David Andersonb9224732019-05-13 13:02:54 -070074using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070075using namespace std::chrono_literals;
76
Paul Crowley73be12d2020-02-03 12:22:03 -080077/* The current cryptfs version */
78#define CURRENT_MAJOR_VERSION 1
79#define CURRENT_MINOR_VERSION 3
80
81#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
82#define CRYPT_PERSIST_DATA_SIZE 0x1000
83
84#define MAX_CRYPTO_TYPE_NAME_LEN 64
85
86#define MAX_KEY_LEN 48
87#define SALT_LEN 16
88#define SCRYPT_LEN 32
89
90/* definitions of flags in the structure below */
91#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
92#define CRYPT_ENCRYPTION_IN_PROGRESS \
93 0x2 /* Encryption partially completed, \
94 encrypted_upto valid*/
95#define CRYPT_INCONSISTENT_STATE \
96 0x4 /* Set when starting encryption, clear when \
97 exit cleanly, either through success or \
98 correctly marked partial encryption */
99#define CRYPT_DATA_CORRUPT \
100 0x8 /* Set when encryption is fine, but the \
101 underlying volume is corrupt */
102#define CRYPT_FORCE_ENCRYPTION \
103 0x10 /* Set when it is time to encrypt this \
104 volume on boot. Everything in this \
105 structure is set up correctly as \
106 though device is encrypted except \
107 that the master key is encrypted with the \
108 default password. */
109#define CRYPT_FORCE_COMPLETE \
110 0x20 /* Set when the above encryption cycle is \
111 complete. On next cryptkeeper entry, match \
112 the password. If it matches fix the master \
113 key and remove this flag. */
114
115/* Allowed values for type in the structure below */
116#define CRYPT_TYPE_PASSWORD \
117 0 /* master_key is encrypted with a password \
118 * Must be zero to be compatible with pre-L \
119 * devices where type is always password.*/
120#define CRYPT_TYPE_DEFAULT \
121 1 /* master_key is encrypted with default \
122 * password */
123#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
124#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
125#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
126
127#define CRYPT_MNT_MAGIC 0xD0B5B1C4
128#define PERSIST_DATA_MAGIC 0xE950CD44
129
130/* Key Derivation Function algorithms */
131#define KDF_PBKDF2 1
132#define KDF_SCRYPT 2
133/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
134#define KDF_SCRYPT_KEYMASTER 5
135
136/* Maximum allowed keymaster blob size. */
137#define KEYMASTER_BLOB_SIZE 2048
138
139/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
140#define __le8 unsigned char
141
142#if !defined(SHA256_DIGEST_LENGTH)
143#define SHA256_DIGEST_LENGTH 32
144#endif
145
146/* This structure starts 16,384 bytes before the end of a hardware
147 * partition that is encrypted, or in a separate partition. It's location
148 * is specified by a property set in init.<device>.rc.
149 * The structure allocates 48 bytes for a key, but the real key size is
150 * specified in the struct. Currently, the code is hardcoded to use 128
151 * bit keys.
152 * The fields after salt are only valid in rev 1.1 and later stuctures.
153 * Obviously, the filesystem does not include the last 16 kbytes
154 * of the partition if the crypt_mnt_ftr lives at the end of the
155 * partition.
156 */
157
158struct crypt_mnt_ftr {
159 __le32 magic; /* See above */
160 __le16 major_version;
161 __le16 minor_version;
162 __le32 ftr_size; /* in bytes, not including key following */
163 __le32 flags; /* See above */
164 __le32 keysize; /* in bytes */
165 __le32 crypt_type; /* how master_key is encrypted. Must be a
166 * CRYPT_TYPE_XXX value */
167 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
168 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
169 mount, set to 0 on successful mount */
170 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
171 needed to decrypt this
172 partition, null terminated */
173 __le32 spare2; /* ignored */
174 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
175 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
176 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
177 * on device with that info, either the footer of the
178 * real_blkdevice or the metadata partition. */
179
180 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
181 * persistent data table*/
182
183 __le8 kdf_type; /* The key derivation function used. */
184
185 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
186 __le8 N_factor; /* (1 << N) */
187 __le8 r_factor; /* (1 << r) */
188 __le8 p_factor; /* (1 << p) */
189 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
190 we have to stop (e.g. power low) this is the last
191 encrypted 512 byte sector.*/
192 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
193 set, hash of first block, used
194 to validate before continuing*/
195
196 /* key_master key, used to sign the derived key which is then used to generate
197 * the intermediate key
198 * This key should be used for no other purposes! We use this key to sign unpadded
199 * data, which is acceptable but only if the key is not reused elsewhere. */
200 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
201 __le32 keymaster_blob_size;
202
203 /* Store scrypt of salted intermediate key. When decryption fails, we can
204 check if this matches, and if it does, we know that the problem is with the
205 drive, and there is no point in asking the user for more passwords.
206
207 Note that if any part of this structure is corrupt, this will not match and
208 we will continue to believe the user entered the wrong password. In that
209 case the only solution is for the user to enter a password enough times to
210 force a wipe.
211
212 Note also that there is no need to worry about migration. If this data is
213 wrong, we simply won't recognise a right password, and will continue to
214 prompt. On the first password change, this value will be populated and
215 then we will be OK.
216 */
217 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
218
219 /* sha of this structure with this element set to zero
220 Used when encrypting on reboot to validate structure before doing something
221 fatal
222 */
223 unsigned char sha256[SHA256_DIGEST_LENGTH];
224};
225
226/* Persistant data that should be available before decryption.
227 * Things like airplane mode, locale and timezone are kept
228 * here and can be retrieved by the CryptKeeper UI to properly
229 * configure the phone before asking for the password
230 * This is only valid if the major and minor version above
231 * is set to 1.1 or higher.
232 *
233 * This is a 4K structure. There are 2 copies, and the code alternates
234 * writing one and then clearing the previous one. The reading
235 * code reads the first valid copy it finds, based on the magic number.
236 * The absolute offset to the first of the two copies is kept in rev 1.1
237 * and higher crypt_mnt_ftr structures.
238 */
239struct crypt_persist_entry {
240 char key[PROPERTY_KEY_MAX];
241 char val[PROPERTY_VALUE_MAX];
242};
243
244/* Should be exactly 4K in size */
245struct crypt_persist_data {
246 __le32 persist_magic;
247 __le32 persist_valid_entries;
248 __le32 persist_spare[30];
249 struct crypt_persist_entry persist_entry[0];
250};
251
252static int wait_and_unmount(const char* mountpoint, bool kill);
253
254typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
255 void* params);
256
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800257#define UNUSED __attribute__((unused))
258
Jason parks70a4b3f2011-01-28 10:10:47 -0600259#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800260
261constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
262constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700263constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800264
265// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700266static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600267
Paul Crowley14c8c072018-09-18 13:30:21 -0700268#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700269
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700270#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800271
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800272#define CRYPTO_BLOCK_DEVICE "userdata"
273
274#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
275
Ken Sumrall29d8da82011-05-18 17:20:07 -0700276#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700277#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700278
Ken Sumralle919efe2012-09-29 17:07:41 -0700279#define TABLE_LOAD_RETRIES 10
280
Shawn Willden47ba10d2014-09-03 17:07:06 -0600281#define RSA_KEY_SIZE 2048
282#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
283#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600284#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700285
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700286#define RETRY_MOUNT_ATTEMPTS 10
287#define RETRY_MOUNT_DELAY_SECONDS 1
288
Paul Crowley5afbc622017-11-27 09:42:17 -0800289#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
290
Paul Crowley73473332017-11-21 15:43:51 -0800291static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
292
Greg Kaiser59ad0182018-02-16 13:01:36 -0800293static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700294static char* saved_mount_point;
295static int master_key_saved = 0;
296static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800297
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700298/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700299static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000300 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700301}
302
303/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700304static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800305 if (ftr->keymaster_blob_size) {
306 SLOGI("Already have key");
307 return 0;
308 }
309
Paul Crowley14c8c072018-09-18 13:30:21 -0700310 int rc = keymaster_create_key_for_cryptfs_scrypt(
311 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
312 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000313 if (rc) {
314 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800315 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000316 ftr->keymaster_blob_size = 0;
317 }
318 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700319 return -1;
320 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000321 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700322}
323
Shawn Willdene17a9c42014-09-08 13:04:08 -0600324/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700325static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
326 const size_t object_size, unsigned char** signature,
327 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600328 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600329 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600330 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600331
Shawn Willdene17a9c42014-09-08 13:04:08 -0600332 // To sign a message with RSA, the message must satisfy two
333 // constraints:
334 //
335 // 1. The message, when interpreted as a big-endian numeric value, must
336 // be strictly less than the public modulus of the RSA key. Note
337 // that because the most significant bit of the public modulus is
338 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
339 // key), an n-bit message with most significant bit 0 always
340 // satisfies this requirement.
341 //
342 // 2. The message must have the same length in bits as the public
343 // modulus of the RSA key. This requirement isn't mathematically
344 // necessary, but is necessary to ensure consistency in
345 // implementations.
346 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600347 case KDF_SCRYPT_KEYMASTER:
348 // This ensures the most significant byte of the signed message
349 // is zero. We could have zero-padded to the left instead, but
350 // this approach is slightly more robust against changes in
351 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600352 // so) because we really should be using a proper deterministic
353 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800354 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600355 SLOGI("Signing safely-padded object");
356 break;
357 default:
358 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000359 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600360 }
Paul Crowley73473332017-11-21 15:43:51 -0800361 for (;;) {
362 auto result = keymaster_sign_object_for_cryptfs_scrypt(
363 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
364 to_sign_size, signature, signature_size);
365 switch (result) {
366 case KeymasterSignResult::ok:
367 return 0;
368 case KeymasterSignResult::upgrade:
369 break;
370 default:
371 return -1;
372 }
373 SLOGD("Upgrading key");
374 if (keymaster_upgrade_key_for_cryptfs_scrypt(
375 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
376 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
377 &ftr->keymaster_blob_size) != 0) {
378 SLOGE("Failed to upgrade key");
379 return -1;
380 }
381 if (put_crypt_ftr_and_key(ftr) != 0) {
382 SLOGE("Failed to write upgraded key to disk");
383 }
384 SLOGD("Key upgraded successfully");
385 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600386}
387
Paul Lawrence399317e2014-03-10 13:20:50 -0700388/* Store password when userdata is successfully decrypted and mounted.
389 * Cleared by cryptfs_clear_password
390 *
391 * To avoid a double prompt at boot, we need to store the CryptKeeper
392 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
393 * Since the entire framework is torn down and rebuilt after encryption,
394 * we have to use a daemon or similar to store the password. Since vold
395 * is secured against IPC except from system processes, it seems a reasonable
396 * place to store this.
397 *
398 * password should be cleared once it has been used.
399 *
400 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800401 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700402static char* password = 0;
403static int password_expiry_time = 0;
404static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800405
Paul Crowley14c8c072018-09-18 13:30:21 -0700406enum class RebootType { reboot, recovery, shutdown };
407static void cryptfs_reboot(RebootType rt) {
408 switch (rt) {
409 case RebootType::reboot:
410 property_set(ANDROID_RB_PROPERTY, "reboot");
411 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800412
Paul Crowley14c8c072018-09-18 13:30:21 -0700413 case RebootType::recovery:
414 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
415 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800416
Paul Crowley14c8c072018-09-18 13:30:21 -0700417 case RebootType::shutdown:
418 property_set(ANDROID_RB_PROPERTY, "shutdown");
419 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700420 }
Paul Lawrence87999172014-02-20 12:21:31 -0800421
Ken Sumralladfba362013-06-04 16:37:52 -0700422 sleep(20);
423
424 /* Shouldn't get here, reboot should happen before sleep times out */
425 return;
426}
427
Greg Kaiser38723f22018-02-16 13:35:35 -0800428namespace {
429
430struct CryptoType;
431
432// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700433const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800434
435struct CryptoType {
436 // We should only be constructing CryptoTypes as part of
437 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
438 // which isn't pure or fully protected as a concession to being able to
439 // do it all at compile time. Add new CryptoTypes in
440 // supported_crypto_types[] below.
441 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
442 constexpr CryptoType set_keysize(uint32_t size) const {
443 return CryptoType(this->property_name, this->crypto_name, size);
444 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800446 return CryptoType(property, this->crypto_name, this->keysize);
447 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700448 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800449 return CryptoType(this->property_name, crypto, this->keysize);
450 }
451
Paul Crowley14c8c072018-09-18 13:30:21 -0700452 constexpr const char* get_property_name() const { return property_name; }
453 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800454 constexpr uint32_t get_keysize() const { return keysize; }
455
Paul Crowley14c8c072018-09-18 13:30:21 -0700456 private:
457 const char* property_name;
458 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800459 uint32_t keysize;
460
Paul Crowley14c8c072018-09-18 13:30:21 -0700461 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800462 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700463 friend const CryptoType& get_crypto_type();
464 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800465};
466
467// We only want to parse this read-only property once. But we need to wait
468// until the system is initialized before we can read it. So we use a static
469// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700470const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800471 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
472 return crypto_type;
473}
474
475constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700476 .set_property_name("AES-128-CBC")
477 .set_crypto_name("aes-cbc-essiv:sha256")
478 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800479
480constexpr CryptoType supported_crypto_types[] = {
481 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800482 CryptoType()
483 .set_property_name("adiantum")
484 .set_crypto_name("xchacha12,aes-adiantum-plain64")
485 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800486 // Add new CryptoTypes here. Order is not important.
487};
488
Greg Kaiser38723f22018-02-16 13:35:35 -0800489// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
490// We confirm all supported_crypto_types have a small enough keysize and
491// had both set_property_name() and set_crypto_name() called.
492
493template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700494constexpr size_t array_length(T (&)[N]) {
495 return N;
496}
Greg Kaiser38723f22018-02-16 13:35:35 -0800497
498constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
499 return (index >= array_length(supported_crypto_types));
500}
501
Paul Crowley14c8c072018-09-18 13:30:21 -0700502constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800503 return ((crypto_type.get_property_name() != nullptr) &&
504 (crypto_type.get_crypto_name() != nullptr) &&
505 (crypto_type.get_keysize() <= MAX_KEY_LEN));
506}
507
508// Note in C++11 that constexpr functions can only have a single line.
509// So our code is a bit convoluted (using recursion instead of a loop),
510// but it's asserting at compile time that all of our key lengths are valid.
511constexpr bool validateSupportedCryptoTypes(size_t index) {
512 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700513 (isValidCryptoType(supported_crypto_types[index]) &&
514 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800515}
516
517static_assert(validateSupportedCryptoTypes(0),
518 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
519 "incompletely constructed.");
520// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
521
Greg Kaiser38723f22018-02-16 13:35:35 -0800522// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700523const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800524 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
525 char paramstr[PROPERTY_VALUE_MAX];
526
Paul Crowley14c8c072018-09-18 13:30:21 -0700527 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
528 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800529 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
530 return ctype;
531 }
532 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700533 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
534 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800535 return default_crypto_type;
536}
537
538} // namespace
539
Kenny Rootc4c70f12013-06-14 12:11:38 -0700540/**
541 * Gets the default device scrypt parameters for key derivation time tuning.
542 * The parameters should lead to about one second derivation time for the
543 * given device.
544 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700545static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700546 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000547 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700548
Paul Crowley63c18d32016-02-10 14:02:47 +0000549 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
550 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
551 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
552 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700553 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000554 ftr->N_factor = Nf;
555 ftr->r_factor = rf;
556 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700557}
558
Greg Kaiser57f9af62018-02-16 13:13:58 -0800559uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800560 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800561}
562
Paul Crowley14c8c072018-09-18 13:30:21 -0700563const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800564 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800565}
566
Tom Cherry4c5bde22019-01-29 14:34:01 -0800567static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800568 int fd, block_size;
569 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200570 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800571
Paul Crowley14c8c072018-09-18 13:30:21 -0700572 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800573 SLOGE("Cannot open device to get filesystem size ");
574 return 0;
575 }
576
577 if (lseek64(fd, 1024, SEEK_SET) < 0) {
578 SLOGE("Cannot seek to superblock");
579 return 0;
580 }
581
582 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
583 SLOGE("Cannot read superblock");
584 return 0;
585 }
586
587 close(fd);
588
Daniel Rosenberge82df162014-08-15 22:19:23 +0000589 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
590 SLOGE("Not a valid ext4 superblock");
591 return 0;
592 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800593 block_size = 1024 << sb.s_log_block_size;
594 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200595 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800596
597 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200598 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800599}
600
Tom Cherry4c5bde22019-01-29 14:34:01 -0800601static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
602 for (const auto& entry : fstab_default) {
603 if (!entry.fs_mgr_flags.vold_managed &&
604 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
605 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
606 if (key_loc != nullptr) {
607 *key_loc = entry.key_loc;
608 }
609 if (real_blk_device != nullptr) {
610 *real_blk_device = entry.blk_device;
611 }
612 return;
613 }
614 }
615}
616
Paul Crowley14c8c072018-09-18 13:30:21 -0700617static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
618 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200619 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700620 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700621 char key_loc[PROPERTY_VALUE_MAX];
622 char real_blkdev[PROPERTY_VALUE_MAX];
623 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700624
Paul Crowley14c8c072018-09-18 13:30:21 -0700625 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800626 std::string key_loc;
627 std::string real_blkdev;
628 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700629
Tom Cherry4c5bde22019-01-29 14:34:01 -0800630 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200631 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700632 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
633 * encryption info footer and key, and plenty of bytes to spare for future
634 * growth.
635 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800636 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200637 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700638 cached_data = 1;
639 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800640 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700641 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700642 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800643 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700644 cached_off = 0;
645 cached_data = 1;
646 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700647 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700648
Paul Crowley14c8c072018-09-18 13:30:21 -0700649 if (cached_data) {
650 if (metadata_fname) {
651 *metadata_fname = cached_metadata_fname;
652 }
653 if (off) {
654 *off = cached_off;
655 }
656 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700657 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700658
Paul Crowley14c8c072018-09-18 13:30:21 -0700659 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700660}
661
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800662/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700663static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800664 SHA256_CTX c;
665 SHA256_Init(&c);
666 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
667 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
668 SHA256_Final(crypt_ftr->sha256, &c);
669}
670
Ken Sumralle8744072011-01-18 22:01:55 -0800671/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800672 * update the failed mount count but not change the key.
673 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700674static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
675 int fd;
676 unsigned int cnt;
677 /* starting_off is set to the SEEK_SET offset
678 * where the crypto structure starts
679 */
680 off64_t starting_off;
681 int rc = -1;
682 char* fname = NULL;
683 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800684
Paul Crowley14c8c072018-09-18 13:30:21 -0700685 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800686
Paul Crowley14c8c072018-09-18 13:30:21 -0700687 if (get_crypt_ftr_info(&fname, &starting_off)) {
688 SLOGE("Unable to get crypt_ftr_info\n");
689 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800690 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700691 if (fname[0] != '/') {
692 SLOGE("Unexpected value for crypto key location\n");
693 return -1;
694 }
695 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
696 SLOGE("Cannot open footer file %s for put\n", fname);
697 return -1;
698 }
Ken Sumralle8744072011-01-18 22:01:55 -0800699
Paul Crowley14c8c072018-09-18 13:30:21 -0700700 /* Seek to the start of the crypt footer */
701 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
702 SLOGE("Cannot seek to real block device footer\n");
703 goto errout;
704 }
705
706 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
707 SLOGE("Cannot write real block device footer\n");
708 goto errout;
709 }
710
711 fstat(fd, &statbuf);
712 /* If the keys are kept on a raw block device, do not try to truncate it. */
713 if (S_ISREG(statbuf.st_mode)) {
714 if (ftruncate(fd, 0x4000)) {
715 SLOGE("Cannot set footer file size\n");
716 goto errout;
717 }
718 }
719
720 /* Success! */
721 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800722
723errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700724 close(fd);
725 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800726}
727
Paul Crowley14c8c072018-09-18 13:30:21 -0700728static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800729 struct crypt_mnt_ftr copy;
730 memcpy(&copy, crypt_ftr, sizeof(copy));
731 set_ftr_sha(&copy);
732 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
733}
734
Paul Crowley14c8c072018-09-18 13:30:21 -0700735static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700736 return TEMP_FAILURE_RETRY(read(fd, buff, len));
737}
738
Paul Crowley14c8c072018-09-18 13:30:21 -0700739static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700740 return TEMP_FAILURE_RETRY(write(fd, buff, len));
741}
742
Paul Crowley14c8c072018-09-18 13:30:21 -0700743static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700744 memset(pdata, 0, len);
745 pdata->persist_magic = PERSIST_DATA_MAGIC;
746 pdata->persist_valid_entries = 0;
747}
748
749/* A routine to update the passed in crypt_ftr to the lastest version.
750 * fd is open read/write on the device that holds the crypto footer and persistent
751 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
752 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
753 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700754static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700755 int orig_major = crypt_ftr->major_version;
756 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700757
Kenny Root7434b312013-06-14 11:29:53 -0700758 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700759 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700760 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761
Kenny Rootc4c70f12013-06-14 12:11:38 -0700762 SLOGW("upgrading crypto footer to 1.1");
763
Paul Crowley14c8c072018-09-18 13:30:21 -0700764 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700765 if (pdata == NULL) {
766 SLOGE("Cannot allocate persisent data\n");
767 return;
768 }
769 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
770
771 /* Need to initialize the persistent data area */
772 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
773 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100774 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700775 return;
776 }
777 /* Write all zeros to the first copy, making it invalid */
778 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
779
780 /* Write a valid but empty structure to the second copy */
781 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
782 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
783
784 /* Update the footer */
785 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
786 crypt_ftr->persist_data_offset[0] = pdata_offset;
787 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
788 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100789 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700790 }
791
Paul Lawrencef4faa572014-01-29 13:31:03 -0800792 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700793 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800794 /* But keep the old kdf_type.
795 * It will get updated later to KDF_SCRYPT after the password has been verified.
796 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700797 crypt_ftr->kdf_type = KDF_PBKDF2;
798 get_device_scrypt_params(crypt_ftr);
799 crypt_ftr->minor_version = 2;
800 }
801
Paul Lawrencef4faa572014-01-29 13:31:03 -0800802 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
803 SLOGW("upgrading crypto footer to 1.3");
804 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
805 crypt_ftr->minor_version = 3;
806 }
807
Kenny Root7434b312013-06-14 11:29:53 -0700808 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
809 if (lseek64(fd, offset, SEEK_SET) == -1) {
810 SLOGE("Cannot seek to crypt footer\n");
811 return;
812 }
813 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700814 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815}
816
Paul Crowley14c8c072018-09-18 13:30:21 -0700817static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
818 int fd;
819 unsigned int cnt;
820 off64_t starting_off;
821 int rc = -1;
822 char* fname = NULL;
823 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700824
Paul Crowley14c8c072018-09-18 13:30:21 -0700825 if (get_crypt_ftr_info(&fname, &starting_off)) {
826 SLOGE("Unable to get crypt_ftr_info\n");
827 return -1;
828 }
829 if (fname[0] != '/') {
830 SLOGE("Unexpected value for crypto key location\n");
831 return -1;
832 }
833 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
834 SLOGE("Cannot open footer file %s for get\n", fname);
835 return -1;
836 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800837
Paul Crowley14c8c072018-09-18 13:30:21 -0700838 /* Make sure it's 16 Kbytes in length */
839 fstat(fd, &statbuf);
840 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
841 SLOGE("footer file %s is not the expected size!\n", fname);
842 goto errout;
843 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700844
Paul Crowley14c8c072018-09-18 13:30:21 -0700845 /* Seek to the start of the crypt footer */
846 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
847 SLOGE("Cannot seek to real block device footer\n");
848 goto errout;
849 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700850
Paul Crowley14c8c072018-09-18 13:30:21 -0700851 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
852 SLOGE("Cannot read real block device footer\n");
853 goto errout;
854 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800855
Paul Crowley14c8c072018-09-18 13:30:21 -0700856 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
857 SLOGE("Bad magic for real block device %s\n", fname);
858 goto errout;
859 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800860
Paul Crowley14c8c072018-09-18 13:30:21 -0700861 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
862 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
863 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
864 goto errout;
865 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800866
Paul Crowley14c8c072018-09-18 13:30:21 -0700867 // We risk buffer overflows with oversized keys, so we just reject them.
868 // 0-sized keys are problematic (essentially by-passing encryption), and
869 // AES-CBC key wrapping only works for multiples of 16 bytes.
870 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
871 (crypt_ftr->keysize > MAX_KEY_LEN)) {
872 SLOGE(
873 "Invalid keysize (%u) for block device %s; Must be non-zero, "
874 "divisible by 16, and <= %d\n",
875 crypt_ftr->keysize, fname, MAX_KEY_LEN);
876 goto errout;
877 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800878
Paul Crowley14c8c072018-09-18 13:30:21 -0700879 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
880 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
881 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
882 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800883
Paul Crowley14c8c072018-09-18 13:30:21 -0700884 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
885 * copy on disk before returning.
886 */
887 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
888 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
889 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800890
Paul Crowley14c8c072018-09-18 13:30:21 -0700891 /* Success! */
892 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800893
894errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700895 close(fd);
896 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800897}
898
Paul Crowley14c8c072018-09-18 13:30:21 -0700899static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700900 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
901 crypt_ftr->persist_data_offset[1]) {
902 SLOGE("Crypt_ftr persist data regions overlap");
903 return -1;
904 }
905
906 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
907 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
908 return -1;
909 }
910
911 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700912 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700913 CRYPT_FOOTER_OFFSET) {
914 SLOGE("Persistent data extends past crypto footer");
915 return -1;
916 }
917
918 return 0;
919}
920
Paul Crowley14c8c072018-09-18 13:30:21 -0700921static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700922 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700923 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700924 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700925 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700926 int found = 0;
927 int fd;
928 int ret;
929 int i;
930
931 if (persist_data) {
932 /* Nothing to do, we've already loaded or initialized it */
933 return 0;
934 }
935
Ken Sumrall160b4d62013-04-22 12:15:39 -0700936 /* If not encrypted, just allocate an empty table and initialize it */
937 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700938 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800939 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700940 if (pdata) {
941 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
942 persist_data = pdata;
943 return 0;
944 }
945 return -1;
946 }
947
Paul Crowley14c8c072018-09-18 13:30:21 -0700948 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700949 return -1;
950 }
951
Paul Crowley14c8c072018-09-18 13:30:21 -0700952 if ((crypt_ftr.major_version < 1) ||
953 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700954 SLOGE("Crypt_ftr version doesn't support persistent data");
955 return -1;
956 }
957
958 if (get_crypt_ftr_info(&fname, NULL)) {
959 return -1;
960 }
961
962 ret = validate_persistent_data_storage(&crypt_ftr);
963 if (ret) {
964 return -1;
965 }
966
Paul Crowley14c8c072018-09-18 13:30:21 -0700967 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700968 if (fd < 0) {
969 SLOGE("Cannot open %s metadata file", fname);
970 return -1;
971 }
972
Wei Wang4375f1b2017-02-24 17:43:01 -0800973 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800974 if (pdata == NULL) {
975 SLOGE("Cannot allocate memory for persistent data");
976 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700977 }
978
979 for (i = 0; i < 2; i++) {
980 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
981 SLOGE("Cannot seek to read persistent data on %s", fname);
982 goto err2;
983 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700984 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700985 SLOGE("Error reading persistent data on iteration %d", i);
986 goto err2;
987 }
988 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
989 found = 1;
990 break;
991 }
992 }
993
994 if (!found) {
995 SLOGI("Could not find valid persistent data, creating");
996 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
997 }
998
999 /* Success */
1000 persist_data = pdata;
1001 close(fd);
1002 return 0;
1003
1004err2:
1005 free(pdata);
1006
1007err:
1008 close(fd);
1009 return -1;
1010}
1011
Paul Crowley14c8c072018-09-18 13:30:21 -07001012static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001013 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001014 struct crypt_persist_data* pdata;
1015 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001016 off64_t write_offset;
1017 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001018 int fd;
1019 int ret;
1020
1021 if (persist_data == NULL) {
1022 SLOGE("No persistent data to save");
1023 return -1;
1024 }
1025
Paul Crowley14c8c072018-09-18 13:30:21 -07001026 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001027 return -1;
1028 }
1029
Paul Crowley14c8c072018-09-18 13:30:21 -07001030 if ((crypt_ftr.major_version < 1) ||
1031 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001032 SLOGE("Crypt_ftr version doesn't support persistent data");
1033 return -1;
1034 }
1035
1036 ret = validate_persistent_data_storage(&crypt_ftr);
1037 if (ret) {
1038 return -1;
1039 }
1040
1041 if (get_crypt_ftr_info(&fname, NULL)) {
1042 return -1;
1043 }
1044
Paul Crowley14c8c072018-09-18 13:30:21 -07001045 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001046 if (fd < 0) {
1047 SLOGE("Cannot open %s metadata file", fname);
1048 return -1;
1049 }
1050
Wei Wang4375f1b2017-02-24 17:43:01 -08001051 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001052 if (pdata == NULL) {
1053 SLOGE("Cannot allocate persistant data");
1054 goto err;
1055 }
1056
1057 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1058 SLOGE("Cannot seek to read persistent data on %s", fname);
1059 goto err2;
1060 }
1061
1062 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001063 SLOGE("Error reading persistent data before save");
1064 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001065 }
1066
1067 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1068 /* The first copy is the curent valid copy, so write to
1069 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001070 write_offset = crypt_ftr.persist_data_offset[1];
1071 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001072 } else {
1073 /* The second copy must be the valid copy, so write to
1074 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001075 write_offset = crypt_ftr.persist_data_offset[0];
1076 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001077 }
1078
1079 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001080 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001081 SLOGE("Cannot seek to write persistent data");
1082 goto err2;
1083 }
1084 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001085 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001086 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001087 SLOGE("Cannot seek to erase previous persistent data");
1088 goto err2;
1089 }
1090 fsync(fd);
1091 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001092 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001093 SLOGE("Cannot write to erase previous persistent data");
1094 goto err2;
1095 }
1096 fsync(fd);
1097 } else {
1098 SLOGE("Cannot write to save persistent data");
1099 goto err2;
1100 }
1101
1102 /* Success */
1103 free(pdata);
1104 close(fd);
1105 return 0;
1106
1107err2:
1108 free(pdata);
1109err:
1110 close(fd);
1111 return -1;
1112}
1113
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001114/* Convert a binary key of specified length into an ascii hex string equivalent,
1115 * without the leading 0x and with null termination
1116 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001117static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1118 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001119 unsigned int i, a;
1120 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121
Paul Crowley14c8c072018-09-18 13:30:21 -07001122 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001123 /* For each byte, write out two ascii hex digits */
1124 nibble = (master_key[i] >> 4) & 0xf;
1125 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001127 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001128 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001129 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001131 /* Add the null termination */
1132 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001133}
1134
Eric Biggersed45ec32019-01-25 10:47:55 -08001135/*
1136 * If the ro.crypto.fde_sector_size system property is set, append the
1137 * parameters to make dm-crypt use the specified crypto sector size and round
1138 * the crypto device size down to a crypto sector boundary.
1139 */
David Andersonb9224732019-05-13 13:02:54 -07001140static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001141 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001142 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001143
Eric Biggersed45ec32019-01-25 10:47:55 -08001144 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1145 unsigned int sector_size;
1146
1147 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1148 (sector_size & (sector_size - 1)) != 0) {
1149 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1150 DM_CRYPT_SECTOR_SIZE, value);
1151 return -1;
1152 }
1153
David Andersonb9224732019-05-13 13:02:54 -07001154 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001155
1156 // With this option, IVs will match the sector numbering, instead
1157 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001158 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001159
1160 // Round the crypto device size down to a crypto sector boundary.
1161 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001162 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001163 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001164}
1165
Paul Crowley5afbc622017-11-27 09:42:17 -08001166static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1167 const char* real_blk_name, char* crypto_blk_name, const char* name,
1168 uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001169 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001170
David Andersonb9224732019-05-13 13:02:54 -07001171 // We need two ASCII characters to represent each byte, and need space for
1172 // the '\0' terminator.
1173 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1174 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001175
David Andersonb9224732019-05-13 13:02:54 -07001176 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1177 (const char*)crypt_ftr->crypto_type_name,
1178 master_key_ascii, 0, real_blk_name, 0);
1179 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180
Paul Crowley5afbc622017-11-27 09:42:17 -08001181 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001182 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001183 }
David Andersonb9224732019-05-13 13:02:54 -07001184 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001185 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001186 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001187 }
David Andersonb9224732019-05-13 13:02:54 -07001188
1189 DmTable table;
1190 table.AddTarget(std::move(target));
1191
1192 int load_count = 1;
1193 while (load_count < TABLE_LOAD_RETRIES) {
1194 if (dm.CreateDevice(name, table)) {
1195 break;
1196 }
1197 load_count++;
1198 }
1199
1200 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001201 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001202 return -1;
1203 }
1204 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001205 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1206 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207
David Andersonb9224732019-05-13 13:02:54 -07001208 std::string path;
1209 if (!dm.GetDmDevicePathByName(name, &path)) {
1210 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1211 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001212 }
David Andersonb9224732019-05-13 13:02:54 -07001213 snprintf(crypto_blk_name, MAXPATHLEN, "%s", path.c_str());
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001214
Paul Crowleycfe39722018-10-30 15:59:24 -07001215 /* Ensure the dm device has been created before returning. */
1216 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1217 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001218 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001219 }
David Andersonb9224732019-05-13 13:02:54 -07001220 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001221}
1222
David Andersonb9224732019-05-13 13:02:54 -07001223static int delete_crypto_blk_dev(const std::string& name) {
1224 auto& dm = DeviceMapper::Instance();
1225 if (!dm.DeleteDevice(name)) {
1226 SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1227 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001228 }
David Andersonb9224732019-05-13 13:02:54 -07001229 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230}
1231
Paul Crowley14c8c072018-09-18 13:30:21 -07001232static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1233 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001234 SLOGI("Using pbkdf2 for cryptfs KDF");
1235
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001236 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001237 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1238 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001239}
1240
Paul Crowley14c8c072018-09-18 13:30:21 -07001241static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001242 SLOGI("Using scrypt for cryptfs KDF");
1243
Paul Crowley14c8c072018-09-18 13:30:21 -07001244 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001245
1246 int N = 1 << ftr->N_factor;
1247 int r = 1 << ftr->r_factor;
1248 int p = 1 << ftr->p_factor;
1249
1250 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001251 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001252 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001253
Paul Crowley14c8c072018-09-18 13:30:21 -07001254 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001255}
1256
Paul Crowley14c8c072018-09-18 13:30:21 -07001257static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1258 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001259 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1260
1261 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001262 size_t signature_size;
1263 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001264 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001265
1266 int N = 1 << ftr->N_factor;
1267 int r = 1 << ftr->r_factor;
1268 int p = 1 << ftr->p_factor;
1269
Paul Crowley14c8c072018-09-18 13:30:21 -07001270 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001271 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001272
1273 if (rc) {
1274 SLOGE("scrypt failed");
1275 return -1;
1276 }
1277
Paul Crowley14c8c072018-09-18 13:30:21 -07001278 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001279 SLOGE("Signing failed");
1280 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001281 }
1282
Paul Crowley14c8c072018-09-18 13:30:21 -07001283 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1284 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001285 free(signature);
1286
1287 if (rc) {
1288 SLOGE("scrypt failed");
1289 return -1;
1290 }
1291
1292 return 0;
1293}
1294
Paul Crowley14c8c072018-09-18 13:30:21 -07001295static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1296 const unsigned char* decrypted_master_key,
1297 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1298 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001299 EVP_CIPHER_CTX e_ctx;
1300 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001301 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001302
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001303 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001304 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001305
1306 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001307 case KDF_SCRYPT_KEYMASTER:
1308 if (keymaster_create_key(crypt_ftr)) {
1309 SLOGE("keymaster_create_key failed");
1310 return -1;
1311 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001312
Paul Crowley14c8c072018-09-18 13:30:21 -07001313 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1314 SLOGE("scrypt failed");
1315 return -1;
1316 }
1317 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001318
Paul Crowley14c8c072018-09-18 13:30:21 -07001319 case KDF_SCRYPT:
1320 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1321 SLOGE("scrypt failed");
1322 return -1;
1323 }
1324 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001325
Paul Crowley14c8c072018-09-18 13:30:21 -07001326 default:
1327 SLOGE("Invalid kdf_type");
1328 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001329 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001330
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001331 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001332 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001333 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1334 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001335 SLOGE("EVP_EncryptInit failed\n");
1336 return -1;
1337 }
1338 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001339
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001340 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001341 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1342 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001343 SLOGE("EVP_EncryptUpdate failed\n");
1344 return -1;
1345 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001346 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001347 SLOGE("EVP_EncryptFinal failed\n");
1348 return -1;
1349 }
1350
Greg Kaiser59ad0182018-02-16 13:01:36 -08001351 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001352 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1353 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001355
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001356 /* Store the scrypt of the intermediate key, so we can validate if it's a
1357 password error or mount error when things go wrong.
1358 Note there's no need to check for errors, since if this is incorrect, we
1359 simply won't wipe userdata, which is the correct default behavior
1360 */
1361 int N = 1 << crypt_ftr->N_factor;
1362 int r = 1 << crypt_ftr->r_factor;
1363 int p = 1 << crypt_ftr->p_factor;
1364
Paul Crowley14c8c072018-09-18 13:30:21 -07001365 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1366 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001367 sizeof(crypt_ftr->scrypted_intermediate_key));
1368
1369 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001370 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001371 }
1372
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001373 EVP_CIPHER_CTX_cleanup(&e_ctx);
1374
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001375 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001376}
1377
Paul Crowley14c8c072018-09-18 13:30:21 -07001378static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1379 const unsigned char* encrypted_master_key, size_t keysize,
1380 unsigned char* decrypted_master_key, kdf_func kdf,
1381 void* kdf_params, unsigned char** intermediate_key,
1382 size_t* intermediate_key_size) {
1383 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1384 EVP_CIPHER_CTX d_ctx;
1385 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001386
Paul Crowley14c8c072018-09-18 13:30:21 -07001387 /* Turn the password into an intermediate key and IV that can decrypt the
1388 master key */
1389 if (kdf(passwd, salt, ikey, kdf_params)) {
1390 SLOGE("kdf failed");
1391 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001392 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001393
Paul Crowley14c8c072018-09-18 13:30:21 -07001394 /* Initialize the decryption engine */
1395 EVP_CIPHER_CTX_init(&d_ctx);
1396 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1397 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1398 return -1;
1399 }
1400 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1401 /* Decrypt the master key */
1402 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1403 keysize)) {
1404 return -1;
1405 }
1406 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1407 return -1;
1408 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001409
Paul Crowley14c8c072018-09-18 13:30:21 -07001410 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1411 return -1;
1412 }
1413
1414 /* Copy intermediate key if needed by params */
1415 if (intermediate_key && intermediate_key_size) {
1416 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1417 if (*intermediate_key) {
1418 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1419 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1420 }
1421 }
1422
1423 EVP_CIPHER_CTX_cleanup(&d_ctx);
1424
1425 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426}
1427
Paul Crowley14c8c072018-09-18 13:30:21 -07001428static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001429 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001430 *kdf = scrypt_keymaster;
1431 *kdf_params = ftr;
1432 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001433 *kdf = scrypt;
1434 *kdf_params = ftr;
1435 } else {
1436 *kdf = pbkdf2;
1437 *kdf_params = NULL;
1438 }
1439}
1440
Paul Crowley14c8c072018-09-18 13:30:21 -07001441static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1442 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1443 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001444 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001445 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001446 int ret;
1447
1448 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001449 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1450 decrypted_master_key, kdf, kdf_params, intermediate_key,
1451 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001452 if (ret != 0) {
1453 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001454 }
1455
1456 return ret;
1457}
1458
Paul Crowley14c8c072018-09-18 13:30:21 -07001459static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1460 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001461 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001462
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001463 /* Get some random bits for a key and salt */
1464 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1465 return -1;
1466 }
1467 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1468 return -1;
1469 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001470
1471 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001472 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001473}
1474
Paul Crowley73be12d2020-02-03 12:22:03 -08001475static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001476 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001477#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001478
1479 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001480 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001481 if (umount(mountpoint) == 0) {
1482 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001483 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001484
1485 if (errno == EINVAL) {
1486 /* EINVAL is returned if the directory is not a mountpoint,
1487 * i.e. there is no filesystem mounted there. So just get out.
1488 */
1489 break;
1490 }
1491
1492 err = errno;
1493
1494 /* If allowed, be increasingly aggressive before the last two retries */
1495 if (kill) {
1496 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1497 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001498 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001499 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1500 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001501 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001502 }
1503 }
1504
1505 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001506 }
1507
1508 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001509 SLOGD("unmounting %s succeeded\n", mountpoint);
1510 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001511 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001512 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1513 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1514 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001515 }
1516
1517 return rc;
1518}
1519
Paul Crowley14c8c072018-09-18 13:30:21 -07001520static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001521 // NOTE: post_fs_data results in init calling back around to vold, so all
1522 // callers to this method must be async
1523
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001524 /* Do the prep of the /data filesystem */
1525 property_set("vold.post_fs_data_done", "0");
1526 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001527 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001528
Ken Sumrallc5872692013-05-14 15:26:31 -07001529 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001530 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001531 /* We timed out to prep /data in time. Continue wait. */
1532 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001533 }
Wei Wang42e38102017-06-07 10:46:12 -07001534 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001535}
1536
Paul Crowley14c8c072018-09-18 13:30:21 -07001537static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001538 // Mark the footer as bad
1539 struct crypt_mnt_ftr crypt_ftr;
1540 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1541 SLOGE("Failed to get crypto footer - panic");
1542 return;
1543 }
1544
1545 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1546 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1547 SLOGE("Failed to set crypto footer - panic");
1548 return;
1549 }
1550}
1551
Paul Crowley14c8c072018-09-18 13:30:21 -07001552static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001553 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001554 SLOGE("Failed to mount tmpfs on data - panic");
1555 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001556 }
1557
1558 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1559 SLOGE("Failed to trigger post fs data - panic");
1560 return;
1561 }
1562
1563 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1564 SLOGE("Failed to trigger restart min framework - panic");
1565 return;
1566 }
1567}
1568
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001569/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001570static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001571 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001572 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001573 static int restart_successful = 0;
1574
1575 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001576 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001577 SLOGE("Encrypted filesystem not validated, aborting");
1578 return -1;
1579 }
1580
1581 if (restart_successful) {
1582 SLOGE("System already restarted with encrypted disk, aborting");
1583 return -1;
1584 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001585
Paul Lawrencef4faa572014-01-29 13:31:03 -08001586 if (restart_main) {
1587 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001588 * start all services in one of these classes: core, early_hal, hal,
1589 * main and late_start. To get to the minimal UI for PIN entry, we
1590 * need to start core, early_hal, hal and main. When we want to
1591 * shutdown the framework again, we need to stop most of the services in
1592 * these classes, but only those services that were started after
1593 * /data was mounted. This excludes critical services like vold and
1594 * ueventd, which need to keep running. We could possible stop
1595 * even fewer services, but because we want services to pick up APEX
1596 * libraries from the real /data, restarting is better, as it makes
1597 * these devices consistent with FBE devices and lets them use the
1598 * most recent code.
1599 *
1600 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001601 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001602 * We then restart the class core, hal, main, and also the class
1603 * late_start.
1604 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001605 * At the moment, I've only put a few things in late_start that I know
1606 * are not needed to bring up the framework, and that also cause problems
1607 * with unmounting the tmpfs /data, but I hope to add add more services
1608 * to the late_start class as we optimize this to decrease the delay
1609 * till the user is asked for the password to the filesystem.
1610 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001611
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001612 /* The init files are setup to stop the right set of services when
1613 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001614 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001615 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001616 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001617
Paul Lawrencef4faa572014-01-29 13:31:03 -08001618 /* Ugh, shutting down the framework is not synchronous, so until it
1619 * can be fixed, this horrible hack will wait a moment for it all to
1620 * shut down before proceeding. Without it, some devices cannot
1621 * restart the graphics services.
1622 */
1623 sleep(2);
1624 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001625
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001626 /* Now that the framework is shutdown, we should be able to umount()
1627 * the tmpfs filesystem, and mount the real one.
1628 */
1629
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001630 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1631 if (strlen(crypto_blkdev) == 0) {
1632 SLOGE("fs_crypto_blkdev not set\n");
1633 return -1;
1634 }
1635
Paul Crowley14c8c072018-09-18 13:30:21 -07001636 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001637 /* If ro.crypto.readonly is set to 1, mount the decrypted
1638 * filesystem readonly. This is used when /data is mounted by
1639 * recovery mode.
1640 */
1641 char ro_prop[PROPERTY_VALUE_MAX];
1642 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001643 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001644 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1645 if (entry != nullptr) {
1646 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001647 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001648 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001649
Ken Sumralle5032c42012-04-01 23:58:44 -07001650 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001651 int retries = RETRY_MOUNT_ATTEMPTS;
1652 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001653
1654 /*
1655 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1656 * partitions in the fsck domain.
1657 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001658 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001659 SLOGE("Failed to setexeccon");
1660 return -1;
1661 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001662 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001663 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001664 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001665 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1666 /* TODO: invoke something similar to
1667 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1668 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001669 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001670 if (--retries) {
1671 sleep(RETRY_MOUNT_DELAY_SECONDS);
1672 } else {
1673 /* Let's hope that a reboot clears away whatever is keeping
1674 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001675 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001676 }
1677 } else {
1678 SLOGE("Failed to mount decrypted data");
1679 cryptfs_set_corrupt();
1680 cryptfs_trigger_restart_min_framework();
1681 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001682 if (setexeccon(NULL)) {
1683 SLOGE("Failed to setexeccon");
1684 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001685 return -1;
1686 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001687 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001688 if (setexeccon(NULL)) {
1689 SLOGE("Failed to setexeccon");
1690 return -1;
1691 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001692
Ken Sumralle5032c42012-04-01 23:58:44 -07001693 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001694 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001695 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001696
1697 /* startup service classes main and late_start */
1698 property_set("vold.decrypt", "trigger_restart_framework");
1699 SLOGD("Just triggered restart_framework\n");
1700
1701 /* Give it a few moments to get started */
1702 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001703 }
1704
Ken Sumrall0cc16632011-01-18 20:32:26 -08001705 if (rc == 0) {
1706 restart_successful = 1;
1707 }
1708
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001709 return rc;
1710}
1711
Paul Crowley14c8c072018-09-18 13:30:21 -07001712int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001713 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001714 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001715 SLOGE("cryptfs_restart not valid for file encryption:");
1716 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001717 }
1718
Paul Lawrencef4faa572014-01-29 13:31:03 -08001719 /* Call internal implementation forcing a restart of main service group */
1720 return cryptfs_restart_internal(1);
1721}
1722
Paul Crowley14c8c072018-09-18 13:30:21 -07001723static int do_crypto_complete(const char* mount_point) {
1724 struct crypt_mnt_ftr crypt_ftr;
1725 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001726
Paul Crowley14c8c072018-09-18 13:30:21 -07001727 property_get("ro.crypto.state", encrypted_state, "");
1728 if (strcmp(encrypted_state, "encrypted")) {
1729 SLOGE("not running with encryption, aborting");
1730 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001731 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001732
Paul Crowley14c8c072018-09-18 13:30:21 -07001733 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001734 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001735 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1736 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001737
Paul Crowley14c8c072018-09-18 13:30:21 -07001738 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001739 std::string key_loc;
1740 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001741
Paul Crowley14c8c072018-09-18 13:30:21 -07001742 /*
1743 * Only report this error if key_loc is a file and it exists.
1744 * If the device was never encrypted, and /data is not mountable for
1745 * some reason, returning 1 should prevent the UI from presenting the
1746 * a "enter password" screen, or worse, a "press button to wipe the
1747 * device" screen.
1748 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001749 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001750 SLOGE("master key file does not exist, aborting");
1751 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1752 } else {
1753 SLOGE("Error getting crypt footer and key\n");
1754 return CRYPTO_COMPLETE_BAD_METADATA;
1755 }
1756 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001757
Paul Crowley14c8c072018-09-18 13:30:21 -07001758 // Test for possible error flags
1759 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1760 SLOGE("Encryption process is partway completed\n");
1761 return CRYPTO_COMPLETE_PARTIAL;
1762 }
1763
1764 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1765 SLOGE("Encryption process was interrupted but cannot continue\n");
1766 return CRYPTO_COMPLETE_INCONSISTENT;
1767 }
1768
1769 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1770 SLOGE("Encryption is successful but data is corrupt\n");
1771 return CRYPTO_COMPLETE_CORRUPT;
1772 }
1773
1774 /* We passed the test! We shall diminish, and return to the west */
1775 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001776}
1777
Paul Crowley14c8c072018-09-18 13:30:21 -07001778static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1779 const char* mount_point, const char* label) {
1780 unsigned char decrypted_master_key[MAX_KEY_LEN];
1781 char crypto_blkdev[MAXPATHLEN];
Tom Cherry4c5bde22019-01-29 14:34:01 -08001782 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001783 char tmp_mount_point[64];
1784 unsigned int orig_failed_decrypt_count;
1785 int rc;
1786 int use_keymaster = 0;
1787 int upgrade = 0;
1788 unsigned char* intermediate_key = 0;
1789 size_t intermediate_key_size = 0;
1790 int N = 1 << crypt_ftr->N_factor;
1791 int r = 1 << crypt_ftr->r_factor;
1792 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001793
Paul Crowley14c8c072018-09-18 13:30:21 -07001794 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1795 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001796
Paul Crowley14c8c072018-09-18 13:30:21 -07001797 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1798 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1799 &intermediate_key_size)) {
1800 SLOGE("Failed to decrypt master key\n");
1801 rc = -1;
1802 goto errout;
1803 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001804 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001805
Tom Cherry4c5bde22019-01-29 14:34:01 -08001806 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001807
Paul Crowley14c8c072018-09-18 13:30:21 -07001808 // Create crypto block device - all (non fatal) code paths
1809 // need it
Tom Cherry4c5bde22019-01-29 14:34:01 -08001810 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
1811 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001812 SLOGE("Error creating decrypted block device\n");
1813 rc = -1;
1814 goto errout;
1815 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001816
Paul Crowley14c8c072018-09-18 13:30:21 -07001817 /* Work out if the problem is the password or the data */
1818 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001819
Paul Crowley14c8c072018-09-18 13:30:21 -07001820 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1821 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1822 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001823
Paul Crowley14c8c072018-09-18 13:30:21 -07001824 // Does the key match the crypto footer?
1825 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1826 sizeof(scrypted_intermediate_key)) == 0) {
1827 SLOGI("Password matches");
1828 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001829 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001830 /* Try mounting the file system anyway, just in case the problem's with
1831 * the footer, not the key. */
1832 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1833 mkdir(tmp_mount_point, 0755);
Tom Cherry4c5bde22019-01-29 14:34:01 -08001834 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001835 SLOGE("Error temp mounting decrypted block device\n");
1836 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001837
Paul Crowley14c8c072018-09-18 13:30:21 -07001838 rc = ++crypt_ftr->failed_decrypt_count;
1839 put_crypt_ftr_and_key(crypt_ftr);
1840 } else {
1841 /* Success! */
1842 SLOGI("Password did not match but decrypted drive mounted - continue");
1843 umount(tmp_mount_point);
1844 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001845 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001846 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001847
Paul Crowley14c8c072018-09-18 13:30:21 -07001848 if (rc == 0) {
1849 crypt_ftr->failed_decrypt_count = 0;
1850 if (orig_failed_decrypt_count != 0) {
1851 put_crypt_ftr_and_key(crypt_ftr);
1852 }
1853
1854 /* Save the name of the crypto block device
1855 * so we can mount it when restarting the framework. */
1856 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1857
1858 /* Also save a the master key so we can reencrypted the key
1859 * the key when we want to change the password on it. */
1860 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1861 saved_mount_point = strdup(mount_point);
1862 master_key_saved = 1;
1863 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1864 rc = 0;
1865
1866 // Upgrade if we're not using the latest KDF.
1867 use_keymaster = keymaster_check_compatibility();
1868 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1869 // Don't allow downgrade
1870 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1871 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1872 upgrade = 1;
1873 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1874 crypt_ftr->kdf_type = KDF_SCRYPT;
1875 upgrade = 1;
1876 }
1877
1878 if (upgrade) {
1879 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1880 crypt_ftr->master_key, crypt_ftr);
1881 if (!rc) {
1882 rc = put_crypt_ftr_and_key(crypt_ftr);
1883 }
1884 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1885
1886 // Do not fail even if upgrade failed - machine is bootable
1887 // Note that if this code is ever hit, there is a *serious* problem
1888 // since KDFs should never fail. You *must* fix the kdf before
1889 // proceeding!
1890 if (rc) {
1891 SLOGW(
1892 "Upgrade failed with error %d,"
1893 " but continuing with previous state",
1894 rc);
1895 rc = 0;
1896 }
1897 }
1898 }
1899
1900errout:
1901 if (intermediate_key) {
1902 memset(intermediate_key, 0, intermediate_key_size);
1903 free(intermediate_key);
1904 }
1905 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001906}
1907
Ken Sumrall29d8da82011-05-18 17:20:07 -07001908/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001909 * Called by vold when it's asked to mount an encrypted external
1910 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001911 * as any metadata is been stored in a separate, small partition. We
1912 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001913 *
1914 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001915 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001916int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
1917 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001918 uint64_t nr_sec = 0;
1919 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001920 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001921 return -1;
1922 }
1923
Jeff Sharkey9c484982015-03-31 10:35:33 -07001924 struct crypt_mnt_ftr ext_crypt_ftr;
1925 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1926 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001927 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001928 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001929 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001930 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001931 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001932 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1933 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001934
Paul Crowley385cb8c2018-03-29 13:27:23 -07001935 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001936}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001937
Jeff Sharkey9c484982015-03-31 10:35:33 -07001938/*
1939 * Called by vold when it's asked to unmount an encrypted external
1940 * storage volume.
1941 */
1942int cryptfs_revert_ext_volume(const char* label) {
David Andersonb9224732019-05-13 13:02:54 -07001943 return delete_crypto_blk_dev(label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001944}
1945
Paul Crowley14c8c072018-09-18 13:30:21 -07001946int cryptfs_crypto_complete(void) {
1947 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001948}
1949
Paul Crowley14c8c072018-09-18 13:30:21 -07001950int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001951 char encrypted_state[PROPERTY_VALUE_MAX];
1952 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001953 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1954 SLOGE(
1955 "encrypted fs already validated or not running with encryption,"
1956 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001957 return -1;
1958 }
1959
1960 if (get_crypt_ftr_and_key(crypt_ftr)) {
1961 SLOGE("Error getting crypt footer and key");
1962 return -1;
1963 }
1964
1965 return 0;
1966}
1967
Paul Crowley14c8c072018-09-18 13:30:21 -07001968int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001969 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001970 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001971 SLOGE("cryptfs_check_passwd not valid for file encryption");
1972 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001973 }
1974
Paul Lawrencef4faa572014-01-29 13:31:03 -08001975 struct crypt_mnt_ftr crypt_ftr;
1976 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001977
Paul Lawrencef4faa572014-01-29 13:31:03 -08001978 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001979 if (rc) {
1980 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001981 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001982 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001983
Paul Crowley14c8c072018-09-18 13:30:21 -07001984 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001985 if (rc) {
1986 SLOGE("Password did not match");
1987 return rc;
1988 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001989
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001990 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1991 // Here we have a default actual password but a real password
1992 // we must test against the scrypted value
1993 // First, we must delete the crypto block device that
1994 // test_mount_encrypted_fs leaves behind as a side effect
1995 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001996 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1997 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001998 if (rc) {
1999 SLOGE("Default password did not match on reboot encryption");
2000 return rc;
2001 }
2002
2003 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2004 put_crypt_ftr_and_key(&crypt_ftr);
2005 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2006 if (rc) {
2007 SLOGE("Could not change password on reboot encryption");
2008 return rc;
2009 }
2010 }
2011
2012 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002013 cryptfs_clear_password();
2014 password = strdup(passwd);
2015 struct timespec now;
2016 clock_gettime(CLOCK_BOOTTIME, &now);
2017 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002018 }
2019
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002020 return rc;
2021}
2022
Paul Crowley14c8c072018-09-18 13:30:21 -07002023int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002024 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002025 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002026 char encrypted_state[PROPERTY_VALUE_MAX];
2027 int rc;
2028
2029 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002030 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002031 SLOGE("device not encrypted, aborting");
2032 return -2;
2033 }
2034
2035 if (!master_key_saved) {
2036 SLOGE("encrypted fs not yet mounted, aborting");
2037 return -1;
2038 }
2039
2040 if (!saved_mount_point) {
2041 SLOGE("encrypted fs failed to save mount point, aborting");
2042 return -1;
2043 }
2044
Ken Sumrall160b4d62013-04-22 12:15:39 -07002045 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002046 SLOGE("Error getting crypt footer and key\n");
2047 return -1;
2048 }
2049
2050 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2051 /* If the device has no password, then just say the password is valid */
2052 rc = 0;
2053 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002054 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002055 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2056 /* They match, the password is correct */
2057 rc = 0;
2058 } else {
2059 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2060 sleep(1);
2061 rc = 1;
2062 }
2063 }
2064
2065 return rc;
2066}
2067
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002068/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002069 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002070 * Presumably, at a minimum, the caller will update the
2071 * filesystem size and crypto_type_name after calling this function.
2072 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002073static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002074 off64_t off;
2075
2076 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002077 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002078 ftr->major_version = CURRENT_MAJOR_VERSION;
2079 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002080 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002081 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002082
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002083 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002084 case 1:
2085 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2086 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002087
Paul Crowley14c8c072018-09-18 13:30:21 -07002088 case 0:
2089 ftr->kdf_type = KDF_SCRYPT;
2090 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002091
Paul Crowley14c8c072018-09-18 13:30:21 -07002092 default:
2093 SLOGE("keymaster_check_compatibility failed");
2094 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002095 }
2096
Kenny Rootc4c70f12013-06-14 12:11:38 -07002097 get_device_scrypt_params(ftr);
2098
Ken Sumrall160b4d62013-04-22 12:15:39 -07002099 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2100 if (get_crypt_ftr_info(NULL, &off) == 0) {
2101 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002102 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002103 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002104
2105 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002106}
2107
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002108#define FRAMEWORK_BOOT_WAIT 60
2109
Paul Crowley14c8c072018-09-18 13:30:21 -07002110static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2111 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002112 if (fd == -1) {
2113 SLOGE("Error opening file %s", filename);
2114 return -1;
2115 }
2116
2117 char block[CRYPT_INPLACE_BUFSIZE];
2118 memset(block, 0, sizeof(block));
2119 if (unix_read(fd, block, sizeof(block)) < 0) {
2120 SLOGE("Error reading file %s", filename);
2121 close(fd);
2122 return -1;
2123 }
2124
2125 close(fd);
2126
2127 SHA256_CTX c;
2128 SHA256_Init(&c);
2129 SHA256_Update(&c, block, sizeof(block));
2130 SHA256_Final(buf, &c);
2131
2132 return 0;
2133}
2134
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002135static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2136 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002137 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002138 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002139
Paul Lawrence87999172014-02-20 12:21:31 -08002140 /* The size of the userdata partition, and add in the vold volumes below */
2141 tot_encryption_size = crypt_ftr->fs_size;
2142
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002143 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002144 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002145
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002146 if (rc == ENABLE_INPLACE_ERR_DEV) {
2147 /* Hack for b/17898962 */
2148 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2149 cryptfs_reboot(RebootType::reboot);
2150 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002151
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002152 if (!rc) {
2153 crypt_ftr->encrypted_upto = cur_encryption_done;
2154 }
Paul Lawrence87999172014-02-20 12:21:31 -08002155
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002156 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2157 /* The inplace routine never actually sets the progress to 100% due
2158 * to the round down nature of integer division, so set it here */
2159 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002160 }
2161
2162 return rc;
2163}
2164
Paul Crowleyb64933a2017-10-31 08:25:55 -07002165static int vold_unmountAll(void) {
2166 VolumeManager* vm = VolumeManager::Instance();
2167 return vm->unmountAll();
2168}
2169
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002170int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002171 char crypto_blkdev[MAXPATHLEN];
2172 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002173 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002174 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002175 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002176 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002177 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002178 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002179 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002180 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002181 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002182 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002183 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002184 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002185
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002186 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002187 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2188 /* An encryption was underway and was interrupted */
2189 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2190 crypt_ftr.encrypted_upto = 0;
2191 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002192
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002193 /* At this point, we are in an inconsistent state. Until we successfully
2194 complete encryption, a reboot will leave us broken. So mark the
2195 encryption failed in case that happens.
2196 On successfully completing encryption, remove this flag */
2197 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002198
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002199 put_crypt_ftr_and_key(&crypt_ftr);
2200 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2201 if (!check_ftr_sha(&crypt_ftr)) {
2202 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2203 put_crypt_ftr_and_key(&crypt_ftr);
2204 goto error_unencrypted;
2205 }
2206
2207 /* Doing a reboot-encryption*/
2208 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2209 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2210 rebootEncryption = true;
2211 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002212 } else {
2213 // We don't want to accidentally reference invalid data.
2214 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002215 }
2216
2217 property_get("ro.crypto.state", encrypted_state, "");
2218 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2219 SLOGE("Device is already running encrypted, aborting");
2220 goto error_unencrypted;
2221 }
2222
Tom Cherry4c5bde22019-01-29 14:34:01 -08002223 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002224
Ken Sumrall3ed82362011-01-28 23:31:16 -08002225 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002226 uint64_t nr_sec;
2227 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002228 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002229 goto error_unencrypted;
2230 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002231
2232 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002233 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002234 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002235 fs_size_sec = get_fs_size(real_blkdev.c_str());
2236 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002237
Paul Lawrence87999172014-02-20 12:21:31 -08002238 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002239
2240 if (fs_size_sec > max_fs_size_sec) {
2241 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2242 goto error_unencrypted;
2243 }
2244 }
2245
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002246 /* Get a wakelock as this may take a while, and we don't want the
2247 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2248 * wants to keep the screen on, it can grab a full wakelock.
2249 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002250 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002251 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002252
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002253 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002254 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002255 */
2256 property_set("vold.decrypt", "trigger_shutdown_framework");
2257 SLOGD("Just asked init to shut down class main\n");
2258
Jeff Sharkey9c484982015-03-31 10:35:33 -07002259 /* Ask vold to unmount all devices that it manages */
2260 if (vold_unmountAll()) {
2261 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002262 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002263
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002264 /* no_ui means we are being called from init, not settings.
2265 Now we always reboot from settings, so !no_ui means reboot
2266 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002267 if (!no_ui) {
2268 /* Try fallback, which is to reboot and try there */
2269 onlyCreateHeader = true;
2270 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2271 if (breadcrumb == 0) {
2272 SLOGE("Failed to create breadcrumb file");
2273 goto error_shutting_down;
2274 }
2275 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002276 }
2277
2278 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002279 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002280 /* Now that /data is unmounted, we need to mount a tmpfs
2281 * /data, set a property saying we're doing inplace encryption,
2282 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002283 */
xzj7e38a3a2018-10-12 10:17:11 +08002284 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002285 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002286 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002287 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002288 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002289 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002290
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002291 /* restart the framework. */
2292 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002293 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002294
Ken Sumrall92736ef2012-10-17 20:57:14 -07002295 /* Ugh, shutting down the framework is not synchronous, so until it
2296 * can be fixed, this horrible hack will wait a moment for it all to
2297 * shut down before proceeding. Without it, some devices cannot
2298 * restart the graphics services.
2299 */
2300 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002301 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002302
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002303 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002304 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002305 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002306 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2307 goto error_shutting_down;
2308 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002309
Tom Cherry4c5bde22019-01-29 14:34:01 -08002310 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002311 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002312 } else {
2313 crypt_ftr.fs_size = nr_sec;
2314 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002315 /* At this point, we are in an inconsistent state. Until we successfully
2316 complete encryption, a reboot will leave us broken. So mark the
2317 encryption failed in case that happens.
2318 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002319 if (onlyCreateHeader) {
2320 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2321 } else {
2322 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2323 }
Paul Lawrence87999172014-02-20 12:21:31 -08002324 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002325 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2326 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002327
Paul Lawrence87999172014-02-20 12:21:31 -08002328 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002329 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2330 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002331 SLOGE("Cannot create encrypted master key\n");
2332 goto error_shutting_down;
2333 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002334
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002335 /* Replace scrypted intermediate key if we are preparing for a reboot */
2336 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002337 unsigned char fake_master_key[MAX_KEY_LEN];
2338 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002339 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002340 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2341 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002342 }
2343
Paul Lawrence87999172014-02-20 12:21:31 -08002344 /* Write the key to the end of the partition */
2345 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002346
Paul Lawrence87999172014-02-20 12:21:31 -08002347 /* If any persistent data has been remembered, save it.
2348 * If none, create a valid empty table and save that.
2349 */
2350 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002351 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2352 if (pdata) {
2353 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2354 persist_data = pdata;
2355 }
Paul Lawrence87999172014-02-20 12:21:31 -08002356 }
2357 if (persist_data) {
2358 save_persistent_data();
2359 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002360 }
2361
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002362 if (onlyCreateHeader) {
2363 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002364 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002365 }
2366
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002367 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002368 /* startup service classes main and late_start */
2369 property_set("vold.decrypt", "trigger_restart_min_framework");
2370 SLOGD("Just triggered restart_min_framework\n");
2371
2372 /* OK, the framework is restarted and will soon be showing a
2373 * progress bar. Time to setup an encrypted mapping, and
2374 * either write a new filesystem, or encrypt in place updating
2375 * the progress bar as we work.
2376 */
2377 }
2378
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002379 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Tom Cherry4c5bde22019-01-29 14:34:01 -08002380 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002381 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002382
Paul Lawrence87999172014-02-20 12:21:31 -08002383 /* If we are continuing, check checksums match */
2384 rc = 0;
2385 if (previously_encrypted_upto) {
2386 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2387 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002388
Paul Crowley14c8c072018-09-18 13:30:21 -07002389 if (!rc &&
2390 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002391 SLOGE("Checksums do not match - trigger wipe");
2392 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002393 }
2394 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002395
Paul Lawrence87999172014-02-20 12:21:31 -08002396 if (!rc) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002397 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002398 previously_encrypted_upto);
2399 }
2400
2401 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002402 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002403 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002404 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002405 SLOGE("Error calculating checksum for continuing encryption");
2406 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002407 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002408 }
2409
2410 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002411 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002412
Paul Crowley14c8c072018-09-18 13:30:21 -07002413 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002414 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002415 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002416
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002417 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002418 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2419 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002420 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002421 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002422
Paul Lawrence6bfed202014-07-28 12:47:22 -07002423 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002424
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002425 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2426 char value[PROPERTY_VALUE_MAX];
2427 property_get("ro.crypto.state", value, "");
2428 if (!strcmp(value, "")) {
2429 /* default encryption - continue first boot sequence */
2430 property_set("ro.crypto.state", "encrypted");
2431 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002432 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002433 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2434 // Bring up cryptkeeper that will check the password and set it
2435 property_set("vold.decrypt", "trigger_shutdown_framework");
2436 sleep(2);
2437 property_set("vold.encrypt_progress", "");
2438 cryptfs_trigger_restart_min_framework();
2439 } else {
2440 cryptfs_check_passwd(DEFAULT_PASSWORD);
2441 cryptfs_restart_internal(1);
2442 }
2443 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002444 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002445 sleep(2); /* Give the UI a chance to show 100% progress */
2446 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002447 }
Paul Lawrence87999172014-02-20 12:21:31 -08002448 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002449 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002450 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002451 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002452 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002453 char value[PROPERTY_VALUE_MAX];
2454
Ken Sumrall319369a2012-06-27 16:30:18 -07002455 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002456 if (!strcmp(value, "1")) {
2457 /* wipe data if encryption failed */
2458 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002459 std::string err;
2460 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002461 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002462 if (!write_bootloader_message(options, &err)) {
2463 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002464 }
Josh Gaofec44372017-08-28 13:22:55 -07002465 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002466 } else {
2467 /* set property to trigger dialog */
2468 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002469 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002470 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002471 }
2472
Ken Sumrall3ed82362011-01-28 23:31:16 -08002473 /* hrm, the encrypt step claims success, but the reboot failed.
2474 * This should not happen.
2475 * Set the property and return. Hope the framework can deal with it.
2476 */
2477 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002478 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002479
2480error_unencrypted:
2481 property_set("vold.encrypt_progress", "error_not_encrypted");
2482 return -1;
2483
2484error_shutting_down:
2485 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2486 * but the framework is stopped and not restarted to show the error, so it's up to
2487 * vold to restart the system.
2488 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002489 SLOGE(
2490 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2491 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002492 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002493
2494 /* shouldn't get here */
2495 property_set("vold.encrypt_progress", "error_shutting_down");
2496 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002497}
2498
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002499int cryptfs_enable(int type, const char* passwd, int no_ui) {
2500 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002501}
2502
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002503int cryptfs_enable_default(int no_ui) {
2504 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002505}
2506
Paul Crowley14c8c072018-09-18 13:30:21 -07002507int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002508 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002509 SLOGE("cryptfs_changepw not valid for file encryption");
2510 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002511 }
2512
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002513 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002514 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002515
2516 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002517 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002518 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002519 return -1;
2520 }
2521
Paul Lawrencef4faa572014-01-29 13:31:03 -08002522 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2523 SLOGE("Invalid crypt_type %d", crypt_type);
2524 return -1;
2525 }
2526
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002527 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002528 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002529 SLOGE("Error getting crypt footer and key");
2530 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002531 }
2532
Paul Lawrencef4faa572014-01-29 13:31:03 -08002533 crypt_ftr.crypt_type = crypt_type;
2534
Paul Crowley14c8c072018-09-18 13:30:21 -07002535 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2536 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002537 if (rc) {
2538 SLOGE("Encrypt master key failed: %d", rc);
2539 return -1;
2540 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002541 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002542 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002543
2544 return 0;
2545}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002546
Rubin Xu85c01f92014-10-13 12:49:54 +01002547static unsigned int persist_get_max_entries(int encrypted) {
2548 struct crypt_mnt_ftr crypt_ftr;
2549 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002550
2551 /* If encrypted, use the values from the crypt_ftr, otherwise
2552 * use the values for the current spec.
2553 */
2554 if (encrypted) {
2555 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002556 /* Something is wrong, assume no space for entries */
2557 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002558 }
2559 dsize = crypt_ftr.persist_data_size;
2560 } else {
2561 dsize = CRYPT_PERSIST_DATA_SIZE;
2562 }
2563
Rubin Xuf83cc612018-10-09 16:13:38 +01002564 if (dsize > sizeof(struct crypt_persist_data)) {
2565 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2566 } else {
2567 return 0;
2568 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002569}
2570
Paul Crowley14c8c072018-09-18 13:30:21 -07002571static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002572 unsigned int i;
2573
2574 if (persist_data == NULL) {
2575 return -1;
2576 }
2577 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2578 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2579 /* We found it! */
2580 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2581 return 0;
2582 }
2583 }
2584
2585 return -1;
2586}
2587
Paul Crowley14c8c072018-09-18 13:30:21 -07002588static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002589 unsigned int i;
2590 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002591 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002592
2593 if (persist_data == NULL) {
2594 return -1;
2595 }
2596
Rubin Xu85c01f92014-10-13 12:49:54 +01002597 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002598
2599 num = persist_data->persist_valid_entries;
2600
2601 for (i = 0; i < num; i++) {
2602 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2603 /* We found an existing entry, update it! */
2604 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2605 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2606 return 0;
2607 }
2608 }
2609
2610 /* We didn't find it, add it to the end, if there is room */
2611 if (persist_data->persist_valid_entries < max_persistent_entries) {
2612 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2613 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2614 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2615 persist_data->persist_valid_entries++;
2616 return 0;
2617 }
2618
2619 return -1;
2620}
2621
Rubin Xu85c01f92014-10-13 12:49:54 +01002622/**
2623 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2624 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2625 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002626int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002627 std::string key_ = key;
2628 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002629
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002630 std::string parsed_field;
2631 unsigned parsed_index;
2632
2633 std::string::size_type split = key_.find_last_of('_');
2634 if (split == std::string::npos) {
2635 parsed_field = key_;
2636 parsed_index = 0;
2637 } else {
2638 parsed_field = key_.substr(0, split);
2639 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002640 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002641
2642 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002643}
2644
2645/*
2646 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2647 * remaining entries starting from index will be deleted.
2648 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2649 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2650 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2651 *
2652 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002653static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002654 unsigned int i;
2655 unsigned int j;
2656 unsigned int num;
2657
2658 if (persist_data == NULL) {
2659 return PERSIST_DEL_KEY_ERROR_OTHER;
2660 }
2661
2662 num = persist_data->persist_valid_entries;
2663
Paul Crowley14c8c072018-09-18 13:30:21 -07002664 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002665 // Filter out to-be-deleted entries in place.
2666 for (i = 0; i < num; i++) {
2667 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2668 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2669 j++;
2670 }
2671 }
2672
2673 if (j < num) {
2674 persist_data->persist_valid_entries = j;
2675 // Zeroise the remaining entries
2676 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2677 return PERSIST_DEL_KEY_OK;
2678 } else {
2679 // Did not find an entry matching the given fieldname
2680 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2681 }
2682}
2683
Paul Crowley14c8c072018-09-18 13:30:21 -07002684static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002685 unsigned int i;
2686 unsigned int count;
2687
2688 if (persist_data == NULL) {
2689 return -1;
2690 }
2691
2692 count = 0;
2693 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2694 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2695 count++;
2696 }
2697 }
2698
2699 return count;
2700}
2701
Ken Sumrall160b4d62013-04-22 12:15:39 -07002702/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002703int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002704 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002705 SLOGE("Cannot get field when file encrypted");
2706 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002707 }
2708
Ken Sumrall160b4d62013-04-22 12:15:39 -07002709 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002710 /* CRYPTO_GETFIELD_OK is success,
2711 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2712 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2713 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002714 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002715 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2716 int i;
2717 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002718
2719 if (persist_data == NULL) {
2720 load_persistent_data();
2721 if (persist_data == NULL) {
2722 SLOGE("Getfield error, cannot load persistent data");
2723 goto out;
2724 }
2725 }
2726
Rubin Xu85c01f92014-10-13 12:49:54 +01002727 // Read value from persistent entries. If the original value is split into multiple entries,
2728 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002729 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002730 // 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 -07002731 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002732 // value too small
2733 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2734 goto out;
2735 }
2736 rc = CRYPTO_GETFIELD_OK;
2737
2738 for (i = 1; /* break explicitly */; i++) {
2739 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002740 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002741 // If the fieldname is very long, we stop as soon as it begins to overflow the
2742 // maximum field length. At this point we have in fact fully read out the original
2743 // value because cryptfs_setfield would not allow fields with longer names to be
2744 // written in the first place.
2745 break;
2746 }
2747 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002748 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2749 // value too small.
2750 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2751 goto out;
2752 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002753 } else {
2754 // Exhaust all entries.
2755 break;
2756 }
2757 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002758 } else {
2759 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002760 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002761 }
2762
2763out:
2764 return rc;
2765}
2766
2767/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002768int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002769 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002770 SLOGE("Cannot set field when file encrypted");
2771 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002772 }
2773
Ken Sumrall160b4d62013-04-22 12:15:39 -07002774 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002775 /* 0 is success, negative values are error */
2776 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002777 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002778 unsigned int field_id;
2779 char temp_field[PROPERTY_KEY_MAX];
2780 unsigned int num_entries;
2781 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002782
2783 if (persist_data == NULL) {
2784 load_persistent_data();
2785 if (persist_data == NULL) {
2786 SLOGE("Setfield error, cannot load persistent data");
2787 goto out;
2788 }
2789 }
2790
2791 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002792 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002793 encrypted = 1;
2794 }
2795
Rubin Xu85c01f92014-10-13 12:49:54 +01002796 // Compute the number of entries required to store value, each entry can store up to
2797 // (PROPERTY_VALUE_MAX - 1) chars
2798 if (strlen(value) == 0) {
2799 // Empty value also needs one entry to store.
2800 num_entries = 1;
2801 } else {
2802 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2803 }
2804
2805 max_keylen = strlen(fieldname);
2806 if (num_entries > 1) {
2807 // Need an extra "_%d" suffix.
2808 max_keylen += 1 + log10(num_entries);
2809 }
2810 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2811 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002812 goto out;
2813 }
2814
Rubin Xu85c01f92014-10-13 12:49:54 +01002815 // Make sure we have enough space to write the new value
2816 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2817 persist_get_max_entries(encrypted)) {
2818 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2819 goto out;
2820 }
2821
2822 // Now that we know persist_data has enough space for value, let's delete the old field first
2823 // to make up space.
2824 persist_del_keys(fieldname, 0);
2825
2826 if (persist_set_key(fieldname, value, encrypted)) {
2827 // fail to set key, should not happen as we have already checked the available space
2828 SLOGE("persist_set_key() error during setfield()");
2829 goto out;
2830 }
2831
2832 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002833 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002834
2835 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2836 // fail to set key, should not happen as we have already checked the available space.
2837 SLOGE("persist_set_key() error during setfield()");
2838 goto out;
2839 }
2840 }
2841
Ken Sumrall160b4d62013-04-22 12:15:39 -07002842 /* If we are running encrypted, save the persistent data now */
2843 if (encrypted) {
2844 if (save_persistent_data()) {
2845 SLOGE("Setfield error, cannot save persistent data");
2846 goto out;
2847 }
2848 }
2849
Rubin Xu85c01f92014-10-13 12:49:54 +01002850 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002851
2852out:
2853 return rc;
2854}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002855
2856/* Checks userdata. Attempt to mount the volume if default-
2857 * encrypted.
2858 * On success trigger next init phase and return 0.
2859 * Currently do not handle failure - see TODO below.
2860 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002861int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002862 int crypt_type = cryptfs_get_password_type();
2863 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2864 SLOGE("Bad crypt type - error");
2865 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002866 SLOGD(
2867 "Password is not default - "
2868 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002869 property_set("vold.decrypt", "trigger_restart_min_framework");
2870 return 0;
2871 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2872 SLOGD("Password is default - restarting filesystem");
2873 cryptfs_restart_internal(0);
2874 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002875 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002876 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002877 }
2878
Paul Lawrence6bfed202014-07-28 12:47:22 -07002879 /** Corrupt. Allow us to boot into framework, which will detect bad
2880 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002881 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002882 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002883 return 0;
2884}
2885
2886/* Returns type of the password, default, pattern, pin or password.
2887 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002888int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002889 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002890 SLOGE("cryptfs_get_password_type not valid for file encryption");
2891 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002892 }
2893
Paul Lawrencef4faa572014-01-29 13:31:03 -08002894 struct crypt_mnt_ftr crypt_ftr;
2895
2896 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2897 SLOGE("Error getting crypt footer and key\n");
2898 return -1;
2899 }
2900
Paul Lawrence6bfed202014-07-28 12:47:22 -07002901 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2902 return -1;
2903 }
2904
Paul Lawrencef4faa572014-01-29 13:31:03 -08002905 return crypt_ftr.crypt_type;
2906}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002907
Paul Crowley14c8c072018-09-18 13:30:21 -07002908const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002909 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002910 SLOGE("cryptfs_get_password not valid for file encryption");
2911 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002912 }
2913
Paul Lawrence399317e2014-03-10 13:20:50 -07002914 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002915 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002916 if (now.tv_sec < password_expiry_time) {
2917 return password;
2918 } else {
2919 cryptfs_clear_password();
2920 return 0;
2921 }
2922}
2923
Paul Crowley14c8c072018-09-18 13:30:21 -07002924void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002925 if (password) {
2926 size_t len = strlen(password);
2927 memset(password, 0, len);
2928 free(password);
2929 password = 0;
2930 password_expiry_time = 0;
2931 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002932}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002933
Paul Crowley14c8c072018-09-18 13:30:21 -07002934int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002935 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2936 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002937}