blob: c3d5f787d0f47f0509c7a25930f352714914faae [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;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080074using android::vold::KeyBuffer;
David Andersonb9224732019-05-13 13:02:54 -070075using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070076using namespace std::chrono_literals;
77
Paul Crowley73be12d2020-02-03 12:22:03 -080078/* The current cryptfs version */
79#define CURRENT_MAJOR_VERSION 1
80#define CURRENT_MINOR_VERSION 3
81
82#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
83#define CRYPT_PERSIST_DATA_SIZE 0x1000
84
85#define MAX_CRYPTO_TYPE_NAME_LEN 64
86
87#define MAX_KEY_LEN 48
88#define SALT_LEN 16
89#define SCRYPT_LEN 32
90
91/* definitions of flags in the structure below */
92#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
93#define CRYPT_ENCRYPTION_IN_PROGRESS \
94 0x2 /* Encryption partially completed, \
95 encrypted_upto valid*/
96#define CRYPT_INCONSISTENT_STATE \
97 0x4 /* Set when starting encryption, clear when \
98 exit cleanly, either through success or \
99 correctly marked partial encryption */
100#define CRYPT_DATA_CORRUPT \
101 0x8 /* Set when encryption is fine, but the \
102 underlying volume is corrupt */
103#define CRYPT_FORCE_ENCRYPTION \
104 0x10 /* Set when it is time to encrypt this \
105 volume on boot. Everything in this \
106 structure is set up correctly as \
107 though device is encrypted except \
108 that the master key is encrypted with the \
109 default password. */
110#define CRYPT_FORCE_COMPLETE \
111 0x20 /* Set when the above encryption cycle is \
112 complete. On next cryptkeeper entry, match \
113 the password. If it matches fix the master \
114 key and remove this flag. */
115
116/* Allowed values for type in the structure below */
117#define CRYPT_TYPE_PASSWORD \
118 0 /* master_key is encrypted with a password \
119 * Must be zero to be compatible with pre-L \
120 * devices where type is always password.*/
121#define CRYPT_TYPE_DEFAULT \
122 1 /* master_key is encrypted with default \
123 * password */
124#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
125#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
126#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
127
128#define CRYPT_MNT_MAGIC 0xD0B5B1C4
129#define PERSIST_DATA_MAGIC 0xE950CD44
130
131/* Key Derivation Function algorithms */
132#define KDF_PBKDF2 1
133#define KDF_SCRYPT 2
134/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
135#define KDF_SCRYPT_KEYMASTER 5
136
137/* Maximum allowed keymaster blob size. */
138#define KEYMASTER_BLOB_SIZE 2048
139
140/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
141#define __le8 unsigned char
142
143#if !defined(SHA256_DIGEST_LENGTH)
144#define SHA256_DIGEST_LENGTH 32
145#endif
146
147/* This structure starts 16,384 bytes before the end of a hardware
148 * partition that is encrypted, or in a separate partition. It's location
149 * is specified by a property set in init.<device>.rc.
150 * The structure allocates 48 bytes for a key, but the real key size is
151 * specified in the struct. Currently, the code is hardcoded to use 128
152 * bit keys.
153 * The fields after salt are only valid in rev 1.1 and later stuctures.
154 * Obviously, the filesystem does not include the last 16 kbytes
155 * of the partition if the crypt_mnt_ftr lives at the end of the
156 * partition.
157 */
158
159struct crypt_mnt_ftr {
160 __le32 magic; /* See above */
161 __le16 major_version;
162 __le16 minor_version;
163 __le32 ftr_size; /* in bytes, not including key following */
164 __le32 flags; /* See above */
165 __le32 keysize; /* in bytes */
166 __le32 crypt_type; /* how master_key is encrypted. Must be a
167 * CRYPT_TYPE_XXX value */
168 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
169 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
170 mount, set to 0 on successful mount */
171 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
172 needed to decrypt this
173 partition, null terminated */
174 __le32 spare2; /* ignored */
175 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
176 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
177 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
178 * on device with that info, either the footer of the
179 * real_blkdevice or the metadata partition. */
180
181 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
182 * persistent data table*/
183
184 __le8 kdf_type; /* The key derivation function used. */
185
186 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
187 __le8 N_factor; /* (1 << N) */
188 __le8 r_factor; /* (1 << r) */
189 __le8 p_factor; /* (1 << p) */
190 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
191 we have to stop (e.g. power low) this is the last
192 encrypted 512 byte sector.*/
193 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
194 set, hash of first block, used
195 to validate before continuing*/
196
197 /* key_master key, used to sign the derived key which is then used to generate
198 * the intermediate key
199 * This key should be used for no other purposes! We use this key to sign unpadded
200 * data, which is acceptable but only if the key is not reused elsewhere. */
201 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
202 __le32 keymaster_blob_size;
203
204 /* Store scrypt of salted intermediate key. When decryption fails, we can
205 check if this matches, and if it does, we know that the problem is with the
206 drive, and there is no point in asking the user for more passwords.
207
208 Note that if any part of this structure is corrupt, this will not match and
209 we will continue to believe the user entered the wrong password. In that
210 case the only solution is for the user to enter a password enough times to
211 force a wipe.
212
213 Note also that there is no need to worry about migration. If this data is
214 wrong, we simply won't recognise a right password, and will continue to
215 prompt. On the first password change, this value will be populated and
216 then we will be OK.
217 */
218 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
219
220 /* sha of this structure with this element set to zero
221 Used when encrypting on reboot to validate structure before doing something
222 fatal
223 */
224 unsigned char sha256[SHA256_DIGEST_LENGTH];
225};
226
227/* Persistant data that should be available before decryption.
228 * Things like airplane mode, locale and timezone are kept
229 * here and can be retrieved by the CryptKeeper UI to properly
230 * configure the phone before asking for the password
231 * This is only valid if the major and minor version above
232 * is set to 1.1 or higher.
233 *
234 * This is a 4K structure. There are 2 copies, and the code alternates
235 * writing one and then clearing the previous one. The reading
236 * code reads the first valid copy it finds, based on the magic number.
237 * The absolute offset to the first of the two copies is kept in rev 1.1
238 * and higher crypt_mnt_ftr structures.
239 */
240struct crypt_persist_entry {
241 char key[PROPERTY_KEY_MAX];
242 char val[PROPERTY_VALUE_MAX];
243};
244
245/* Should be exactly 4K in size */
246struct crypt_persist_data {
247 __le32 persist_magic;
248 __le32 persist_valid_entries;
249 __le32 persist_spare[30];
250 struct crypt_persist_entry persist_entry[0];
251};
252
253static int wait_and_unmount(const char* mountpoint, bool kill);
254
255typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
256 void* params);
257
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800258#define UNUSED __attribute__((unused))
259
Jason parks70a4b3f2011-01-28 10:10:47 -0600260#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800261
262constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
263constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700264constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800265
266// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700267static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600268
Paul Crowley14c8c072018-09-18 13:30:21 -0700269#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700270
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700271#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800272
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800273#define CRYPTO_BLOCK_DEVICE "userdata"
274
275#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
276
Ken Sumrall29d8da82011-05-18 17:20:07 -0700277#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700278#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700279
Ken Sumralle919efe2012-09-29 17:07:41 -0700280#define TABLE_LOAD_RETRIES 10
281
Shawn Willden47ba10d2014-09-03 17:07:06 -0600282#define RSA_KEY_SIZE 2048
283#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
284#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600285#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700286
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700287#define RETRY_MOUNT_ATTEMPTS 10
288#define RETRY_MOUNT_DELAY_SECONDS 1
289
Paul Crowley5afbc622017-11-27 09:42:17 -0800290#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
291
Paul Crowley73473332017-11-21 15:43:51 -0800292static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
293
Greg Kaiser59ad0182018-02-16 13:01:36 -0800294static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700295static char* saved_mount_point;
296static int master_key_saved = 0;
297static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800298
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700299/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700300static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000301 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700302}
303
304/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700305static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800306 if (ftr->keymaster_blob_size) {
307 SLOGI("Already have key");
308 return 0;
309 }
310
Paul Crowley14c8c072018-09-18 13:30:21 -0700311 int rc = keymaster_create_key_for_cryptfs_scrypt(
312 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
313 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000314 if (rc) {
315 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800316 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000317 ftr->keymaster_blob_size = 0;
318 }
319 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700320 return -1;
321 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000322 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700323}
324
Shawn Willdene17a9c42014-09-08 13:04:08 -0600325/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700326static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
327 const size_t object_size, unsigned char** signature,
328 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600329 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600330 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600331 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600332
Shawn Willdene17a9c42014-09-08 13:04:08 -0600333 // To sign a message with RSA, the message must satisfy two
334 // constraints:
335 //
336 // 1. The message, when interpreted as a big-endian numeric value, must
337 // be strictly less than the public modulus of the RSA key. Note
338 // that because the most significant bit of the public modulus is
339 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
340 // key), an n-bit message with most significant bit 0 always
341 // satisfies this requirement.
342 //
343 // 2. The message must have the same length in bits as the public
344 // modulus of the RSA key. This requirement isn't mathematically
345 // necessary, but is necessary to ensure consistency in
346 // implementations.
347 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600348 case KDF_SCRYPT_KEYMASTER:
349 // This ensures the most significant byte of the signed message
350 // is zero. We could have zero-padded to the left instead, but
351 // this approach is slightly more robust against changes in
352 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600353 // so) because we really should be using a proper deterministic
354 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800355 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600356 SLOGI("Signing safely-padded object");
357 break;
358 default:
359 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000360 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600361 }
Paul Crowley73473332017-11-21 15:43:51 -0800362 for (;;) {
363 auto result = keymaster_sign_object_for_cryptfs_scrypt(
364 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
365 to_sign_size, signature, signature_size);
366 switch (result) {
367 case KeymasterSignResult::ok:
368 return 0;
369 case KeymasterSignResult::upgrade:
370 break;
371 default:
372 return -1;
373 }
374 SLOGD("Upgrading key");
375 if (keymaster_upgrade_key_for_cryptfs_scrypt(
376 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
377 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
378 &ftr->keymaster_blob_size) != 0) {
379 SLOGE("Failed to upgrade key");
380 return -1;
381 }
382 if (put_crypt_ftr_and_key(ftr) != 0) {
383 SLOGE("Failed to write upgraded key to disk");
384 }
385 SLOGD("Key upgraded successfully");
386 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600387}
388
Paul Lawrence399317e2014-03-10 13:20:50 -0700389/* Store password when userdata is successfully decrypted and mounted.
390 * Cleared by cryptfs_clear_password
391 *
392 * To avoid a double prompt at boot, we need to store the CryptKeeper
393 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
394 * Since the entire framework is torn down and rebuilt after encryption,
395 * we have to use a daemon or similar to store the password. Since vold
396 * is secured against IPC except from system processes, it seems a reasonable
397 * place to store this.
398 *
399 * password should be cleared once it has been used.
400 *
401 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800402 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700403static char* password = 0;
404static int password_expiry_time = 0;
405static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800406
Paul Crowley14c8c072018-09-18 13:30:21 -0700407enum class RebootType { reboot, recovery, shutdown };
408static void cryptfs_reboot(RebootType rt) {
409 switch (rt) {
410 case RebootType::reboot:
411 property_set(ANDROID_RB_PROPERTY, "reboot");
412 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800413
Paul Crowley14c8c072018-09-18 13:30:21 -0700414 case RebootType::recovery:
415 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
416 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800417
Paul Crowley14c8c072018-09-18 13:30:21 -0700418 case RebootType::shutdown:
419 property_set(ANDROID_RB_PROPERTY, "shutdown");
420 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700421 }
Paul Lawrence87999172014-02-20 12:21:31 -0800422
Ken Sumralladfba362013-06-04 16:37:52 -0700423 sleep(20);
424
425 /* Shouldn't get here, reboot should happen before sleep times out */
426 return;
427}
428
Greg Kaiser38723f22018-02-16 13:35:35 -0800429namespace {
430
431struct CryptoType;
432
433// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700434const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800435
436struct CryptoType {
437 // We should only be constructing CryptoTypes as part of
438 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
439 // which isn't pure or fully protected as a concession to being able to
440 // do it all at compile time. Add new CryptoTypes in
441 // supported_crypto_types[] below.
442 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
Paul Crowleya661fb62020-02-11 16:21:54 -0800443 constexpr CryptoType set_keysize(size_t keysize) const {
444 return CryptoType(this->config_name, this->kernel_name, keysize);
Greg Kaiser38723f22018-02-16 13:35:35 -0800445 }
Paul Crowleya661fb62020-02-11 16:21:54 -0800446 constexpr CryptoType set_config_name(const char* config_name) const {
447 return CryptoType(config_name, this->kernel_name, this->keysize);
Greg Kaiser38723f22018-02-16 13:35:35 -0800448 }
Paul Crowleya661fb62020-02-11 16:21:54 -0800449 constexpr CryptoType set_kernel_name(const char* kernel_name) const {
450 return CryptoType(this->config_name, kernel_name, this->keysize);
Greg Kaiser38723f22018-02-16 13:35:35 -0800451 }
452
Paul Crowleya661fb62020-02-11 16:21:54 -0800453 constexpr const char* get_config_name() const { return config_name; }
454 constexpr const char* get_kernel_name() const { return kernel_name; }
455 constexpr size_t get_keysize() const { return keysize; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800456
Paul Crowley14c8c072018-09-18 13:30:21 -0700457 private:
Paul Crowleya661fb62020-02-11 16:21:54 -0800458 const char* config_name;
459 const char* kernel_name;
460 size_t keysize;
Greg Kaiser38723f22018-02-16 13:35:35 -0800461
Paul Crowleya661fb62020-02-11 16:21:54 -0800462 constexpr CryptoType(const char* config, const char* crypto, size_t ksize)
463 : config_name(config), kernel_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700464 friend const CryptoType& get_crypto_type();
465 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800466};
467
468// We only want to parse this read-only property once. But we need to wait
469// until the system is initialized before we can read it. So we use a static
470// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700471const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800472 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
473 return crypto_type;
474}
475
476constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowleya661fb62020-02-11 16:21:54 -0800477 .set_config_name("AES-128-CBC")
478 .set_kernel_name("aes-cbc-essiv:sha256")
479 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800480
481constexpr CryptoType supported_crypto_types[] = {
Paul Crowleya661fb62020-02-11 16:21:54 -0800482 default_crypto_type,
483 CryptoType()
484 .set_config_name("adiantum")
485 .set_kernel_name("xchacha12,aes-adiantum-plain64")
486 .set_keysize(32),
487 // Add new CryptoTypes here. Order is not important.
Greg Kaiser38723f22018-02-16 13:35:35 -0800488};
489
Greg Kaiser38723f22018-02-16 13:35:35 -0800490// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
491// We confirm all supported_crypto_types have a small enough keysize and
Paul Crowleya661fb62020-02-11 16:21:54 -0800492// had both set_config_name() and set_kernel_name() called.
Greg Kaiser38723f22018-02-16 13:35:35 -0800493
494template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700495constexpr size_t array_length(T (&)[N]) {
496 return N;
497}
Greg Kaiser38723f22018-02-16 13:35:35 -0800498
499constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
500 return (index >= array_length(supported_crypto_types));
501}
502
Paul Crowley14c8c072018-09-18 13:30:21 -0700503constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Paul Crowleya661fb62020-02-11 16:21:54 -0800504 return ((crypto_type.get_config_name() != nullptr) &&
505 (crypto_type.get_kernel_name() != nullptr) &&
Greg Kaiser38723f22018-02-16 13:35:35 -0800506 (crypto_type.get_keysize() <= MAX_KEY_LEN));
507}
508
509// Note in C++11 that constexpr functions can only have a single line.
510// So our code is a bit convoluted (using recursion instead of a loop),
511// but it's asserting at compile time that all of our key lengths are valid.
512constexpr bool validateSupportedCryptoTypes(size_t index) {
513 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700514 (isValidCryptoType(supported_crypto_types[index]) &&
515 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800516}
517
518static_assert(validateSupportedCryptoTypes(0),
519 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
520 "incompletely constructed.");
521// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
522
Greg Kaiser38723f22018-02-16 13:35:35 -0800523// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700524const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800525 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
526 char paramstr[PROPERTY_VALUE_MAX];
527
Paul Crowleya661fb62020-02-11 16:21:54 -0800528 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_config_name());
Paul Crowley14c8c072018-09-18 13:30:21 -0700529 for (auto const& ctype : supported_crypto_types) {
Paul Crowleya661fb62020-02-11 16:21:54 -0800530 if (strcmp(paramstr, ctype.get_config_name()) == 0) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800531 return ctype;
532 }
533 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700534 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
Paul Crowleya661fb62020-02-11 16:21:54 -0800535 default_crypto_type.get_config_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800536 return default_crypto_type;
537}
538
539} // namespace
540
Kenny Rootc4c70f12013-06-14 12:11:38 -0700541/**
542 * Gets the default device scrypt parameters for key derivation time tuning.
543 * The parameters should lead to about one second derivation time for the
544 * given device.
545 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700546static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700547 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000548 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700549
Paul Crowley63c18d32016-02-10 14:02:47 +0000550 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
551 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
552 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
553 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700554 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000555 ftr->N_factor = Nf;
556 ftr->r_factor = rf;
557 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700558}
559
Paul Crowleya661fb62020-02-11 16:21:54 -0800560size_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800561 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800562}
563
Paul Crowleya661fb62020-02-11 16:21:54 -0800564const char* cryptfs_get_kernel_name() {
565 return get_crypto_type().get_kernel_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800566}
567
Tom Cherry4c5bde22019-01-29 14:34:01 -0800568static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800569 int fd, block_size;
570 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200571 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800572
Paul Crowley14c8c072018-09-18 13:30:21 -0700573 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800574 SLOGE("Cannot open device to get filesystem size ");
575 return 0;
576 }
577
578 if (lseek64(fd, 1024, SEEK_SET) < 0) {
579 SLOGE("Cannot seek to superblock");
580 return 0;
581 }
582
583 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
584 SLOGE("Cannot read superblock");
585 return 0;
586 }
587
588 close(fd);
589
Daniel Rosenberge82df162014-08-15 22:19:23 +0000590 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
591 SLOGE("Not a valid ext4 superblock");
592 return 0;
593 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800594 block_size = 1024 << sb.s_log_block_size;
595 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200596 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800597
598 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200599 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800600}
601
Tom Cherry4c5bde22019-01-29 14:34:01 -0800602static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
603 for (const auto& entry : fstab_default) {
604 if (!entry.fs_mgr_flags.vold_managed &&
605 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
606 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
607 if (key_loc != nullptr) {
608 *key_loc = entry.key_loc;
609 }
610 if (real_blk_device != nullptr) {
611 *real_blk_device = entry.blk_device;
612 }
613 return;
614 }
615 }
616}
617
Paul Crowley14c8c072018-09-18 13:30:21 -0700618static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
619 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200620 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700621 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700622 char key_loc[PROPERTY_VALUE_MAX];
623 char real_blkdev[PROPERTY_VALUE_MAX];
624 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700625
Paul Crowley14c8c072018-09-18 13:30:21 -0700626 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800627 std::string key_loc;
628 std::string real_blkdev;
629 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700630
Tom Cherry4c5bde22019-01-29 14:34:01 -0800631 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200632 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700633 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
634 * encryption info footer and key, and plenty of bytes to spare for future
635 * growth.
636 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800637 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200638 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700639 cached_data = 1;
640 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800641 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700642 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700643 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800644 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700645 cached_off = 0;
646 cached_data = 1;
647 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700648 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700649
Paul Crowley14c8c072018-09-18 13:30:21 -0700650 if (cached_data) {
651 if (metadata_fname) {
652 *metadata_fname = cached_metadata_fname;
653 }
654 if (off) {
655 *off = cached_off;
656 }
657 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700658 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700659
Paul Crowley14c8c072018-09-18 13:30:21 -0700660 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700661}
662
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800663/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700664static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800665 SHA256_CTX c;
666 SHA256_Init(&c);
667 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
668 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
669 SHA256_Final(crypt_ftr->sha256, &c);
670}
671
Ken Sumralle8744072011-01-18 22:01:55 -0800672/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800673 * update the failed mount count but not change the key.
674 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700675static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
676 int fd;
677 unsigned int cnt;
678 /* starting_off is set to the SEEK_SET offset
679 * where the crypto structure starts
680 */
681 off64_t starting_off;
682 int rc = -1;
683 char* fname = NULL;
684 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800685
Paul Crowley14c8c072018-09-18 13:30:21 -0700686 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800687
Paul Crowley14c8c072018-09-18 13:30:21 -0700688 if (get_crypt_ftr_info(&fname, &starting_off)) {
689 SLOGE("Unable to get crypt_ftr_info\n");
690 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800691 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700692 if (fname[0] != '/') {
693 SLOGE("Unexpected value for crypto key location\n");
694 return -1;
695 }
696 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
697 SLOGE("Cannot open footer file %s for put\n", fname);
698 return -1;
699 }
Ken Sumralle8744072011-01-18 22:01:55 -0800700
Paul Crowley14c8c072018-09-18 13:30:21 -0700701 /* Seek to the start of the crypt footer */
702 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
703 SLOGE("Cannot seek to real block device footer\n");
704 goto errout;
705 }
706
707 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
708 SLOGE("Cannot write real block device footer\n");
709 goto errout;
710 }
711
712 fstat(fd, &statbuf);
713 /* If the keys are kept on a raw block device, do not try to truncate it. */
714 if (S_ISREG(statbuf.st_mode)) {
715 if (ftruncate(fd, 0x4000)) {
716 SLOGE("Cannot set footer file size\n");
717 goto errout;
718 }
719 }
720
721 /* Success! */
722 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800723
724errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700725 close(fd);
726 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800727}
728
Paul Crowley14c8c072018-09-18 13:30:21 -0700729static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800730 struct crypt_mnt_ftr copy;
731 memcpy(&copy, crypt_ftr, sizeof(copy));
732 set_ftr_sha(&copy);
733 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
734}
735
Paul Crowley14c8c072018-09-18 13:30:21 -0700736static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737 return TEMP_FAILURE_RETRY(read(fd, buff, len));
738}
739
Paul Crowley14c8c072018-09-18 13:30:21 -0700740static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700741 return TEMP_FAILURE_RETRY(write(fd, buff, len));
742}
743
Paul Crowley14c8c072018-09-18 13:30:21 -0700744static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700745 memset(pdata, 0, len);
746 pdata->persist_magic = PERSIST_DATA_MAGIC;
747 pdata->persist_valid_entries = 0;
748}
749
750/* A routine to update the passed in crypt_ftr to the lastest version.
751 * fd is open read/write on the device that holds the crypto footer and persistent
752 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
753 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
754 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700755static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700756 int orig_major = crypt_ftr->major_version;
757 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700758
Kenny Root7434b312013-06-14 11:29:53 -0700759 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700760 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700761 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700762
Kenny Rootc4c70f12013-06-14 12:11:38 -0700763 SLOGW("upgrading crypto footer to 1.1");
764
Paul Crowley14c8c072018-09-18 13:30:21 -0700765 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700766 if (pdata == NULL) {
767 SLOGE("Cannot allocate persisent data\n");
768 return;
769 }
770 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
771
772 /* Need to initialize the persistent data area */
773 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
774 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100775 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700776 return;
777 }
778 /* Write all zeros to the first copy, making it invalid */
779 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
780
781 /* Write a valid but empty structure to the second copy */
782 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
783 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
784
785 /* Update the footer */
786 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
787 crypt_ftr->persist_data_offset[0] = pdata_offset;
788 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
789 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100790 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700791 }
792
Paul Lawrencef4faa572014-01-29 13:31:03 -0800793 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700794 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800795 /* But keep the old kdf_type.
796 * It will get updated later to KDF_SCRYPT after the password has been verified.
797 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700798 crypt_ftr->kdf_type = KDF_PBKDF2;
799 get_device_scrypt_params(crypt_ftr);
800 crypt_ftr->minor_version = 2;
801 }
802
Paul Lawrencef4faa572014-01-29 13:31:03 -0800803 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
804 SLOGW("upgrading crypto footer to 1.3");
805 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
806 crypt_ftr->minor_version = 3;
807 }
808
Kenny Root7434b312013-06-14 11:29:53 -0700809 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
810 if (lseek64(fd, offset, SEEK_SET) == -1) {
811 SLOGE("Cannot seek to crypt footer\n");
812 return;
813 }
814 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700816}
817
Paul Crowley14c8c072018-09-18 13:30:21 -0700818static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
819 int fd;
820 unsigned int cnt;
821 off64_t starting_off;
822 int rc = -1;
823 char* fname = NULL;
824 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700825
Paul Crowley14c8c072018-09-18 13:30:21 -0700826 if (get_crypt_ftr_info(&fname, &starting_off)) {
827 SLOGE("Unable to get crypt_ftr_info\n");
828 return -1;
829 }
830 if (fname[0] != '/') {
831 SLOGE("Unexpected value for crypto key location\n");
832 return -1;
833 }
834 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
835 SLOGE("Cannot open footer file %s for get\n", fname);
836 return -1;
837 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800838
Paul Crowley14c8c072018-09-18 13:30:21 -0700839 /* Make sure it's 16 Kbytes in length */
840 fstat(fd, &statbuf);
841 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
842 SLOGE("footer file %s is not the expected size!\n", fname);
843 goto errout;
844 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700845
Paul Crowley14c8c072018-09-18 13:30:21 -0700846 /* Seek to the start of the crypt footer */
847 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
848 SLOGE("Cannot seek to real block device footer\n");
849 goto errout;
850 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700851
Paul Crowley14c8c072018-09-18 13:30:21 -0700852 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
853 SLOGE("Cannot read real block device footer\n");
854 goto errout;
855 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800856
Paul Crowley14c8c072018-09-18 13:30:21 -0700857 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
858 SLOGE("Bad magic for real block device %s\n", fname);
859 goto errout;
860 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800861
Paul Crowley14c8c072018-09-18 13:30:21 -0700862 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
863 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
864 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
865 goto errout;
866 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800867
Paul Crowley14c8c072018-09-18 13:30:21 -0700868 // We risk buffer overflows with oversized keys, so we just reject them.
869 // 0-sized keys are problematic (essentially by-passing encryption), and
870 // AES-CBC key wrapping only works for multiples of 16 bytes.
871 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
872 (crypt_ftr->keysize > MAX_KEY_LEN)) {
873 SLOGE(
874 "Invalid keysize (%u) for block device %s; Must be non-zero, "
875 "divisible by 16, and <= %d\n",
876 crypt_ftr->keysize, fname, MAX_KEY_LEN);
877 goto errout;
878 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800879
Paul Crowley14c8c072018-09-18 13:30:21 -0700880 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
881 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
882 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
883 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800884
Paul Crowley14c8c072018-09-18 13:30:21 -0700885 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
886 * copy on disk before returning.
887 */
888 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
889 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
890 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800891
Paul Crowley14c8c072018-09-18 13:30:21 -0700892 /* Success! */
893 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800894
895errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700896 close(fd);
897 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800898}
899
Paul Crowley14c8c072018-09-18 13:30:21 -0700900static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700901 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
902 crypt_ftr->persist_data_offset[1]) {
903 SLOGE("Crypt_ftr persist data regions overlap");
904 return -1;
905 }
906
907 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
908 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
909 return -1;
910 }
911
912 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700913 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700914 CRYPT_FOOTER_OFFSET) {
915 SLOGE("Persistent data extends past crypto footer");
916 return -1;
917 }
918
919 return 0;
920}
921
Paul Crowley14c8c072018-09-18 13:30:21 -0700922static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700923 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700924 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700925 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700926 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700927 int found = 0;
928 int fd;
929 int ret;
930 int i;
931
932 if (persist_data) {
933 /* Nothing to do, we've already loaded or initialized it */
934 return 0;
935 }
936
Ken Sumrall160b4d62013-04-22 12:15:39 -0700937 /* If not encrypted, just allocate an empty table and initialize it */
938 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700939 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800940 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700941 if (pdata) {
942 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
943 persist_data = pdata;
944 return 0;
945 }
946 return -1;
947 }
948
Paul Crowley14c8c072018-09-18 13:30:21 -0700949 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700950 return -1;
951 }
952
Paul Crowley14c8c072018-09-18 13:30:21 -0700953 if ((crypt_ftr.major_version < 1) ||
954 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700955 SLOGE("Crypt_ftr version doesn't support persistent data");
956 return -1;
957 }
958
959 if (get_crypt_ftr_info(&fname, NULL)) {
960 return -1;
961 }
962
963 ret = validate_persistent_data_storage(&crypt_ftr);
964 if (ret) {
965 return -1;
966 }
967
Paul Crowley14c8c072018-09-18 13:30:21 -0700968 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700969 if (fd < 0) {
970 SLOGE("Cannot open %s metadata file", fname);
971 return -1;
972 }
973
Wei Wang4375f1b2017-02-24 17:43:01 -0800974 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800975 if (pdata == NULL) {
976 SLOGE("Cannot allocate memory for persistent data");
977 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700978 }
979
980 for (i = 0; i < 2; i++) {
981 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
982 SLOGE("Cannot seek to read persistent data on %s", fname);
983 goto err2;
984 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700985 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700986 SLOGE("Error reading persistent data on iteration %d", i);
987 goto err2;
988 }
989 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
990 found = 1;
991 break;
992 }
993 }
994
995 if (!found) {
996 SLOGI("Could not find valid persistent data, creating");
997 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
998 }
999
1000 /* Success */
1001 persist_data = pdata;
1002 close(fd);
1003 return 0;
1004
1005err2:
1006 free(pdata);
1007
1008err:
1009 close(fd);
1010 return -1;
1011}
1012
Paul Crowley14c8c072018-09-18 13:30:21 -07001013static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001014 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001015 struct crypt_persist_data* pdata;
1016 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001017 off64_t write_offset;
1018 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001019 int fd;
1020 int ret;
1021
1022 if (persist_data == NULL) {
1023 SLOGE("No persistent data to save");
1024 return -1;
1025 }
1026
Paul Crowley14c8c072018-09-18 13:30:21 -07001027 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001028 return -1;
1029 }
1030
Paul Crowley14c8c072018-09-18 13:30:21 -07001031 if ((crypt_ftr.major_version < 1) ||
1032 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001033 SLOGE("Crypt_ftr version doesn't support persistent data");
1034 return -1;
1035 }
1036
1037 ret = validate_persistent_data_storage(&crypt_ftr);
1038 if (ret) {
1039 return -1;
1040 }
1041
1042 if (get_crypt_ftr_info(&fname, NULL)) {
1043 return -1;
1044 }
1045
Paul Crowley14c8c072018-09-18 13:30:21 -07001046 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001047 if (fd < 0) {
1048 SLOGE("Cannot open %s metadata file", fname);
1049 return -1;
1050 }
1051
Wei Wang4375f1b2017-02-24 17:43:01 -08001052 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001053 if (pdata == NULL) {
1054 SLOGE("Cannot allocate persistant data");
1055 goto err;
1056 }
1057
1058 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1059 SLOGE("Cannot seek to read persistent data on %s", fname);
1060 goto err2;
1061 }
1062
1063 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001064 SLOGE("Error reading persistent data before save");
1065 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001066 }
1067
1068 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1069 /* The first copy is the curent valid copy, so write to
1070 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001071 write_offset = crypt_ftr.persist_data_offset[1];
1072 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001073 } else {
1074 /* The second copy must be the valid copy, so write to
1075 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001076 write_offset = crypt_ftr.persist_data_offset[0];
1077 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001078 }
1079
1080 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001081 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001082 SLOGE("Cannot seek to write persistent data");
1083 goto err2;
1084 }
1085 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001086 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001087 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001088 SLOGE("Cannot seek to erase previous persistent data");
1089 goto err2;
1090 }
1091 fsync(fd);
1092 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001093 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001094 SLOGE("Cannot write to erase previous persistent data");
1095 goto err2;
1096 }
1097 fsync(fd);
1098 } else {
1099 SLOGE("Cannot write to save persistent data");
1100 goto err2;
1101 }
1102
1103 /* Success */
1104 free(pdata);
1105 close(fd);
1106 return 0;
1107
1108err2:
1109 free(pdata);
1110err:
1111 close(fd);
1112 return -1;
1113}
1114
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001115/* Convert a binary key of specified length into an ascii hex string equivalent,
1116 * without the leading 0x and with null termination
1117 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001118static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1119 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001120 unsigned int i, a;
1121 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122
Paul Crowley14c8c072018-09-18 13:30:21 -07001123 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001124 /* For each byte, write out two ascii hex digits */
1125 nibble = (master_key[i] >> 4) & 0xf;
1126 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001127
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001128 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001129 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001130 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001132 /* Add the null termination */
1133 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134}
1135
Eric Biggersed45ec32019-01-25 10:47:55 -08001136/*
1137 * If the ro.crypto.fde_sector_size system property is set, append the
1138 * parameters to make dm-crypt use the specified crypto sector size and round
1139 * the crypto device size down to a crypto sector boundary.
1140 */
David Andersonb9224732019-05-13 13:02:54 -07001141static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001142 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001143 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001144
Eric Biggersed45ec32019-01-25 10:47:55 -08001145 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1146 unsigned int sector_size;
1147
1148 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1149 (sector_size & (sector_size - 1)) != 0) {
1150 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1151 DM_CRYPT_SECTOR_SIZE, value);
1152 return -1;
1153 }
1154
David Andersonb9224732019-05-13 13:02:54 -07001155 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001156
1157 // With this option, IVs will match the sector numbering, instead
1158 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001159 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001160
1161 // Round the crypto device size down to a crypto sector boundary.
1162 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001163 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001164 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001165}
1166
Paul Crowley5afbc622017-11-27 09:42:17 -08001167static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001168 const char* real_blk_name, std::string* crypto_blk_name,
1169 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001170 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001171
David Andersonb9224732019-05-13 13:02:54 -07001172 // We need two ASCII characters to represent each byte, and need space for
1173 // the '\0' terminator.
1174 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1175 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001176
David Andersonb9224732019-05-13 13:02:54 -07001177 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1178 (const char*)crypt_ftr->crypto_type_name,
1179 master_key_ascii, 0, real_blk_name, 0);
1180 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001181
Paul Crowley5afbc622017-11-27 09:42:17 -08001182 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001183 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001184 }
David Andersonb9224732019-05-13 13:02:54 -07001185 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001186 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001187 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001188 }
David Andersonb9224732019-05-13 13:02:54 -07001189
1190 DmTable table;
1191 table.AddTarget(std::move(target));
1192
1193 int load_count = 1;
1194 while (load_count < TABLE_LOAD_RETRIES) {
1195 if (dm.CreateDevice(name, table)) {
1196 break;
1197 }
1198 load_count++;
1199 }
1200
1201 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001202 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001203 return -1;
1204 }
1205 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001206 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1207 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001208
Paul Crowley81796e92020-02-07 11:27:49 -08001209 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001210 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1211 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001212 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001213
Paul Crowleycfe39722018-10-30 15:59:24 -07001214 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001215 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001216 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001217 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001218 }
David Andersonb9224732019-05-13 13:02:54 -07001219 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001220}
1221
David Andersonb9224732019-05-13 13:02:54 -07001222static int delete_crypto_blk_dev(const std::string& name) {
1223 auto& dm = DeviceMapper::Instance();
1224 if (!dm.DeleteDevice(name)) {
1225 SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1226 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001227 }
David Andersonb9224732019-05-13 13:02:54 -07001228 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229}
1230
Paul Crowley14c8c072018-09-18 13:30:21 -07001231static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1232 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001233 SLOGI("Using pbkdf2 for cryptfs KDF");
1234
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001235 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001236 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1237 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001238}
1239
Paul Crowley14c8c072018-09-18 13:30:21 -07001240static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001241 SLOGI("Using scrypt for cryptfs KDF");
1242
Paul Crowley14c8c072018-09-18 13:30:21 -07001243 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001244
1245 int N = 1 << ftr->N_factor;
1246 int r = 1 << ftr->r_factor;
1247 int p = 1 << ftr->p_factor;
1248
1249 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001250 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001251 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001252
Paul Crowley14c8c072018-09-18 13:30:21 -07001253 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001254}
1255
Paul Crowley14c8c072018-09-18 13:30:21 -07001256static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1257 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001258 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1259
1260 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001261 size_t signature_size;
1262 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001263 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001264
1265 int N = 1 << ftr->N_factor;
1266 int r = 1 << ftr->r_factor;
1267 int p = 1 << ftr->p_factor;
1268
Paul Crowley14c8c072018-09-18 13:30:21 -07001269 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001270 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001271
1272 if (rc) {
1273 SLOGE("scrypt failed");
1274 return -1;
1275 }
1276
Paul Crowley14c8c072018-09-18 13:30:21 -07001277 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001278 SLOGE("Signing failed");
1279 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001280 }
1281
Paul Crowley14c8c072018-09-18 13:30:21 -07001282 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1283 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001284 free(signature);
1285
1286 if (rc) {
1287 SLOGE("scrypt failed");
1288 return -1;
1289 }
1290
1291 return 0;
1292}
1293
Paul Crowley14c8c072018-09-18 13:30:21 -07001294static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1295 const unsigned char* decrypted_master_key,
1296 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1297 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001298 EVP_CIPHER_CTX e_ctx;
1299 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001300 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001301
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001302 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001303 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001304
1305 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001306 case KDF_SCRYPT_KEYMASTER:
1307 if (keymaster_create_key(crypt_ftr)) {
1308 SLOGE("keymaster_create_key failed");
1309 return -1;
1310 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001311
Paul Crowley14c8c072018-09-18 13:30:21 -07001312 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1313 SLOGE("scrypt failed");
1314 return -1;
1315 }
1316 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001317
Paul Crowley14c8c072018-09-18 13:30:21 -07001318 case KDF_SCRYPT:
1319 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1320 SLOGE("scrypt failed");
1321 return -1;
1322 }
1323 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001324
Paul Crowley14c8c072018-09-18 13:30:21 -07001325 default:
1326 SLOGE("Invalid kdf_type");
1327 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001328 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001329
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001330 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001331 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001332 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1333 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001334 SLOGE("EVP_EncryptInit failed\n");
1335 return -1;
1336 }
1337 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001338
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001339 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001340 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1341 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001342 SLOGE("EVP_EncryptUpdate failed\n");
1343 return -1;
1344 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001345 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001346 SLOGE("EVP_EncryptFinal failed\n");
1347 return -1;
1348 }
1349
Greg Kaiser59ad0182018-02-16 13:01:36 -08001350 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001351 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1352 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001353 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001354
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001355 /* Store the scrypt of the intermediate key, so we can validate if it's a
1356 password error or mount error when things go wrong.
1357 Note there's no need to check for errors, since if this is incorrect, we
1358 simply won't wipe userdata, which is the correct default behavior
1359 */
1360 int N = 1 << crypt_ftr->N_factor;
1361 int r = 1 << crypt_ftr->r_factor;
1362 int p = 1 << crypt_ftr->p_factor;
1363
Paul Crowley14c8c072018-09-18 13:30:21 -07001364 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1365 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001366 sizeof(crypt_ftr->scrypted_intermediate_key));
1367
1368 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001369 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001370 }
1371
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001372 EVP_CIPHER_CTX_cleanup(&e_ctx);
1373
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001374 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001375}
1376
Paul Crowley14c8c072018-09-18 13:30:21 -07001377static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1378 const unsigned char* encrypted_master_key, size_t keysize,
1379 unsigned char* decrypted_master_key, kdf_func kdf,
1380 void* kdf_params, unsigned char** intermediate_key,
1381 size_t* intermediate_key_size) {
1382 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1383 EVP_CIPHER_CTX d_ctx;
1384 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001385
Paul Crowley14c8c072018-09-18 13:30:21 -07001386 /* Turn the password into an intermediate key and IV that can decrypt the
1387 master key */
1388 if (kdf(passwd, salt, ikey, kdf_params)) {
1389 SLOGE("kdf failed");
1390 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001391 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001392
Paul Crowley14c8c072018-09-18 13:30:21 -07001393 /* Initialize the decryption engine */
1394 EVP_CIPHER_CTX_init(&d_ctx);
1395 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1396 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1397 return -1;
1398 }
1399 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1400 /* Decrypt the master key */
1401 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1402 keysize)) {
1403 return -1;
1404 }
1405 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1406 return -1;
1407 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001408
Paul Crowley14c8c072018-09-18 13:30:21 -07001409 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1410 return -1;
1411 }
1412
1413 /* Copy intermediate key if needed by params */
1414 if (intermediate_key && intermediate_key_size) {
1415 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1416 if (*intermediate_key) {
1417 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1418 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1419 }
1420 }
1421
1422 EVP_CIPHER_CTX_cleanup(&d_ctx);
1423
1424 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001425}
1426
Paul Crowley14c8c072018-09-18 13:30:21 -07001427static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001428 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001429 *kdf = scrypt_keymaster;
1430 *kdf_params = ftr;
1431 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001432 *kdf = scrypt;
1433 *kdf_params = ftr;
1434 } else {
1435 *kdf = pbkdf2;
1436 *kdf_params = NULL;
1437 }
1438}
1439
Paul Crowley14c8c072018-09-18 13:30:21 -07001440static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1441 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1442 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001443 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001444 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001445 int ret;
1446
1447 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001448 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1449 decrypted_master_key, kdf, kdf_params, intermediate_key,
1450 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001451 if (ret != 0) {
1452 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001453 }
1454
1455 return ret;
1456}
1457
Paul Crowley14c8c072018-09-18 13:30:21 -07001458static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1459 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001460 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001461
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001462 /* Get some random bits for a key and salt */
1463 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1464 return -1;
1465 }
1466 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1467 return -1;
1468 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001469
1470 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001471 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001472}
1473
Paul Crowley73be12d2020-02-03 12:22:03 -08001474static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001475 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001476#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001477
1478 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001479 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001480 if (umount(mountpoint) == 0) {
1481 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001482 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001483
1484 if (errno == EINVAL) {
1485 /* EINVAL is returned if the directory is not a mountpoint,
1486 * i.e. there is no filesystem mounted there. So just get out.
1487 */
1488 break;
1489 }
1490
1491 err = errno;
1492
1493 /* If allowed, be increasingly aggressive before the last two retries */
1494 if (kill) {
1495 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1496 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001497 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001498 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1499 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001500 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001501 }
1502 }
1503
1504 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001505 }
1506
1507 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001508 SLOGD("unmounting %s succeeded\n", mountpoint);
1509 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001510 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001511 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1512 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1513 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001514 }
1515
1516 return rc;
1517}
1518
Paul Crowley14c8c072018-09-18 13:30:21 -07001519static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001520 // NOTE: post_fs_data results in init calling back around to vold, so all
1521 // callers to this method must be async
1522
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001523 /* Do the prep of the /data filesystem */
1524 property_set("vold.post_fs_data_done", "0");
1525 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001526 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001527
Ken Sumrallc5872692013-05-14 15:26:31 -07001528 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001529 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001530 /* We timed out to prep /data in time. Continue wait. */
1531 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001532 }
Wei Wang42e38102017-06-07 10:46:12 -07001533 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001534}
1535
Paul Crowley14c8c072018-09-18 13:30:21 -07001536static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001537 // Mark the footer as bad
1538 struct crypt_mnt_ftr crypt_ftr;
1539 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1540 SLOGE("Failed to get crypto footer - panic");
1541 return;
1542 }
1543
1544 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1545 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1546 SLOGE("Failed to set crypto footer - panic");
1547 return;
1548 }
1549}
1550
Paul Crowley14c8c072018-09-18 13:30:21 -07001551static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001552 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001553 SLOGE("Failed to mount tmpfs on data - panic");
1554 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001555 }
1556
1557 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1558 SLOGE("Failed to trigger post fs data - panic");
1559 return;
1560 }
1561
1562 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1563 SLOGE("Failed to trigger restart min framework - panic");
1564 return;
1565 }
1566}
1567
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001568/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001569static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001570 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001571 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001572 static int restart_successful = 0;
1573
1574 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001575 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001576 SLOGE("Encrypted filesystem not validated, aborting");
1577 return -1;
1578 }
1579
1580 if (restart_successful) {
1581 SLOGE("System already restarted with encrypted disk, aborting");
1582 return -1;
1583 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584
Paul Lawrencef4faa572014-01-29 13:31:03 -08001585 if (restart_main) {
1586 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001587 * start all services in one of these classes: core, early_hal, hal,
1588 * main and late_start. To get to the minimal UI for PIN entry, we
1589 * need to start core, early_hal, hal and main. When we want to
1590 * shutdown the framework again, we need to stop most of the services in
1591 * these classes, but only those services that were started after
1592 * /data was mounted. This excludes critical services like vold and
1593 * ueventd, which need to keep running. We could possible stop
1594 * even fewer services, but because we want services to pick up APEX
1595 * libraries from the real /data, restarting is better, as it makes
1596 * these devices consistent with FBE devices and lets them use the
1597 * most recent code.
1598 *
1599 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001600 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001601 * We then restart the class core, hal, main, and also the class
1602 * late_start.
1603 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001604 * At the moment, I've only put a few things in late_start that I know
1605 * are not needed to bring up the framework, and that also cause problems
1606 * with unmounting the tmpfs /data, but I hope to add add more services
1607 * to the late_start class as we optimize this to decrease the delay
1608 * till the user is asked for the password to the filesystem.
1609 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001611 /* The init files are setup to stop the right set of services when
1612 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001613 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001614 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001615 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616
Paul Lawrencef4faa572014-01-29 13:31:03 -08001617 /* Ugh, shutting down the framework is not synchronous, so until it
1618 * can be fixed, this horrible hack will wait a moment for it all to
1619 * shut down before proceeding. Without it, some devices cannot
1620 * restart the graphics services.
1621 */
1622 sleep(2);
1623 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001624
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001625 /* Now that the framework is shutdown, we should be able to umount()
1626 * the tmpfs filesystem, and mount the real one.
1627 */
1628
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001629 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1630 if (strlen(crypto_blkdev) == 0) {
1631 SLOGE("fs_crypto_blkdev not set\n");
1632 return -1;
1633 }
1634
Paul Crowley14c8c072018-09-18 13:30:21 -07001635 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001636 /* If ro.crypto.readonly is set to 1, mount the decrypted
1637 * filesystem readonly. This is used when /data is mounted by
1638 * recovery mode.
1639 */
1640 char ro_prop[PROPERTY_VALUE_MAX];
1641 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001642 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001643 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1644 if (entry != nullptr) {
1645 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001646 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001647 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001648
Ken Sumralle5032c42012-04-01 23:58:44 -07001649 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001650 int retries = RETRY_MOUNT_ATTEMPTS;
1651 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001652
1653 /*
1654 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1655 * partitions in the fsck domain.
1656 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001657 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001658 SLOGE("Failed to setexeccon");
1659 return -1;
1660 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001661 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001662 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001663 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001664 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1665 /* TODO: invoke something similar to
1666 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1667 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001668 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001669 if (--retries) {
1670 sleep(RETRY_MOUNT_DELAY_SECONDS);
1671 } else {
1672 /* Let's hope that a reboot clears away whatever is keeping
1673 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001674 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001675 }
1676 } else {
1677 SLOGE("Failed to mount decrypted data");
1678 cryptfs_set_corrupt();
1679 cryptfs_trigger_restart_min_framework();
1680 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001681 if (setexeccon(NULL)) {
1682 SLOGE("Failed to setexeccon");
1683 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001684 return -1;
1685 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001686 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001687 if (setexeccon(NULL)) {
1688 SLOGE("Failed to setexeccon");
1689 return -1;
1690 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001691
Ken Sumralle5032c42012-04-01 23:58:44 -07001692 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001693 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001694 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001695
1696 /* startup service classes main and late_start */
1697 property_set("vold.decrypt", "trigger_restart_framework");
1698 SLOGD("Just triggered restart_framework\n");
1699
1700 /* Give it a few moments to get started */
1701 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001702 }
1703
Ken Sumrall0cc16632011-01-18 20:32:26 -08001704 if (rc == 0) {
1705 restart_successful = 1;
1706 }
1707
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001708 return rc;
1709}
1710
Paul Crowley14c8c072018-09-18 13:30:21 -07001711int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001712 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001713 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001714 SLOGE("cryptfs_restart not valid for file encryption:");
1715 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001716 }
1717
Paul Lawrencef4faa572014-01-29 13:31:03 -08001718 /* Call internal implementation forcing a restart of main service group */
1719 return cryptfs_restart_internal(1);
1720}
1721
Paul Crowley14c8c072018-09-18 13:30:21 -07001722static int do_crypto_complete(const char* mount_point) {
1723 struct crypt_mnt_ftr crypt_ftr;
1724 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001725
Paul Crowley14c8c072018-09-18 13:30:21 -07001726 property_get("ro.crypto.state", encrypted_state, "");
1727 if (strcmp(encrypted_state, "encrypted")) {
1728 SLOGE("not running with encryption, aborting");
1729 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001730 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001731
Paul Crowley14c8c072018-09-18 13:30:21 -07001732 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001733 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001734 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1735 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001736
Paul Crowley14c8c072018-09-18 13:30:21 -07001737 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001738 std::string key_loc;
1739 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001740
Paul Crowley14c8c072018-09-18 13:30:21 -07001741 /*
1742 * Only report this error if key_loc is a file and it exists.
1743 * If the device was never encrypted, and /data is not mountable for
1744 * some reason, returning 1 should prevent the UI from presenting the
1745 * a "enter password" screen, or worse, a "press button to wipe the
1746 * device" screen.
1747 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001748 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001749 SLOGE("master key file does not exist, aborting");
1750 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1751 } else {
1752 SLOGE("Error getting crypt footer and key\n");
1753 return CRYPTO_COMPLETE_BAD_METADATA;
1754 }
1755 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001756
Paul Crowley14c8c072018-09-18 13:30:21 -07001757 // Test for possible error flags
1758 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1759 SLOGE("Encryption process is partway completed\n");
1760 return CRYPTO_COMPLETE_PARTIAL;
1761 }
1762
1763 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1764 SLOGE("Encryption process was interrupted but cannot continue\n");
1765 return CRYPTO_COMPLETE_INCONSISTENT;
1766 }
1767
1768 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1769 SLOGE("Encryption is successful but data is corrupt\n");
1770 return CRYPTO_COMPLETE_CORRUPT;
1771 }
1772
1773 /* We passed the test! We shall diminish, and return to the west */
1774 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001775}
1776
Paul Crowley14c8c072018-09-18 13:30:21 -07001777static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1778 const char* mount_point, const char* label) {
1779 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001780 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001781 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001782 char tmp_mount_point[64];
1783 unsigned int orig_failed_decrypt_count;
1784 int rc;
1785 int use_keymaster = 0;
1786 int upgrade = 0;
1787 unsigned char* intermediate_key = 0;
1788 size_t intermediate_key_size = 0;
1789 int N = 1 << crypt_ftr->N_factor;
1790 int r = 1 << crypt_ftr->r_factor;
1791 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001792
Paul Crowley14c8c072018-09-18 13:30:21 -07001793 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1794 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001795
Paul Crowley14c8c072018-09-18 13:30:21 -07001796 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1797 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1798 &intermediate_key_size)) {
1799 SLOGE("Failed to decrypt master key\n");
1800 rc = -1;
1801 goto errout;
1802 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001803 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001804
Tom Cherry4c5bde22019-01-29 14:34:01 -08001805 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001806
Paul Crowley14c8c072018-09-18 13:30:21 -07001807 // Create crypto block device - all (non fatal) code paths
1808 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001809 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001810 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001811 SLOGE("Error creating decrypted block device\n");
1812 rc = -1;
1813 goto errout;
1814 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001815
Paul Crowley14c8c072018-09-18 13:30:21 -07001816 /* Work out if the problem is the password or the data */
1817 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001818
Paul Crowley14c8c072018-09-18 13:30:21 -07001819 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1820 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1821 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001822
Paul Crowley14c8c072018-09-18 13:30:21 -07001823 // Does the key match the crypto footer?
1824 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1825 sizeof(scrypted_intermediate_key)) == 0) {
1826 SLOGI("Password matches");
1827 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001828 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001829 /* Try mounting the file system anyway, just in case the problem's with
1830 * the footer, not the key. */
1831 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1832 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001833 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1834 const_cast<char*>(crypto_blkdev.c_str()), 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. */
Paul Crowley81796e92020-02-07 11:27:49 -08001856 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001857
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.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001913 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001914int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001915 std::string* out_crypto_blkdev) {
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001916 if (key.size() != cryptfs_get_keysize()) {
Paul Crowleya661fb62020-02-11 16:21:54 -08001917 SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001918 cryptfs_get_keysize());
1919 return -1;
1920 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001921 uint64_t nr_sec = 0;
1922 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001923 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001924 return -1;
1925 }
1926
Jeff Sharkey9c484982015-03-31 10:35:33 -07001927 struct crypt_mnt_ftr ext_crypt_ftr;
1928 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1929 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001930 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowleya661fb62020-02-11 16:21:54 -08001931 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_kernel_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001932 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001933 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001934 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001935 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1936 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001937
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001938 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1939 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001940}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001941
Paul Crowley14c8c072018-09-18 13:30:21 -07001942int cryptfs_crypto_complete(void) {
1943 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001944}
1945
Paul Crowley14c8c072018-09-18 13:30:21 -07001946int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001947 char encrypted_state[PROPERTY_VALUE_MAX];
1948 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001949 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1950 SLOGE(
1951 "encrypted fs already validated or not running with encryption,"
1952 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001953 return -1;
1954 }
1955
1956 if (get_crypt_ftr_and_key(crypt_ftr)) {
1957 SLOGE("Error getting crypt footer and key");
1958 return -1;
1959 }
1960
1961 return 0;
1962}
1963
Paul Crowley14c8c072018-09-18 13:30:21 -07001964int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001965 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001966 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001967 SLOGE("cryptfs_check_passwd not valid for file encryption");
1968 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001969 }
1970
Paul Lawrencef4faa572014-01-29 13:31:03 -08001971 struct crypt_mnt_ftr crypt_ftr;
1972 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001973
Paul Lawrencef4faa572014-01-29 13:31:03 -08001974 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001975 if (rc) {
1976 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001977 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001978 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001979
Paul Crowley14c8c072018-09-18 13:30:21 -07001980 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001981 if (rc) {
1982 SLOGE("Password did not match");
1983 return rc;
1984 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001985
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001986 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1987 // Here we have a default actual password but a real password
1988 // we must test against the scrypted value
1989 // First, we must delete the crypto block device that
1990 // test_mount_encrypted_fs leaves behind as a side effect
1991 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07001992 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
1993 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001994 if (rc) {
1995 SLOGE("Default password did not match on reboot encryption");
1996 return rc;
1997 }
1998
1999 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2000 put_crypt_ftr_and_key(&crypt_ftr);
2001 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2002 if (rc) {
2003 SLOGE("Could not change password on reboot encryption");
2004 return rc;
2005 }
2006 }
2007
2008 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002009 cryptfs_clear_password();
2010 password = strdup(passwd);
2011 struct timespec now;
2012 clock_gettime(CLOCK_BOOTTIME, &now);
2013 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002014 }
2015
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002016 return rc;
2017}
2018
Paul Crowley14c8c072018-09-18 13:30:21 -07002019int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002020 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002021 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002022 char encrypted_state[PROPERTY_VALUE_MAX];
2023 int rc;
2024
2025 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002026 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002027 SLOGE("device not encrypted, aborting");
2028 return -2;
2029 }
2030
2031 if (!master_key_saved) {
2032 SLOGE("encrypted fs not yet mounted, aborting");
2033 return -1;
2034 }
2035
2036 if (!saved_mount_point) {
2037 SLOGE("encrypted fs failed to save mount point, aborting");
2038 return -1;
2039 }
2040
Ken Sumrall160b4d62013-04-22 12:15:39 -07002041 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002042 SLOGE("Error getting crypt footer and key\n");
2043 return -1;
2044 }
2045
2046 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2047 /* If the device has no password, then just say the password is valid */
2048 rc = 0;
2049 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002050 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002051 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2052 /* They match, the password is correct */
2053 rc = 0;
2054 } else {
2055 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2056 sleep(1);
2057 rc = 1;
2058 }
2059 }
2060
2061 return rc;
2062}
2063
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002064/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002065 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002066 * Presumably, at a minimum, the caller will update the
2067 * filesystem size and crypto_type_name after calling this function.
2068 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002069static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002070 off64_t off;
2071
2072 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002073 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002074 ftr->major_version = CURRENT_MAJOR_VERSION;
2075 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002076 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002077 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002078
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002079 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002080 case 1:
2081 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2082 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002083
Paul Crowley14c8c072018-09-18 13:30:21 -07002084 case 0:
2085 ftr->kdf_type = KDF_SCRYPT;
2086 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002087
Paul Crowley14c8c072018-09-18 13:30:21 -07002088 default:
2089 SLOGE("keymaster_check_compatibility failed");
2090 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002091 }
2092
Kenny Rootc4c70f12013-06-14 12:11:38 -07002093 get_device_scrypt_params(ftr);
2094
Ken Sumrall160b4d62013-04-22 12:15:39 -07002095 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2096 if (get_crypt_ftr_info(NULL, &off) == 0) {
2097 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002098 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002099 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002100
2101 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002102}
2103
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002104#define FRAMEWORK_BOOT_WAIT 60
2105
Paul Crowley14c8c072018-09-18 13:30:21 -07002106static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2107 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002108 if (fd == -1) {
2109 SLOGE("Error opening file %s", filename);
2110 return -1;
2111 }
2112
2113 char block[CRYPT_INPLACE_BUFSIZE];
2114 memset(block, 0, sizeof(block));
2115 if (unix_read(fd, block, sizeof(block)) < 0) {
2116 SLOGE("Error reading file %s", filename);
2117 close(fd);
2118 return -1;
2119 }
2120
2121 close(fd);
2122
2123 SHA256_CTX c;
2124 SHA256_Init(&c);
2125 SHA256_Update(&c, block, sizeof(block));
2126 SHA256_Final(buf, &c);
2127
2128 return 0;
2129}
2130
Paul Crowley81796e92020-02-07 11:27:49 -08002131static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2132 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002133 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002134 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002135
Paul Lawrence87999172014-02-20 12:21:31 -08002136 /* The size of the userdata partition, and add in the vold volumes below */
2137 tot_encryption_size = crypt_ftr->fs_size;
2138
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002139 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002140 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002141
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002142 if (rc == ENABLE_INPLACE_ERR_DEV) {
2143 /* Hack for b/17898962 */
2144 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2145 cryptfs_reboot(RebootType::reboot);
2146 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002147
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002148 if (!rc) {
2149 crypt_ftr->encrypted_upto = cur_encryption_done;
2150 }
Paul Lawrence87999172014-02-20 12:21:31 -08002151
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002152 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2153 /* The inplace routine never actually sets the progress to 100% due
2154 * to the round down nature of integer division, so set it here */
2155 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002156 }
2157
2158 return rc;
2159}
2160
Paul Crowleyb64933a2017-10-31 08:25:55 -07002161static int vold_unmountAll(void) {
2162 VolumeManager* vm = VolumeManager::Instance();
2163 return vm->unmountAll();
2164}
2165
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002166int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002167 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002168 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002169 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002170 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002171 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002172 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002173 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002174 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002175 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002176 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002177 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002178 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002179 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002180 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002181
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002182 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002183 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2184 /* An encryption was underway and was interrupted */
2185 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2186 crypt_ftr.encrypted_upto = 0;
2187 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002188
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002189 /* At this point, we are in an inconsistent state. Until we successfully
2190 complete encryption, a reboot will leave us broken. So mark the
2191 encryption failed in case that happens.
2192 On successfully completing encryption, remove this flag */
2193 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002194
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002195 put_crypt_ftr_and_key(&crypt_ftr);
2196 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2197 if (!check_ftr_sha(&crypt_ftr)) {
2198 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2199 put_crypt_ftr_and_key(&crypt_ftr);
2200 goto error_unencrypted;
2201 }
2202
2203 /* Doing a reboot-encryption*/
2204 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2205 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2206 rebootEncryption = true;
2207 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002208 } else {
2209 // We don't want to accidentally reference invalid data.
2210 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002211 }
2212
2213 property_get("ro.crypto.state", encrypted_state, "");
2214 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2215 SLOGE("Device is already running encrypted, aborting");
2216 goto error_unencrypted;
2217 }
2218
Tom Cherry4c5bde22019-01-29 14:34:01 -08002219 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002220
Ken Sumrall3ed82362011-01-28 23:31:16 -08002221 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002222 uint64_t nr_sec;
2223 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002224 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002225 goto error_unencrypted;
2226 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002227
2228 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002229 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002230 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002231 fs_size_sec = get_fs_size(real_blkdev.c_str());
2232 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002233
Paul Lawrence87999172014-02-20 12:21:31 -08002234 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002235
2236 if (fs_size_sec > max_fs_size_sec) {
2237 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2238 goto error_unencrypted;
2239 }
2240 }
2241
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002242 /* Get a wakelock as this may take a while, and we don't want the
2243 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2244 * wants to keep the screen on, it can grab a full wakelock.
2245 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002246 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002247 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002248
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002249 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002250 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002251 */
2252 property_set("vold.decrypt", "trigger_shutdown_framework");
2253 SLOGD("Just asked init to shut down class main\n");
2254
Jeff Sharkey9c484982015-03-31 10:35:33 -07002255 /* Ask vold to unmount all devices that it manages */
2256 if (vold_unmountAll()) {
2257 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002258 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002259
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002260 /* no_ui means we are being called from init, not settings.
2261 Now we always reboot from settings, so !no_ui means reboot
2262 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002263 if (!no_ui) {
2264 /* Try fallback, which is to reboot and try there */
2265 onlyCreateHeader = true;
2266 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2267 if (breadcrumb == 0) {
2268 SLOGE("Failed to create breadcrumb file");
2269 goto error_shutting_down;
2270 }
2271 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002272 }
2273
2274 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002275 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002276 /* Now that /data is unmounted, we need to mount a tmpfs
2277 * /data, set a property saying we're doing inplace encryption,
2278 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002279 */
xzj7e38a3a2018-10-12 10:17:11 +08002280 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002281 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002282 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002283 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002284 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002285 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002286
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002287 /* restart the framework. */
2288 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002289 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002290
Ken Sumrall92736ef2012-10-17 20:57:14 -07002291 /* Ugh, shutting down the framework is not synchronous, so until it
2292 * can be fixed, this horrible hack will wait a moment for it all to
2293 * shut down before proceeding. Without it, some devices cannot
2294 * restart the graphics services.
2295 */
2296 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002297 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002298
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002299 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002300 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002301 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002302 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2303 goto error_shutting_down;
2304 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002305
Tom Cherry4c5bde22019-01-29 14:34:01 -08002306 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002307 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002308 } else {
2309 crypt_ftr.fs_size = nr_sec;
2310 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002311 /* At this point, we are in an inconsistent state. Until we successfully
2312 complete encryption, a reboot will leave us broken. So mark the
2313 encryption failed in case that happens.
2314 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002315 if (onlyCreateHeader) {
2316 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2317 } else {
2318 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2319 }
Paul Lawrence87999172014-02-20 12:21:31 -08002320 crypt_ftr.crypt_type = crypt_type;
Paul Crowleya661fb62020-02-11 16:21:54 -08002321 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_kernel_name(),
Paul Crowley14c8c072018-09-18 13:30:21 -07002322 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002323
Paul Lawrence87999172014-02-20 12:21:31 -08002324 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002325 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2326 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002327 SLOGE("Cannot create encrypted master key\n");
2328 goto error_shutting_down;
2329 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002330
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002331 /* Replace scrypted intermediate key if we are preparing for a reboot */
2332 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002333 unsigned char fake_master_key[MAX_KEY_LEN];
2334 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002335 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002336 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2337 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002338 }
2339
Paul Lawrence87999172014-02-20 12:21:31 -08002340 /* Write the key to the end of the partition */
2341 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002342
Paul Lawrence87999172014-02-20 12:21:31 -08002343 /* If any persistent data has been remembered, save it.
2344 * If none, create a valid empty table and save that.
2345 */
2346 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002347 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2348 if (pdata) {
2349 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2350 persist_data = pdata;
2351 }
Paul Lawrence87999172014-02-20 12:21:31 -08002352 }
2353 if (persist_data) {
2354 save_persistent_data();
2355 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002356 }
2357
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002358 if (onlyCreateHeader) {
2359 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002360 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002361 }
2362
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002363 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002364 /* startup service classes main and late_start */
2365 property_set("vold.decrypt", "trigger_restart_min_framework");
2366 SLOGD("Just triggered restart_min_framework\n");
2367
2368 /* OK, the framework is restarted and will soon be showing a
2369 * progress bar. Time to setup an encrypted mapping, and
2370 * either write a new filesystem, or encrypt in place updating
2371 * the progress bar as we work.
2372 */
2373 }
2374
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002375 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002376 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002377 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002378
Paul Lawrence87999172014-02-20 12:21:31 -08002379 /* If we are continuing, check checksums match */
2380 rc = 0;
2381 if (previously_encrypted_upto) {
2382 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002383 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002384
Paul Crowley14c8c072018-09-18 13:30:21 -07002385 if (!rc &&
2386 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002387 SLOGE("Checksums do not match - trigger wipe");
2388 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002389 }
2390 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002391
Paul Lawrence87999172014-02-20 12:21:31 -08002392 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002393 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002394 previously_encrypted_upto);
2395 }
2396
2397 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002398 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002399 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002400 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002401 SLOGE("Error calculating checksum for continuing encryption");
2402 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002403 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002404 }
2405
2406 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002407 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002408
Paul Crowley14c8c072018-09-18 13:30:21 -07002409 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002410 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002411 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002412
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002413 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002414 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2415 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002416 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002417 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002418
Paul Lawrence6bfed202014-07-28 12:47:22 -07002419 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002420
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002421 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2422 char value[PROPERTY_VALUE_MAX];
2423 property_get("ro.crypto.state", value, "");
2424 if (!strcmp(value, "")) {
2425 /* default encryption - continue first boot sequence */
2426 property_set("ro.crypto.state", "encrypted");
2427 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002428 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002429 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2430 // Bring up cryptkeeper that will check the password and set it
2431 property_set("vold.decrypt", "trigger_shutdown_framework");
2432 sleep(2);
2433 property_set("vold.encrypt_progress", "");
2434 cryptfs_trigger_restart_min_framework();
2435 } else {
2436 cryptfs_check_passwd(DEFAULT_PASSWORD);
2437 cryptfs_restart_internal(1);
2438 }
2439 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002440 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002441 sleep(2); /* Give the UI a chance to show 100% progress */
2442 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002443 }
Paul Lawrence87999172014-02-20 12:21:31 -08002444 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002445 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002446 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002447 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002448 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002449 char value[PROPERTY_VALUE_MAX];
2450
Ken Sumrall319369a2012-06-27 16:30:18 -07002451 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002452 if (!strcmp(value, "1")) {
2453 /* wipe data if encryption failed */
2454 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002455 std::string err;
2456 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002457 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002458 if (!write_bootloader_message(options, &err)) {
2459 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002460 }
Josh Gaofec44372017-08-28 13:22:55 -07002461 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002462 } else {
2463 /* set property to trigger dialog */
2464 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002465 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002466 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002467 }
2468
Ken Sumrall3ed82362011-01-28 23:31:16 -08002469 /* hrm, the encrypt step claims success, but the reboot failed.
2470 * This should not happen.
2471 * Set the property and return. Hope the framework can deal with it.
2472 */
2473 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002474 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002475
2476error_unencrypted:
2477 property_set("vold.encrypt_progress", "error_not_encrypted");
2478 return -1;
2479
2480error_shutting_down:
2481 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2482 * but the framework is stopped and not restarted to show the error, so it's up to
2483 * vold to restart the system.
2484 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002485 SLOGE(
2486 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2487 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002488 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002489
2490 /* shouldn't get here */
2491 property_set("vold.encrypt_progress", "error_shutting_down");
2492 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002493}
2494
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002495int cryptfs_enable(int type, const char* passwd, int no_ui) {
2496 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002497}
2498
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002499int cryptfs_enable_default(int no_ui) {
2500 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002501}
2502
Paul Crowley14c8c072018-09-18 13:30:21 -07002503int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002504 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002505 SLOGE("cryptfs_changepw not valid for file encryption");
2506 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002507 }
2508
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002509 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002510 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002511
2512 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002513 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002514 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002515 return -1;
2516 }
2517
Paul Lawrencef4faa572014-01-29 13:31:03 -08002518 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2519 SLOGE("Invalid crypt_type %d", crypt_type);
2520 return -1;
2521 }
2522
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002523 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002524 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002525 SLOGE("Error getting crypt footer and key");
2526 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002527 }
2528
Paul Lawrencef4faa572014-01-29 13:31:03 -08002529 crypt_ftr.crypt_type = crypt_type;
2530
Paul Crowley14c8c072018-09-18 13:30:21 -07002531 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2532 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002533 if (rc) {
2534 SLOGE("Encrypt master key failed: %d", rc);
2535 return -1;
2536 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002537 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002538 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002539
2540 return 0;
2541}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002542
Rubin Xu85c01f92014-10-13 12:49:54 +01002543static unsigned int persist_get_max_entries(int encrypted) {
2544 struct crypt_mnt_ftr crypt_ftr;
2545 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002546
2547 /* If encrypted, use the values from the crypt_ftr, otherwise
2548 * use the values for the current spec.
2549 */
2550 if (encrypted) {
2551 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002552 /* Something is wrong, assume no space for entries */
2553 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002554 }
2555 dsize = crypt_ftr.persist_data_size;
2556 } else {
2557 dsize = CRYPT_PERSIST_DATA_SIZE;
2558 }
2559
Rubin Xuf83cc612018-10-09 16:13:38 +01002560 if (dsize > sizeof(struct crypt_persist_data)) {
2561 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2562 } else {
2563 return 0;
2564 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002565}
2566
Paul Crowley14c8c072018-09-18 13:30:21 -07002567static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002568 unsigned int i;
2569
2570 if (persist_data == NULL) {
2571 return -1;
2572 }
2573 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2574 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2575 /* We found it! */
2576 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2577 return 0;
2578 }
2579 }
2580
2581 return -1;
2582}
2583
Paul Crowley14c8c072018-09-18 13:30:21 -07002584static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002585 unsigned int i;
2586 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002587 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002588
2589 if (persist_data == NULL) {
2590 return -1;
2591 }
2592
Rubin Xu85c01f92014-10-13 12:49:54 +01002593 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002594
2595 num = persist_data->persist_valid_entries;
2596
2597 for (i = 0; i < num; i++) {
2598 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2599 /* We found an existing entry, update it! */
2600 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2601 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2602 return 0;
2603 }
2604 }
2605
2606 /* We didn't find it, add it to the end, if there is room */
2607 if (persist_data->persist_valid_entries < max_persistent_entries) {
2608 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2609 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2610 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2611 persist_data->persist_valid_entries++;
2612 return 0;
2613 }
2614
2615 return -1;
2616}
2617
Rubin Xu85c01f92014-10-13 12:49:54 +01002618/**
2619 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2620 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2621 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002622int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002623 std::string key_ = key;
2624 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002625
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002626 std::string parsed_field;
2627 unsigned parsed_index;
2628
2629 std::string::size_type split = key_.find_last_of('_');
2630 if (split == std::string::npos) {
2631 parsed_field = key_;
2632 parsed_index = 0;
2633 } else {
2634 parsed_field = key_.substr(0, split);
2635 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002636 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002637
2638 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002639}
2640
2641/*
2642 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2643 * remaining entries starting from index will be deleted.
2644 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2645 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2646 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2647 *
2648 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002649static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002650 unsigned int i;
2651 unsigned int j;
2652 unsigned int num;
2653
2654 if (persist_data == NULL) {
2655 return PERSIST_DEL_KEY_ERROR_OTHER;
2656 }
2657
2658 num = persist_data->persist_valid_entries;
2659
Paul Crowley14c8c072018-09-18 13:30:21 -07002660 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002661 // Filter out to-be-deleted entries in place.
2662 for (i = 0; i < num; i++) {
2663 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2664 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2665 j++;
2666 }
2667 }
2668
2669 if (j < num) {
2670 persist_data->persist_valid_entries = j;
2671 // Zeroise the remaining entries
2672 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2673 return PERSIST_DEL_KEY_OK;
2674 } else {
2675 // Did not find an entry matching the given fieldname
2676 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2677 }
2678}
2679
Paul Crowley14c8c072018-09-18 13:30:21 -07002680static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002681 unsigned int i;
2682 unsigned int count;
2683
2684 if (persist_data == NULL) {
2685 return -1;
2686 }
2687
2688 count = 0;
2689 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2690 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2691 count++;
2692 }
2693 }
2694
2695 return count;
2696}
2697
Ken Sumrall160b4d62013-04-22 12:15:39 -07002698/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002699int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002700 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002701 SLOGE("Cannot get field when file encrypted");
2702 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002703 }
2704
Ken Sumrall160b4d62013-04-22 12:15:39 -07002705 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002706 /* CRYPTO_GETFIELD_OK is success,
2707 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2708 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2709 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002710 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002711 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2712 int i;
2713 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002714
2715 if (persist_data == NULL) {
2716 load_persistent_data();
2717 if (persist_data == NULL) {
2718 SLOGE("Getfield error, cannot load persistent data");
2719 goto out;
2720 }
2721 }
2722
Rubin Xu85c01f92014-10-13 12:49:54 +01002723 // Read value from persistent entries. If the original value is split into multiple entries,
2724 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002725 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002726 // 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 -07002727 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002728 // value too small
2729 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2730 goto out;
2731 }
2732 rc = CRYPTO_GETFIELD_OK;
2733
2734 for (i = 1; /* break explicitly */; i++) {
2735 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002736 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002737 // If the fieldname is very long, we stop as soon as it begins to overflow the
2738 // maximum field length. At this point we have in fact fully read out the original
2739 // value because cryptfs_setfield would not allow fields with longer names to be
2740 // written in the first place.
2741 break;
2742 }
2743 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002744 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2745 // value too small.
2746 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2747 goto out;
2748 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002749 } else {
2750 // Exhaust all entries.
2751 break;
2752 }
2753 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002754 } else {
2755 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002756 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002757 }
2758
2759out:
2760 return rc;
2761}
2762
2763/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002764int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002765 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002766 SLOGE("Cannot set field when file encrypted");
2767 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002768 }
2769
Ken Sumrall160b4d62013-04-22 12:15:39 -07002770 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002771 /* 0 is success, negative values are error */
2772 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002773 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002774 unsigned int field_id;
2775 char temp_field[PROPERTY_KEY_MAX];
2776 unsigned int num_entries;
2777 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002778
2779 if (persist_data == NULL) {
2780 load_persistent_data();
2781 if (persist_data == NULL) {
2782 SLOGE("Setfield error, cannot load persistent data");
2783 goto out;
2784 }
2785 }
2786
2787 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002788 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002789 encrypted = 1;
2790 }
2791
Rubin Xu85c01f92014-10-13 12:49:54 +01002792 // Compute the number of entries required to store value, each entry can store up to
2793 // (PROPERTY_VALUE_MAX - 1) chars
2794 if (strlen(value) == 0) {
2795 // Empty value also needs one entry to store.
2796 num_entries = 1;
2797 } else {
2798 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2799 }
2800
2801 max_keylen = strlen(fieldname);
2802 if (num_entries > 1) {
2803 // Need an extra "_%d" suffix.
2804 max_keylen += 1 + log10(num_entries);
2805 }
2806 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2807 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002808 goto out;
2809 }
2810
Rubin Xu85c01f92014-10-13 12:49:54 +01002811 // Make sure we have enough space to write the new value
2812 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2813 persist_get_max_entries(encrypted)) {
2814 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2815 goto out;
2816 }
2817
2818 // Now that we know persist_data has enough space for value, let's delete the old field first
2819 // to make up space.
2820 persist_del_keys(fieldname, 0);
2821
2822 if (persist_set_key(fieldname, value, encrypted)) {
2823 // fail to set key, should not happen as we have already checked the available space
2824 SLOGE("persist_set_key() error during setfield()");
2825 goto out;
2826 }
2827
2828 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002829 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002830
2831 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2832 // fail to set key, should not happen as we have already checked the available space.
2833 SLOGE("persist_set_key() error during setfield()");
2834 goto out;
2835 }
2836 }
2837
Ken Sumrall160b4d62013-04-22 12:15:39 -07002838 /* If we are running encrypted, save the persistent data now */
2839 if (encrypted) {
2840 if (save_persistent_data()) {
2841 SLOGE("Setfield error, cannot save persistent data");
2842 goto out;
2843 }
2844 }
2845
Rubin Xu85c01f92014-10-13 12:49:54 +01002846 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002847
2848out:
2849 return rc;
2850}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002851
2852/* Checks userdata. Attempt to mount the volume if default-
2853 * encrypted.
2854 * On success trigger next init phase and return 0.
2855 * Currently do not handle failure - see TODO below.
2856 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002857int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002858 int crypt_type = cryptfs_get_password_type();
2859 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2860 SLOGE("Bad crypt type - error");
2861 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002862 SLOGD(
2863 "Password is not default - "
2864 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002865 property_set("vold.decrypt", "trigger_restart_min_framework");
2866 return 0;
2867 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2868 SLOGD("Password is default - restarting filesystem");
2869 cryptfs_restart_internal(0);
2870 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002871 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002872 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002873 }
2874
Paul Lawrence6bfed202014-07-28 12:47:22 -07002875 /** Corrupt. Allow us to boot into framework, which will detect bad
2876 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002877 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002878 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002879 return 0;
2880}
2881
2882/* Returns type of the password, default, pattern, pin or password.
2883 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002884int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002885 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002886 SLOGE("cryptfs_get_password_type not valid for file encryption");
2887 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002888 }
2889
Paul Lawrencef4faa572014-01-29 13:31:03 -08002890 struct crypt_mnt_ftr crypt_ftr;
2891
2892 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2893 SLOGE("Error getting crypt footer and key\n");
2894 return -1;
2895 }
2896
Paul Lawrence6bfed202014-07-28 12:47:22 -07002897 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2898 return -1;
2899 }
2900
Paul Lawrencef4faa572014-01-29 13:31:03 -08002901 return crypt_ftr.crypt_type;
2902}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002903
Paul Crowley14c8c072018-09-18 13:30:21 -07002904const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002905 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002906 SLOGE("cryptfs_get_password not valid for file encryption");
2907 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002908 }
2909
Paul Lawrence399317e2014-03-10 13:20:50 -07002910 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002911 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002912 if (now.tv_sec < password_expiry_time) {
2913 return password;
2914 } else {
2915 cryptfs_clear_password();
2916 return 0;
2917 }
2918}
2919
Paul Crowley14c8c072018-09-18 13:30:21 -07002920void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002921 if (password) {
2922 size_t len = strlen(password);
2923 memset(password, 0, len);
2924 free(password);
2925 password = 0;
2926 password_expiry_time = 0;
2927 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002928}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002929
Paul Crowley14c8c072018-09-18 13:30:21 -07002930int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002931 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2932 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002933}