blob: c06de0ada623e90791b416c6e3f9f705e0abee90 [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
Martijn Coenen26ad7b32020-02-13 16:20:52 +010067#include <chrono>
68#include <thread>
69
Wei Wang4375f1b2017-02-24 17:43:01 -080070extern "C" {
71#include <crypto_scrypt.h>
72}
Mark Salyzyn3e971272014-01-21 13:27:04 -080073
Eric Biggersed45ec32019-01-25 10:47:55 -080074using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080075using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080076using android::fs_mgr::GetEntryForMountPoint;
David Andersonb9224732019-05-13 13:02:54 -070077using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070078using namespace std::chrono_literals;
79
Paul Crowley73be12d2020-02-03 12:22:03 -080080/* The current cryptfs version */
81#define CURRENT_MAJOR_VERSION 1
82#define CURRENT_MINOR_VERSION 3
83
84#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
85#define CRYPT_PERSIST_DATA_SIZE 0x1000
86
87#define MAX_CRYPTO_TYPE_NAME_LEN 64
88
89#define MAX_KEY_LEN 48
90#define SALT_LEN 16
91#define SCRYPT_LEN 32
92
93/* definitions of flags in the structure below */
94#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
95#define CRYPT_ENCRYPTION_IN_PROGRESS \
96 0x2 /* Encryption partially completed, \
97 encrypted_upto valid*/
98#define CRYPT_INCONSISTENT_STATE \
99 0x4 /* Set when starting encryption, clear when \
100 exit cleanly, either through success or \
101 correctly marked partial encryption */
102#define CRYPT_DATA_CORRUPT \
103 0x8 /* Set when encryption is fine, but the \
104 underlying volume is corrupt */
105#define CRYPT_FORCE_ENCRYPTION \
106 0x10 /* Set when it is time to encrypt this \
107 volume on boot. Everything in this \
108 structure is set up correctly as \
109 though device is encrypted except \
110 that the master key is encrypted with the \
111 default password. */
112#define CRYPT_FORCE_COMPLETE \
113 0x20 /* Set when the above encryption cycle is \
114 complete. On next cryptkeeper entry, match \
115 the password. If it matches fix the master \
116 key and remove this flag. */
117
118/* Allowed values for type in the structure below */
119#define CRYPT_TYPE_PASSWORD \
120 0 /* master_key is encrypted with a password \
121 * Must be zero to be compatible with pre-L \
122 * devices where type is always password.*/
123#define CRYPT_TYPE_DEFAULT \
124 1 /* master_key is encrypted with default \
125 * password */
126#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
127#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
128#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
129
130#define CRYPT_MNT_MAGIC 0xD0B5B1C4
131#define PERSIST_DATA_MAGIC 0xE950CD44
132
133/* Key Derivation Function algorithms */
134#define KDF_PBKDF2 1
135#define KDF_SCRYPT 2
136/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
137#define KDF_SCRYPT_KEYMASTER 5
138
139/* Maximum allowed keymaster blob size. */
140#define KEYMASTER_BLOB_SIZE 2048
141
142/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
143#define __le8 unsigned char
144
145#if !defined(SHA256_DIGEST_LENGTH)
146#define SHA256_DIGEST_LENGTH 32
147#endif
148
149/* This structure starts 16,384 bytes before the end of a hardware
150 * partition that is encrypted, or in a separate partition. It's location
151 * is specified by a property set in init.<device>.rc.
152 * The structure allocates 48 bytes for a key, but the real key size is
153 * specified in the struct. Currently, the code is hardcoded to use 128
154 * bit keys.
155 * The fields after salt are only valid in rev 1.1 and later stuctures.
156 * Obviously, the filesystem does not include the last 16 kbytes
157 * of the partition if the crypt_mnt_ftr lives at the end of the
158 * partition.
159 */
160
161struct crypt_mnt_ftr {
162 __le32 magic; /* See above */
163 __le16 major_version;
164 __le16 minor_version;
165 __le32 ftr_size; /* in bytes, not including key following */
166 __le32 flags; /* See above */
167 __le32 keysize; /* in bytes */
168 __le32 crypt_type; /* how master_key is encrypted. Must be a
169 * CRYPT_TYPE_XXX value */
170 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
171 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
172 mount, set to 0 on successful mount */
173 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
174 needed to decrypt this
175 partition, null terminated */
176 __le32 spare2; /* ignored */
177 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
178 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
179 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
180 * on device with that info, either the footer of the
181 * real_blkdevice or the metadata partition. */
182
183 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
184 * persistent data table*/
185
186 __le8 kdf_type; /* The key derivation function used. */
187
188 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
189 __le8 N_factor; /* (1 << N) */
190 __le8 r_factor; /* (1 << r) */
191 __le8 p_factor; /* (1 << p) */
192 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
193 we have to stop (e.g. power low) this is the last
194 encrypted 512 byte sector.*/
195 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
196 set, hash of first block, used
197 to validate before continuing*/
198
199 /* key_master key, used to sign the derived key which is then used to generate
200 * the intermediate key
201 * This key should be used for no other purposes! We use this key to sign unpadded
202 * data, which is acceptable but only if the key is not reused elsewhere. */
203 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
204 __le32 keymaster_blob_size;
205
206 /* Store scrypt of salted intermediate key. When decryption fails, we can
207 check if this matches, and if it does, we know that the problem is with the
208 drive, and there is no point in asking the user for more passwords.
209
210 Note that if any part of this structure is corrupt, this will not match and
211 we will continue to believe the user entered the wrong password. In that
212 case the only solution is for the user to enter a password enough times to
213 force a wipe.
214
215 Note also that there is no need to worry about migration. If this data is
216 wrong, we simply won't recognise a right password, and will continue to
217 prompt. On the first password change, this value will be populated and
218 then we will be OK.
219 */
220 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
221
222 /* sha of this structure with this element set to zero
223 Used when encrypting on reboot to validate structure before doing something
224 fatal
225 */
226 unsigned char sha256[SHA256_DIGEST_LENGTH];
227};
228
229/* Persistant data that should be available before decryption.
230 * Things like airplane mode, locale and timezone are kept
231 * here and can be retrieved by the CryptKeeper UI to properly
232 * configure the phone before asking for the password
233 * This is only valid if the major and minor version above
234 * is set to 1.1 or higher.
235 *
236 * This is a 4K structure. There are 2 copies, and the code alternates
237 * writing one and then clearing the previous one. The reading
238 * code reads the first valid copy it finds, based on the magic number.
239 * The absolute offset to the first of the two copies is kept in rev 1.1
240 * and higher crypt_mnt_ftr structures.
241 */
242struct crypt_persist_entry {
243 char key[PROPERTY_KEY_MAX];
244 char val[PROPERTY_VALUE_MAX];
245};
246
247/* Should be exactly 4K in size */
248struct crypt_persist_data {
249 __le32 persist_magic;
250 __le32 persist_valid_entries;
251 __le32 persist_spare[30];
252 struct crypt_persist_entry persist_entry[0];
253};
254
255static int wait_and_unmount(const char* mountpoint, bool kill);
256
257typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
258 void* params);
259
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800260#define UNUSED __attribute__((unused))
261
Jason parks70a4b3f2011-01-28 10:10:47 -0600262#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800263
264constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
265constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700266constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800267
268// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700269static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600270
Paul Crowley14c8c072018-09-18 13:30:21 -0700271#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700272
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700273#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800274
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800275#define CRYPTO_BLOCK_DEVICE "userdata"
276
277#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
278
Ken Sumrall29d8da82011-05-18 17:20:07 -0700279#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700280#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700281
Ken Sumralle919efe2012-09-29 17:07:41 -0700282#define TABLE_LOAD_RETRIES 10
283
Shawn Willden47ba10d2014-09-03 17:07:06 -0600284#define RSA_KEY_SIZE 2048
285#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
286#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600287#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700288
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700289#define RETRY_MOUNT_ATTEMPTS 10
290#define RETRY_MOUNT_DELAY_SECONDS 1
291
Paul Crowley5afbc622017-11-27 09:42:17 -0800292#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
293
Paul Crowley73473332017-11-21 15:43:51 -0800294static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
295
Greg Kaiser59ad0182018-02-16 13:01:36 -0800296static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700297static char* saved_mount_point;
298static int master_key_saved = 0;
299static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800300
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700301/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700302static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000303 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700304}
305
306/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700307static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800308 if (ftr->keymaster_blob_size) {
309 SLOGI("Already have key");
310 return 0;
311 }
312
Paul Crowley14c8c072018-09-18 13:30:21 -0700313 int rc = keymaster_create_key_for_cryptfs_scrypt(
314 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
315 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000316 if (rc) {
317 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800318 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000319 ftr->keymaster_blob_size = 0;
320 }
321 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700322 return -1;
323 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000324 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700325}
326
Shawn Willdene17a9c42014-09-08 13:04:08 -0600327/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700328static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
329 const size_t object_size, unsigned char** signature,
330 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600331 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600332 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600333 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600334
Shawn Willdene17a9c42014-09-08 13:04:08 -0600335 // To sign a message with RSA, the message must satisfy two
336 // constraints:
337 //
338 // 1. The message, when interpreted as a big-endian numeric value, must
339 // be strictly less than the public modulus of the RSA key. Note
340 // that because the most significant bit of the public modulus is
341 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
342 // key), an n-bit message with most significant bit 0 always
343 // satisfies this requirement.
344 //
345 // 2. The message must have the same length in bits as the public
346 // modulus of the RSA key. This requirement isn't mathematically
347 // necessary, but is necessary to ensure consistency in
348 // implementations.
349 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600350 case KDF_SCRYPT_KEYMASTER:
351 // This ensures the most significant byte of the signed message
352 // is zero. We could have zero-padded to the left instead, but
353 // this approach is slightly more robust against changes in
354 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600355 // so) because we really should be using a proper deterministic
356 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800357 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600358 SLOGI("Signing safely-padded object");
359 break;
360 default:
361 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000362 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600363 }
Paul Crowley73473332017-11-21 15:43:51 -0800364 for (;;) {
365 auto result = keymaster_sign_object_for_cryptfs_scrypt(
366 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
367 to_sign_size, signature, signature_size);
368 switch (result) {
369 case KeymasterSignResult::ok:
370 return 0;
371 case KeymasterSignResult::upgrade:
372 break;
373 default:
374 return -1;
375 }
376 SLOGD("Upgrading key");
377 if (keymaster_upgrade_key_for_cryptfs_scrypt(
378 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
379 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
380 &ftr->keymaster_blob_size) != 0) {
381 SLOGE("Failed to upgrade key");
382 return -1;
383 }
384 if (put_crypt_ftr_and_key(ftr) != 0) {
385 SLOGE("Failed to write upgraded key to disk");
386 }
387 SLOGD("Key upgraded successfully");
388 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600389}
390
Paul Lawrence399317e2014-03-10 13:20:50 -0700391/* Store password when userdata is successfully decrypted and mounted.
392 * Cleared by cryptfs_clear_password
393 *
394 * To avoid a double prompt at boot, we need to store the CryptKeeper
395 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
396 * Since the entire framework is torn down and rebuilt after encryption,
397 * we have to use a daemon or similar to store the password. Since vold
398 * is secured against IPC except from system processes, it seems a reasonable
399 * place to store this.
400 *
401 * password should be cleared once it has been used.
402 *
403 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800404 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700405static char* password = 0;
406static int password_expiry_time = 0;
407static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800408
Paul Crowley14c8c072018-09-18 13:30:21 -0700409enum class RebootType { reboot, recovery, shutdown };
410static void cryptfs_reboot(RebootType rt) {
411 switch (rt) {
412 case RebootType::reboot:
413 property_set(ANDROID_RB_PROPERTY, "reboot");
414 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800415
Paul Crowley14c8c072018-09-18 13:30:21 -0700416 case RebootType::recovery:
417 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
418 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800419
Paul Crowley14c8c072018-09-18 13:30:21 -0700420 case RebootType::shutdown:
421 property_set(ANDROID_RB_PROPERTY, "shutdown");
422 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700423 }
Paul Lawrence87999172014-02-20 12:21:31 -0800424
Ken Sumralladfba362013-06-04 16:37:52 -0700425 sleep(20);
426
427 /* Shouldn't get here, reboot should happen before sleep times out */
428 return;
429}
430
Greg Kaiser38723f22018-02-16 13:35:35 -0800431namespace {
432
433struct CryptoType;
434
435// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700436const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800437
438struct CryptoType {
439 // We should only be constructing CryptoTypes as part of
440 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
441 // which isn't pure or fully protected as a concession to being able to
442 // do it all at compile time. Add new CryptoTypes in
443 // supported_crypto_types[] below.
444 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
445 constexpr CryptoType set_keysize(uint32_t size) const {
446 return CryptoType(this->property_name, this->crypto_name, size);
447 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700448 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800449 return CryptoType(property, this->crypto_name, this->keysize);
450 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700451 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800452 return CryptoType(this->property_name, crypto, this->keysize);
453 }
454
Paul Crowley14c8c072018-09-18 13:30:21 -0700455 constexpr const char* get_property_name() const { return property_name; }
456 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800457 constexpr uint32_t get_keysize() const { return keysize; }
458
Paul Crowley14c8c072018-09-18 13:30:21 -0700459 private:
460 const char* property_name;
461 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800462 uint32_t keysize;
463
Paul Crowley14c8c072018-09-18 13:30:21 -0700464 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800465 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700466 friend const CryptoType& get_crypto_type();
467 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800468};
469
470// We only want to parse this read-only property once. But we need to wait
471// until the system is initialized before we can read it. So we use a static
472// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700473const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800474 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
475 return crypto_type;
476}
477
478constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700479 .set_property_name("AES-128-CBC")
480 .set_crypto_name("aes-cbc-essiv:sha256")
481 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800482
483constexpr CryptoType supported_crypto_types[] = {
484 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800485 CryptoType()
486 .set_property_name("adiantum")
487 .set_crypto_name("xchacha12,aes-adiantum-plain64")
488 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800489 // Add new CryptoTypes here. Order is not important.
490};
491
Greg Kaiser38723f22018-02-16 13:35:35 -0800492// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
493// We confirm all supported_crypto_types have a small enough keysize and
494// had both set_property_name() and set_crypto_name() called.
495
496template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700497constexpr size_t array_length(T (&)[N]) {
498 return N;
499}
Greg Kaiser38723f22018-02-16 13:35:35 -0800500
501constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
502 return (index >= array_length(supported_crypto_types));
503}
504
Paul Crowley14c8c072018-09-18 13:30:21 -0700505constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800506 return ((crypto_type.get_property_name() != nullptr) &&
507 (crypto_type.get_crypto_name() != nullptr) &&
508 (crypto_type.get_keysize() <= MAX_KEY_LEN));
509}
510
511// Note in C++11 that constexpr functions can only have a single line.
512// So our code is a bit convoluted (using recursion instead of a loop),
513// but it's asserting at compile time that all of our key lengths are valid.
514constexpr bool validateSupportedCryptoTypes(size_t index) {
515 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700516 (isValidCryptoType(supported_crypto_types[index]) &&
517 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800518}
519
520static_assert(validateSupportedCryptoTypes(0),
521 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
522 "incompletely constructed.");
523// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
524
Greg Kaiser38723f22018-02-16 13:35:35 -0800525// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700526const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800527 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
528 char paramstr[PROPERTY_VALUE_MAX];
529
Paul Crowley14c8c072018-09-18 13:30:21 -0700530 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
531 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800532 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
533 return ctype;
534 }
535 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700536 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
537 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800538 return default_crypto_type;
539}
540
541} // namespace
542
Kenny Rootc4c70f12013-06-14 12:11:38 -0700543/**
544 * Gets the default device scrypt parameters for key derivation time tuning.
545 * The parameters should lead to about one second derivation time for the
546 * given device.
547 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700548static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700549 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000550 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700551
Paul Crowley63c18d32016-02-10 14:02:47 +0000552 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
553 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
554 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
555 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700556 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000557 ftr->N_factor = Nf;
558 ftr->r_factor = rf;
559 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700560}
561
Greg Kaiser57f9af62018-02-16 13:13:58 -0800562uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800563 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800564}
565
Paul Crowley14c8c072018-09-18 13:30:21 -0700566const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800567 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800568}
569
Tom Cherry4c5bde22019-01-29 14:34:01 -0800570static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800571 int fd, block_size;
572 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200573 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800574
Paul Crowley14c8c072018-09-18 13:30:21 -0700575 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800576 SLOGE("Cannot open device to get filesystem size ");
577 return 0;
578 }
579
580 if (lseek64(fd, 1024, SEEK_SET) < 0) {
581 SLOGE("Cannot seek to superblock");
582 return 0;
583 }
584
585 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
586 SLOGE("Cannot read superblock");
587 return 0;
588 }
589
590 close(fd);
591
Daniel Rosenberge82df162014-08-15 22:19:23 +0000592 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
593 SLOGE("Not a valid ext4 superblock");
594 return 0;
595 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800596 block_size = 1024 << sb.s_log_block_size;
597 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200598 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800599
600 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200601 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800602}
603
Tom Cherry4c5bde22019-01-29 14:34:01 -0800604static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
605 for (const auto& entry : fstab_default) {
606 if (!entry.fs_mgr_flags.vold_managed &&
607 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
608 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
609 if (key_loc != nullptr) {
610 *key_loc = entry.key_loc;
611 }
612 if (real_blk_device != nullptr) {
613 *real_blk_device = entry.blk_device;
614 }
615 return;
616 }
617 }
618}
619
Paul Crowley14c8c072018-09-18 13:30:21 -0700620static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
621 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200622 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700623 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700624 char key_loc[PROPERTY_VALUE_MAX];
625 char real_blkdev[PROPERTY_VALUE_MAX];
626 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627
Paul Crowley14c8c072018-09-18 13:30:21 -0700628 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800629 std::string key_loc;
630 std::string real_blkdev;
631 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700632
Tom Cherry4c5bde22019-01-29 14:34:01 -0800633 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200634 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700635 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
636 * encryption info footer and key, and plenty of bytes to spare for future
637 * growth.
638 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800639 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200640 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700641 cached_data = 1;
642 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800643 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700644 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700645 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800646 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700647 cached_off = 0;
648 cached_data = 1;
649 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700650 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700651
Paul Crowley14c8c072018-09-18 13:30:21 -0700652 if (cached_data) {
653 if (metadata_fname) {
654 *metadata_fname = cached_metadata_fname;
655 }
656 if (off) {
657 *off = cached_off;
658 }
659 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700660 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700661
Paul Crowley14c8c072018-09-18 13:30:21 -0700662 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700663}
664
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800665/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700666static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800667 SHA256_CTX c;
668 SHA256_Init(&c);
669 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
670 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
671 SHA256_Final(crypt_ftr->sha256, &c);
672}
673
Ken Sumralle8744072011-01-18 22:01:55 -0800674/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800675 * update the failed mount count but not change the key.
676 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700677static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
678 int fd;
679 unsigned int cnt;
680 /* starting_off is set to the SEEK_SET offset
681 * where the crypto structure starts
682 */
683 off64_t starting_off;
684 int rc = -1;
685 char* fname = NULL;
686 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800687
Paul Crowley14c8c072018-09-18 13:30:21 -0700688 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800689
Paul Crowley14c8c072018-09-18 13:30:21 -0700690 if (get_crypt_ftr_info(&fname, &starting_off)) {
691 SLOGE("Unable to get crypt_ftr_info\n");
692 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800693 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700694 if (fname[0] != '/') {
695 SLOGE("Unexpected value for crypto key location\n");
696 return -1;
697 }
698 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
699 SLOGE("Cannot open footer file %s for put\n", fname);
700 return -1;
701 }
Ken Sumralle8744072011-01-18 22:01:55 -0800702
Paul Crowley14c8c072018-09-18 13:30:21 -0700703 /* Seek to the start of the crypt footer */
704 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
705 SLOGE("Cannot seek to real block device footer\n");
706 goto errout;
707 }
708
709 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
710 SLOGE("Cannot write real block device footer\n");
711 goto errout;
712 }
713
714 fstat(fd, &statbuf);
715 /* If the keys are kept on a raw block device, do not try to truncate it. */
716 if (S_ISREG(statbuf.st_mode)) {
717 if (ftruncate(fd, 0x4000)) {
718 SLOGE("Cannot set footer file size\n");
719 goto errout;
720 }
721 }
722
723 /* Success! */
724 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800725
726errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700727 close(fd);
728 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800729}
730
Paul Crowley14c8c072018-09-18 13:30:21 -0700731static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800732 struct crypt_mnt_ftr copy;
733 memcpy(&copy, crypt_ftr, sizeof(copy));
734 set_ftr_sha(&copy);
735 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
736}
737
Paul Crowley14c8c072018-09-18 13:30:21 -0700738static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700739 return TEMP_FAILURE_RETRY(read(fd, buff, len));
740}
741
Paul Crowley14c8c072018-09-18 13:30:21 -0700742static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700743 return TEMP_FAILURE_RETRY(write(fd, buff, len));
744}
745
Paul Crowley14c8c072018-09-18 13:30:21 -0700746static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700747 memset(pdata, 0, len);
748 pdata->persist_magic = PERSIST_DATA_MAGIC;
749 pdata->persist_valid_entries = 0;
750}
751
752/* A routine to update the passed in crypt_ftr to the lastest version.
753 * fd is open read/write on the device that holds the crypto footer and persistent
754 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
755 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
756 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700757static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700758 int orig_major = crypt_ftr->major_version;
759 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700760
Kenny Root7434b312013-06-14 11:29:53 -0700761 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700762 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700763 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700764
Kenny Rootc4c70f12013-06-14 12:11:38 -0700765 SLOGW("upgrading crypto footer to 1.1");
766
Paul Crowley14c8c072018-09-18 13:30:21 -0700767 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700768 if (pdata == NULL) {
769 SLOGE("Cannot allocate persisent data\n");
770 return;
771 }
772 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
773
774 /* Need to initialize the persistent data area */
775 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
776 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100777 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700778 return;
779 }
780 /* Write all zeros to the first copy, making it invalid */
781 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
782
783 /* Write a valid but empty structure to the second copy */
784 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
785 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
786
787 /* Update the footer */
788 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
789 crypt_ftr->persist_data_offset[0] = pdata_offset;
790 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
791 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100792 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700793 }
794
Paul Lawrencef4faa572014-01-29 13:31:03 -0800795 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700796 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800797 /* But keep the old kdf_type.
798 * It will get updated later to KDF_SCRYPT after the password has been verified.
799 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700800 crypt_ftr->kdf_type = KDF_PBKDF2;
801 get_device_scrypt_params(crypt_ftr);
802 crypt_ftr->minor_version = 2;
803 }
804
Paul Lawrencef4faa572014-01-29 13:31:03 -0800805 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
806 SLOGW("upgrading crypto footer to 1.3");
807 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
808 crypt_ftr->minor_version = 3;
809 }
810
Kenny Root7434b312013-06-14 11:29:53 -0700811 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
812 if (lseek64(fd, offset, SEEK_SET) == -1) {
813 SLOGE("Cannot seek to crypt footer\n");
814 return;
815 }
816 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700817 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700818}
819
Paul Crowley14c8c072018-09-18 13:30:21 -0700820static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
821 int fd;
822 unsigned int cnt;
823 off64_t starting_off;
824 int rc = -1;
825 char* fname = NULL;
826 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700827
Paul Crowley14c8c072018-09-18 13:30:21 -0700828 if (get_crypt_ftr_info(&fname, &starting_off)) {
829 SLOGE("Unable to get crypt_ftr_info\n");
830 return -1;
831 }
832 if (fname[0] != '/') {
833 SLOGE("Unexpected value for crypto key location\n");
834 return -1;
835 }
836 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
837 SLOGE("Cannot open footer file %s for get\n", fname);
838 return -1;
839 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800840
Paul Crowley14c8c072018-09-18 13:30:21 -0700841 /* Make sure it's 16 Kbytes in length */
842 fstat(fd, &statbuf);
843 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
844 SLOGE("footer file %s is not the expected size!\n", fname);
845 goto errout;
846 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700847
Paul Crowley14c8c072018-09-18 13:30:21 -0700848 /* Seek to the start of the crypt footer */
849 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
850 SLOGE("Cannot seek to real block device footer\n");
851 goto errout;
852 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700853
Paul Crowley14c8c072018-09-18 13:30:21 -0700854 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
855 SLOGE("Cannot read real block device footer\n");
856 goto errout;
857 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800858
Paul Crowley14c8c072018-09-18 13:30:21 -0700859 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
860 SLOGE("Bad magic for real block device %s\n", fname);
861 goto errout;
862 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800863
Paul Crowley14c8c072018-09-18 13:30:21 -0700864 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
865 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
866 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
867 goto errout;
868 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800869
Paul Crowley14c8c072018-09-18 13:30:21 -0700870 // We risk buffer overflows with oversized keys, so we just reject them.
871 // 0-sized keys are problematic (essentially by-passing encryption), and
872 // AES-CBC key wrapping only works for multiples of 16 bytes.
873 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
874 (crypt_ftr->keysize > MAX_KEY_LEN)) {
875 SLOGE(
876 "Invalid keysize (%u) for block device %s; Must be non-zero, "
877 "divisible by 16, and <= %d\n",
878 crypt_ftr->keysize, fname, MAX_KEY_LEN);
879 goto errout;
880 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800881
Paul Crowley14c8c072018-09-18 13:30:21 -0700882 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
883 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
884 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
885 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800886
Paul Crowley14c8c072018-09-18 13:30:21 -0700887 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
888 * copy on disk before returning.
889 */
890 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
891 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
892 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800893
Paul Crowley14c8c072018-09-18 13:30:21 -0700894 /* Success! */
895 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800896
897errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700898 close(fd);
899 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800900}
901
Paul Crowley14c8c072018-09-18 13:30:21 -0700902static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700903 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
904 crypt_ftr->persist_data_offset[1]) {
905 SLOGE("Crypt_ftr persist data regions overlap");
906 return -1;
907 }
908
909 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
910 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
911 return -1;
912 }
913
914 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700915 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700916 CRYPT_FOOTER_OFFSET) {
917 SLOGE("Persistent data extends past crypto footer");
918 return -1;
919 }
920
921 return 0;
922}
923
Paul Crowley14c8c072018-09-18 13:30:21 -0700924static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700925 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700926 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700927 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700928 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700929 int found = 0;
930 int fd;
931 int ret;
932 int i;
933
934 if (persist_data) {
935 /* Nothing to do, we've already loaded or initialized it */
936 return 0;
937 }
938
Ken Sumrall160b4d62013-04-22 12:15:39 -0700939 /* If not encrypted, just allocate an empty table and initialize it */
940 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700941 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800942 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700943 if (pdata) {
944 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
945 persist_data = pdata;
946 return 0;
947 }
948 return -1;
949 }
950
Paul Crowley14c8c072018-09-18 13:30:21 -0700951 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700952 return -1;
953 }
954
Paul Crowley14c8c072018-09-18 13:30:21 -0700955 if ((crypt_ftr.major_version < 1) ||
956 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700957 SLOGE("Crypt_ftr version doesn't support persistent data");
958 return -1;
959 }
960
961 if (get_crypt_ftr_info(&fname, NULL)) {
962 return -1;
963 }
964
965 ret = validate_persistent_data_storage(&crypt_ftr);
966 if (ret) {
967 return -1;
968 }
969
Paul Crowley14c8c072018-09-18 13:30:21 -0700970 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700971 if (fd < 0) {
972 SLOGE("Cannot open %s metadata file", fname);
973 return -1;
974 }
975
Wei Wang4375f1b2017-02-24 17:43:01 -0800976 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800977 if (pdata == NULL) {
978 SLOGE("Cannot allocate memory for persistent data");
979 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700980 }
981
982 for (i = 0; i < 2; i++) {
983 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
984 SLOGE("Cannot seek to read persistent data on %s", fname);
985 goto err2;
986 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700987 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700988 SLOGE("Error reading persistent data on iteration %d", i);
989 goto err2;
990 }
991 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
992 found = 1;
993 break;
994 }
995 }
996
997 if (!found) {
998 SLOGI("Could not find valid persistent data, creating");
999 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
1000 }
1001
1002 /* Success */
1003 persist_data = pdata;
1004 close(fd);
1005 return 0;
1006
1007err2:
1008 free(pdata);
1009
1010err:
1011 close(fd);
1012 return -1;
1013}
1014
Paul Crowley14c8c072018-09-18 13:30:21 -07001015static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001016 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001017 struct crypt_persist_data* pdata;
1018 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001019 off64_t write_offset;
1020 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001021 int fd;
1022 int ret;
1023
1024 if (persist_data == NULL) {
1025 SLOGE("No persistent data to save");
1026 return -1;
1027 }
1028
Paul Crowley14c8c072018-09-18 13:30:21 -07001029 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001030 return -1;
1031 }
1032
Paul Crowley14c8c072018-09-18 13:30:21 -07001033 if ((crypt_ftr.major_version < 1) ||
1034 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001035 SLOGE("Crypt_ftr version doesn't support persistent data");
1036 return -1;
1037 }
1038
1039 ret = validate_persistent_data_storage(&crypt_ftr);
1040 if (ret) {
1041 return -1;
1042 }
1043
1044 if (get_crypt_ftr_info(&fname, NULL)) {
1045 return -1;
1046 }
1047
Paul Crowley14c8c072018-09-18 13:30:21 -07001048 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001049 if (fd < 0) {
1050 SLOGE("Cannot open %s metadata file", fname);
1051 return -1;
1052 }
1053
Wei Wang4375f1b2017-02-24 17:43:01 -08001054 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001055 if (pdata == NULL) {
1056 SLOGE("Cannot allocate persistant data");
1057 goto err;
1058 }
1059
1060 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1061 SLOGE("Cannot seek to read persistent data on %s", fname);
1062 goto err2;
1063 }
1064
1065 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001066 SLOGE("Error reading persistent data before save");
1067 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001068 }
1069
1070 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1071 /* The first copy is the curent valid copy, so write to
1072 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001073 write_offset = crypt_ftr.persist_data_offset[1];
1074 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001075 } else {
1076 /* The second copy must be the valid copy, so write to
1077 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001078 write_offset = crypt_ftr.persist_data_offset[0];
1079 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001080 }
1081
1082 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001083 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001084 SLOGE("Cannot seek to write persistent data");
1085 goto err2;
1086 }
1087 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001088 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001089 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001090 SLOGE("Cannot seek to erase previous persistent data");
1091 goto err2;
1092 }
1093 fsync(fd);
1094 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001095 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001096 SLOGE("Cannot write to erase previous persistent data");
1097 goto err2;
1098 }
1099 fsync(fd);
1100 } else {
1101 SLOGE("Cannot write to save persistent data");
1102 goto err2;
1103 }
1104
1105 /* Success */
1106 free(pdata);
1107 close(fd);
1108 return 0;
1109
1110err2:
1111 free(pdata);
1112err:
1113 close(fd);
1114 return -1;
1115}
1116
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117/* Convert a binary key of specified length into an ascii hex string equivalent,
1118 * without the leading 0x and with null termination
1119 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001120static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1121 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001122 unsigned int i, a;
1123 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001124
Paul Crowley14c8c072018-09-18 13:30:21 -07001125 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001126 /* For each byte, write out two ascii hex digits */
1127 nibble = (master_key[i] >> 4) & 0xf;
1128 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001130 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001131 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001132 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001133
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001134 /* Add the null termination */
1135 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001136}
1137
Eric Biggersed45ec32019-01-25 10:47:55 -08001138/*
1139 * If the ro.crypto.fde_sector_size system property is set, append the
1140 * parameters to make dm-crypt use the specified crypto sector size and round
1141 * the crypto device size down to a crypto sector boundary.
1142 */
David Andersonb9224732019-05-13 13:02:54 -07001143static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001144 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001145 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001146
Eric Biggersed45ec32019-01-25 10:47:55 -08001147 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1148 unsigned int sector_size;
1149
1150 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1151 (sector_size & (sector_size - 1)) != 0) {
1152 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1153 DM_CRYPT_SECTOR_SIZE, value);
1154 return -1;
1155 }
1156
David Andersonb9224732019-05-13 13:02:54 -07001157 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001158
1159 // With this option, IVs will match the sector numbering, instead
1160 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001161 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001162
1163 // Round the crypto device size down to a crypto sector boundary.
1164 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001165 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001166 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001167}
1168
Paul Crowley5afbc622017-11-27 09:42:17 -08001169static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001170 const char* real_blk_name, std::string* crypto_blk_name,
1171 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001172 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001173
David Andersonb9224732019-05-13 13:02:54 -07001174 // We need two ASCII characters to represent each byte, and need space for
1175 // the '\0' terminator.
1176 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1177 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001178
David Andersonb9224732019-05-13 13:02:54 -07001179 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1180 (const char*)crypt_ftr->crypto_type_name,
1181 master_key_ascii, 0, real_blk_name, 0);
1182 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001183
Paul Crowley5afbc622017-11-27 09:42:17 -08001184 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001185 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001186 }
David Andersonb9224732019-05-13 13:02:54 -07001187 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001188 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001189 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001190 }
David Andersonb9224732019-05-13 13:02:54 -07001191
1192 DmTable table;
1193 table.AddTarget(std::move(target));
1194
1195 int load_count = 1;
1196 while (load_count < TABLE_LOAD_RETRIES) {
1197 if (dm.CreateDevice(name, table)) {
1198 break;
1199 }
1200 load_count++;
1201 }
1202
1203 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001204 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001205 return -1;
1206 }
1207 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001208 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1209 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210
Paul Crowley81796e92020-02-07 11:27:49 -08001211 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001212 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1213 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001214 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001215
Paul Crowleycfe39722018-10-30 15:59:24 -07001216 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001217 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001218 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001219 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001220 }
David Andersonb9224732019-05-13 13:02:54 -07001221 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001222}
1223
David Andersonb9224732019-05-13 13:02:54 -07001224static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001225 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001226 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001227 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1228 // to delete the device fails with EBUSY; for now, work around this by retrying.
1229 int tries = 5;
1230 while (tries-- > 0) {
1231 ret = dm.DeleteDevice(name);
1232 if (ret || errno != EBUSY) {
1233 break;
1234 }
1235 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1236 strerror(errno));
1237 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1238 }
1239 if (!ret) {
1240 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001241 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001242 }
David Andersonb9224732019-05-13 13:02:54 -07001243 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244}
1245
Paul Crowley14c8c072018-09-18 13:30:21 -07001246static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1247 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001248 SLOGI("Using pbkdf2 for cryptfs KDF");
1249
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001251 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1252 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001253}
1254
Paul Crowley14c8c072018-09-18 13:30:21 -07001255static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001256 SLOGI("Using scrypt for cryptfs KDF");
1257
Paul Crowley14c8c072018-09-18 13:30:21 -07001258 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001259
1260 int N = 1 << ftr->N_factor;
1261 int r = 1 << ftr->r_factor;
1262 int p = 1 << ftr->p_factor;
1263
1264 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001265 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001266 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001267
Paul Crowley14c8c072018-09-18 13:30:21 -07001268 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001269}
1270
Paul Crowley14c8c072018-09-18 13:30:21 -07001271static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1272 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001273 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1274
1275 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001276 size_t signature_size;
1277 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001278 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001279
1280 int N = 1 << ftr->N_factor;
1281 int r = 1 << ftr->r_factor;
1282 int p = 1 << ftr->p_factor;
1283
Paul Crowley14c8c072018-09-18 13:30:21 -07001284 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001285 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001286
1287 if (rc) {
1288 SLOGE("scrypt failed");
1289 return -1;
1290 }
1291
Paul Crowley14c8c072018-09-18 13:30:21 -07001292 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001293 SLOGE("Signing failed");
1294 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001295 }
1296
Paul Crowley14c8c072018-09-18 13:30:21 -07001297 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1298 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001299 free(signature);
1300
1301 if (rc) {
1302 SLOGE("scrypt failed");
1303 return -1;
1304 }
1305
1306 return 0;
1307}
1308
Paul Crowley14c8c072018-09-18 13:30:21 -07001309static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1310 const unsigned char* decrypted_master_key,
1311 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1312 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001313 EVP_CIPHER_CTX e_ctx;
1314 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001315 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001316
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001317 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001318 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001319
1320 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001321 case KDF_SCRYPT_KEYMASTER:
1322 if (keymaster_create_key(crypt_ftr)) {
1323 SLOGE("keymaster_create_key failed");
1324 return -1;
1325 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001326
Paul Crowley14c8c072018-09-18 13:30:21 -07001327 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1328 SLOGE("scrypt failed");
1329 return -1;
1330 }
1331 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001332
Paul Crowley14c8c072018-09-18 13:30:21 -07001333 case KDF_SCRYPT:
1334 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1335 SLOGE("scrypt failed");
1336 return -1;
1337 }
1338 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001339
Paul Crowley14c8c072018-09-18 13:30:21 -07001340 default:
1341 SLOGE("Invalid kdf_type");
1342 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001343 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001344
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001345 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001346 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001347 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1348 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349 SLOGE("EVP_EncryptInit failed\n");
1350 return -1;
1351 }
1352 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001353
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001355 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1356 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357 SLOGE("EVP_EncryptUpdate failed\n");
1358 return -1;
1359 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001360 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001361 SLOGE("EVP_EncryptFinal failed\n");
1362 return -1;
1363 }
1364
Greg Kaiser59ad0182018-02-16 13:01:36 -08001365 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001366 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1367 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001368 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001369
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001370 /* Store the scrypt of the intermediate key, so we can validate if it's a
1371 password error or mount error when things go wrong.
1372 Note there's no need to check for errors, since if this is incorrect, we
1373 simply won't wipe userdata, which is the correct default behavior
1374 */
1375 int N = 1 << crypt_ftr->N_factor;
1376 int r = 1 << crypt_ftr->r_factor;
1377 int p = 1 << crypt_ftr->p_factor;
1378
Paul Crowley14c8c072018-09-18 13:30:21 -07001379 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1380 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001381 sizeof(crypt_ftr->scrypted_intermediate_key));
1382
1383 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001384 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001385 }
1386
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001387 EVP_CIPHER_CTX_cleanup(&e_ctx);
1388
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001389 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001390}
1391
Paul Crowley14c8c072018-09-18 13:30:21 -07001392static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1393 const unsigned char* encrypted_master_key, size_t keysize,
1394 unsigned char* decrypted_master_key, kdf_func kdf,
1395 void* kdf_params, unsigned char** intermediate_key,
1396 size_t* intermediate_key_size) {
1397 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1398 EVP_CIPHER_CTX d_ctx;
1399 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001400
Paul Crowley14c8c072018-09-18 13:30:21 -07001401 /* Turn the password into an intermediate key and IV that can decrypt the
1402 master key */
1403 if (kdf(passwd, salt, ikey, kdf_params)) {
1404 SLOGE("kdf failed");
1405 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001406 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001407
Paul Crowley14c8c072018-09-18 13:30:21 -07001408 /* Initialize the decryption engine */
1409 EVP_CIPHER_CTX_init(&d_ctx);
1410 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1411 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1412 return -1;
1413 }
1414 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1415 /* Decrypt the master key */
1416 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1417 keysize)) {
1418 return -1;
1419 }
1420 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1421 return -1;
1422 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001423
Paul Crowley14c8c072018-09-18 13:30:21 -07001424 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1425 return -1;
1426 }
1427
1428 /* Copy intermediate key if needed by params */
1429 if (intermediate_key && intermediate_key_size) {
1430 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1431 if (*intermediate_key) {
1432 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1433 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1434 }
1435 }
1436
1437 EVP_CIPHER_CTX_cleanup(&d_ctx);
1438
1439 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001440}
1441
Paul Crowley14c8c072018-09-18 13:30:21 -07001442static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001443 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001444 *kdf = scrypt_keymaster;
1445 *kdf_params = ftr;
1446 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001447 *kdf = scrypt;
1448 *kdf_params = ftr;
1449 } else {
1450 *kdf = pbkdf2;
1451 *kdf_params = NULL;
1452 }
1453}
1454
Paul Crowley14c8c072018-09-18 13:30:21 -07001455static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1456 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1457 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001458 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001459 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001460 int ret;
1461
1462 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001463 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1464 decrypted_master_key, kdf, kdf_params, intermediate_key,
1465 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001466 if (ret != 0) {
1467 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001468 }
1469
1470 return ret;
1471}
1472
Paul Crowley14c8c072018-09-18 13:30:21 -07001473static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1474 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001475 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001476
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001477 /* Get some random bits for a key and salt */
1478 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1479 return -1;
1480 }
1481 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1482 return -1;
1483 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001484
1485 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001486 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001487}
1488
Paul Crowley73be12d2020-02-03 12:22:03 -08001489static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001490 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001491#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001492
1493 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001494 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001495 if (umount(mountpoint) == 0) {
1496 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001497 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001498
1499 if (errno == EINVAL) {
1500 /* EINVAL is returned if the directory is not a mountpoint,
1501 * i.e. there is no filesystem mounted there. So just get out.
1502 */
1503 break;
1504 }
1505
1506 err = errno;
1507
1508 /* If allowed, be increasingly aggressive before the last two retries */
1509 if (kill) {
1510 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1511 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001512 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001513 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1514 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001515 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001516 }
1517 }
1518
1519 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001520 }
1521
1522 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001523 SLOGD("unmounting %s succeeded\n", mountpoint);
1524 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001526 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1527 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1528 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001529 }
1530
1531 return rc;
1532}
1533
Paul Crowley14c8c072018-09-18 13:30:21 -07001534static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001535 // NOTE: post_fs_data results in init calling back around to vold, so all
1536 // callers to this method must be async
1537
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001538 /* Do the prep of the /data filesystem */
1539 property_set("vold.post_fs_data_done", "0");
1540 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001541 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001542
Ken Sumrallc5872692013-05-14 15:26:31 -07001543 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001544 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001545 /* We timed out to prep /data in time. Continue wait. */
1546 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001547 }
Wei Wang42e38102017-06-07 10:46:12 -07001548 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001549}
1550
Paul Crowley14c8c072018-09-18 13:30:21 -07001551static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001552 // Mark the footer as bad
1553 struct crypt_mnt_ftr crypt_ftr;
1554 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1555 SLOGE("Failed to get crypto footer - panic");
1556 return;
1557 }
1558
1559 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1560 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1561 SLOGE("Failed to set crypto footer - panic");
1562 return;
1563 }
1564}
1565
Paul Crowley14c8c072018-09-18 13:30:21 -07001566static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001567 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001568 SLOGE("Failed to mount tmpfs on data - panic");
1569 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001570 }
1571
1572 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1573 SLOGE("Failed to trigger post fs data - panic");
1574 return;
1575 }
1576
1577 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1578 SLOGE("Failed to trigger restart min framework - panic");
1579 return;
1580 }
1581}
1582
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001583/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001584static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001585 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001586 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001587 static int restart_successful = 0;
1588
1589 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001590 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001591 SLOGE("Encrypted filesystem not validated, aborting");
1592 return -1;
1593 }
1594
1595 if (restart_successful) {
1596 SLOGE("System already restarted with encrypted disk, aborting");
1597 return -1;
1598 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001599
Paul Lawrencef4faa572014-01-29 13:31:03 -08001600 if (restart_main) {
1601 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001602 * start all services in one of these classes: core, early_hal, hal,
1603 * main and late_start. To get to the minimal UI for PIN entry, we
1604 * need to start core, early_hal, hal and main. When we want to
1605 * shutdown the framework again, we need to stop most of the services in
1606 * these classes, but only those services that were started after
1607 * /data was mounted. This excludes critical services like vold and
1608 * ueventd, which need to keep running. We could possible stop
1609 * even fewer services, but because we want services to pick up APEX
1610 * libraries from the real /data, restarting is better, as it makes
1611 * these devices consistent with FBE devices and lets them use the
1612 * most recent code.
1613 *
1614 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001615 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001616 * We then restart the class core, hal, main, and also the class
1617 * late_start.
1618 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001619 * At the moment, I've only put a few things in late_start that I know
1620 * are not needed to bring up the framework, and that also cause problems
1621 * with unmounting the tmpfs /data, but I hope to add add more services
1622 * to the late_start class as we optimize this to decrease the delay
1623 * till the user is asked for the password to the filesystem.
1624 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001625
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001626 /* The init files are setup to stop the right set of services when
1627 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001628 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001629 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001630 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631
Paul Lawrencef4faa572014-01-29 13:31:03 -08001632 /* Ugh, shutting down the framework is not synchronous, so until it
1633 * can be fixed, this horrible hack will wait a moment for it all to
1634 * shut down before proceeding. Without it, some devices cannot
1635 * restart the graphics services.
1636 */
1637 sleep(2);
1638 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001639
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001640 /* Now that the framework is shutdown, we should be able to umount()
1641 * the tmpfs filesystem, and mount the real one.
1642 */
1643
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001644 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1645 if (strlen(crypto_blkdev) == 0) {
1646 SLOGE("fs_crypto_blkdev not set\n");
1647 return -1;
1648 }
1649
Paul Crowley14c8c072018-09-18 13:30:21 -07001650 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001651 /* If ro.crypto.readonly is set to 1, mount the decrypted
1652 * filesystem readonly. This is used when /data is mounted by
1653 * recovery mode.
1654 */
1655 char ro_prop[PROPERTY_VALUE_MAX];
1656 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001657 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001658 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1659 if (entry != nullptr) {
1660 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001661 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001662 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001663
Ken Sumralle5032c42012-04-01 23:58:44 -07001664 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001665 int retries = RETRY_MOUNT_ATTEMPTS;
1666 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001667
1668 /*
1669 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1670 * partitions in the fsck domain.
1671 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001672 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001673 SLOGE("Failed to setexeccon");
1674 return -1;
1675 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001676 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001677 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001678 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001679 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1680 /* TODO: invoke something similar to
1681 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1682 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001683 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001684 if (--retries) {
1685 sleep(RETRY_MOUNT_DELAY_SECONDS);
1686 } else {
1687 /* Let's hope that a reboot clears away whatever is keeping
1688 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001689 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001690 }
1691 } else {
1692 SLOGE("Failed to mount decrypted data");
1693 cryptfs_set_corrupt();
1694 cryptfs_trigger_restart_min_framework();
1695 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001696 if (setexeccon(NULL)) {
1697 SLOGE("Failed to setexeccon");
1698 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001699 return -1;
1700 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001701 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001702 if (setexeccon(NULL)) {
1703 SLOGE("Failed to setexeccon");
1704 return -1;
1705 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001706
Ken Sumralle5032c42012-04-01 23:58:44 -07001707 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001708 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001709 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001710
1711 /* startup service classes main and late_start */
1712 property_set("vold.decrypt", "trigger_restart_framework");
1713 SLOGD("Just triggered restart_framework\n");
1714
1715 /* Give it a few moments to get started */
1716 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 }
1718
Ken Sumrall0cc16632011-01-18 20:32:26 -08001719 if (rc == 0) {
1720 restart_successful = 1;
1721 }
1722
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001723 return rc;
1724}
1725
Paul Crowley14c8c072018-09-18 13:30:21 -07001726int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001727 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001728 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001729 SLOGE("cryptfs_restart not valid for file encryption:");
1730 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001731 }
1732
Paul Lawrencef4faa572014-01-29 13:31:03 -08001733 /* Call internal implementation forcing a restart of main service group */
1734 return cryptfs_restart_internal(1);
1735}
1736
Paul Crowley14c8c072018-09-18 13:30:21 -07001737static int do_crypto_complete(const char* mount_point) {
1738 struct crypt_mnt_ftr crypt_ftr;
1739 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001740
Paul Crowley14c8c072018-09-18 13:30:21 -07001741 property_get("ro.crypto.state", encrypted_state, "");
1742 if (strcmp(encrypted_state, "encrypted")) {
1743 SLOGE("not running with encryption, aborting");
1744 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001745 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001746
Paul Crowley14c8c072018-09-18 13:30:21 -07001747 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001748 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001749 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1750 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001751
Paul Crowley14c8c072018-09-18 13:30:21 -07001752 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001753 std::string key_loc;
1754 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001755
Paul Crowley14c8c072018-09-18 13:30:21 -07001756 /*
1757 * Only report this error if key_loc is a file and it exists.
1758 * If the device was never encrypted, and /data is not mountable for
1759 * some reason, returning 1 should prevent the UI from presenting the
1760 * a "enter password" screen, or worse, a "press button to wipe the
1761 * device" screen.
1762 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001763 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001764 SLOGE("master key file does not exist, aborting");
1765 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1766 } else {
1767 SLOGE("Error getting crypt footer and key\n");
1768 return CRYPTO_COMPLETE_BAD_METADATA;
1769 }
1770 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001771
Paul Crowley14c8c072018-09-18 13:30:21 -07001772 // Test for possible error flags
1773 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1774 SLOGE("Encryption process is partway completed\n");
1775 return CRYPTO_COMPLETE_PARTIAL;
1776 }
1777
1778 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1779 SLOGE("Encryption process was interrupted but cannot continue\n");
1780 return CRYPTO_COMPLETE_INCONSISTENT;
1781 }
1782
1783 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1784 SLOGE("Encryption is successful but data is corrupt\n");
1785 return CRYPTO_COMPLETE_CORRUPT;
1786 }
1787
1788 /* We passed the test! We shall diminish, and return to the west */
1789 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001790}
1791
Paul Crowley14c8c072018-09-18 13:30:21 -07001792static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1793 const char* mount_point, const char* label) {
1794 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001795 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001796 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001797 char tmp_mount_point[64];
1798 unsigned int orig_failed_decrypt_count;
1799 int rc;
1800 int use_keymaster = 0;
1801 int upgrade = 0;
1802 unsigned char* intermediate_key = 0;
1803 size_t intermediate_key_size = 0;
1804 int N = 1 << crypt_ftr->N_factor;
1805 int r = 1 << crypt_ftr->r_factor;
1806 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001807
Paul Crowley14c8c072018-09-18 13:30:21 -07001808 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1809 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001810
Paul Crowley14c8c072018-09-18 13:30:21 -07001811 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1812 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1813 &intermediate_key_size)) {
1814 SLOGE("Failed to decrypt master key\n");
1815 rc = -1;
1816 goto errout;
1817 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001818 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001819
Tom Cherry4c5bde22019-01-29 14:34:01 -08001820 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001821
Paul Crowley14c8c072018-09-18 13:30:21 -07001822 // Create crypto block device - all (non fatal) code paths
1823 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001824 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001825 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001826 SLOGE("Error creating decrypted block device\n");
1827 rc = -1;
1828 goto errout;
1829 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001830
Paul Crowley14c8c072018-09-18 13:30:21 -07001831 /* Work out if the problem is the password or the data */
1832 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001833
Paul Crowley14c8c072018-09-18 13:30:21 -07001834 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1835 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1836 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001837
Paul Crowley14c8c072018-09-18 13:30:21 -07001838 // Does the key match the crypto footer?
1839 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1840 sizeof(scrypted_intermediate_key)) == 0) {
1841 SLOGI("Password matches");
1842 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001843 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001844 /* Try mounting the file system anyway, just in case the problem's with
1845 * the footer, not the key. */
1846 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1847 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001848 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1849 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001850 SLOGE("Error temp mounting decrypted block device\n");
1851 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001852
Paul Crowley14c8c072018-09-18 13:30:21 -07001853 rc = ++crypt_ftr->failed_decrypt_count;
1854 put_crypt_ftr_and_key(crypt_ftr);
1855 } else {
1856 /* Success! */
1857 SLOGI("Password did not match but decrypted drive mounted - continue");
1858 umount(tmp_mount_point);
1859 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001860 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001861 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001862
Paul Crowley14c8c072018-09-18 13:30:21 -07001863 if (rc == 0) {
1864 crypt_ftr->failed_decrypt_count = 0;
1865 if (orig_failed_decrypt_count != 0) {
1866 put_crypt_ftr_and_key(crypt_ftr);
1867 }
1868
1869 /* Save the name of the crypto block device
1870 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001871 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001872
1873 /* Also save a the master key so we can reencrypted the key
1874 * the key when we want to change the password on it. */
1875 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1876 saved_mount_point = strdup(mount_point);
1877 master_key_saved = 1;
1878 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1879 rc = 0;
1880
1881 // Upgrade if we're not using the latest KDF.
1882 use_keymaster = keymaster_check_compatibility();
1883 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1884 // Don't allow downgrade
1885 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1886 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1887 upgrade = 1;
1888 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1889 crypt_ftr->kdf_type = KDF_SCRYPT;
1890 upgrade = 1;
1891 }
1892
1893 if (upgrade) {
1894 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1895 crypt_ftr->master_key, crypt_ftr);
1896 if (!rc) {
1897 rc = put_crypt_ftr_and_key(crypt_ftr);
1898 }
1899 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1900
1901 // Do not fail even if upgrade failed - machine is bootable
1902 // Note that if this code is ever hit, there is a *serious* problem
1903 // since KDFs should never fail. You *must* fix the kdf before
1904 // proceeding!
1905 if (rc) {
1906 SLOGW(
1907 "Upgrade failed with error %d,"
1908 " but continuing with previous state",
1909 rc);
1910 rc = 0;
1911 }
1912 }
1913 }
1914
1915errout:
1916 if (intermediate_key) {
1917 memset(intermediate_key, 0, intermediate_key_size);
1918 free(intermediate_key);
1919 }
1920 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001921}
1922
Ken Sumrall29d8da82011-05-18 17:20:07 -07001923/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001924 * Called by vold when it's asked to mount an encrypted external
1925 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001926 * as any metadata is been stored in a separate, small partition. We
1927 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001928 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001929int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
Paul Crowley81796e92020-02-07 11:27:49 -08001930 std::string* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001931 uint64_t nr_sec = 0;
1932 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001933 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001934 return -1;
1935 }
1936
Jeff Sharkey9c484982015-03-31 10:35:33 -07001937 struct crypt_mnt_ftr ext_crypt_ftr;
1938 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1939 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001940 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001941 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001942 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001943 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001944 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001945 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1946 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001947
Paul Crowley385cb8c2018-03-29 13:27:23 -07001948 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001949}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001950
Jeff Sharkey9c484982015-03-31 10:35:33 -07001951/*
1952 * Called by vold when it's asked to unmount an encrypted external
1953 * storage volume.
1954 */
1955int cryptfs_revert_ext_volume(const char* label) {
David Andersonb9224732019-05-13 13:02:54 -07001956 return delete_crypto_blk_dev(label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001957}
1958
Paul Crowley14c8c072018-09-18 13:30:21 -07001959int cryptfs_crypto_complete(void) {
1960 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001961}
1962
Paul Crowley14c8c072018-09-18 13:30:21 -07001963int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001964 char encrypted_state[PROPERTY_VALUE_MAX];
1965 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001966 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1967 SLOGE(
1968 "encrypted fs already validated or not running with encryption,"
1969 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001970 return -1;
1971 }
1972
1973 if (get_crypt_ftr_and_key(crypt_ftr)) {
1974 SLOGE("Error getting crypt footer and key");
1975 return -1;
1976 }
1977
1978 return 0;
1979}
1980
Paul Crowley14c8c072018-09-18 13:30:21 -07001981int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001982 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001983 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001984 SLOGE("cryptfs_check_passwd not valid for file encryption");
1985 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001986 }
1987
Paul Lawrencef4faa572014-01-29 13:31:03 -08001988 struct crypt_mnt_ftr crypt_ftr;
1989 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001990
Paul Lawrencef4faa572014-01-29 13:31:03 -08001991 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001992 if (rc) {
1993 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001994 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001995 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001996
Paul Crowley14c8c072018-09-18 13:30:21 -07001997 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001998 if (rc) {
1999 SLOGE("Password did not match");
2000 return rc;
2001 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002002
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002003 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2004 // Here we have a default actual password but a real password
2005 // we must test against the scrypted value
2006 // First, we must delete the crypto block device that
2007 // test_mount_encrypted_fs leaves behind as a side effect
2008 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002009 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2010 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002011 if (rc) {
2012 SLOGE("Default password did not match on reboot encryption");
2013 return rc;
2014 }
2015
2016 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2017 put_crypt_ftr_and_key(&crypt_ftr);
2018 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2019 if (rc) {
2020 SLOGE("Could not change password on reboot encryption");
2021 return rc;
2022 }
2023 }
2024
2025 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002026 cryptfs_clear_password();
2027 password = strdup(passwd);
2028 struct timespec now;
2029 clock_gettime(CLOCK_BOOTTIME, &now);
2030 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002031 }
2032
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002033 return rc;
2034}
2035
Paul Crowley14c8c072018-09-18 13:30:21 -07002036int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002037 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002038 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002039 char encrypted_state[PROPERTY_VALUE_MAX];
2040 int rc;
2041
2042 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002043 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002044 SLOGE("device not encrypted, aborting");
2045 return -2;
2046 }
2047
2048 if (!master_key_saved) {
2049 SLOGE("encrypted fs not yet mounted, aborting");
2050 return -1;
2051 }
2052
2053 if (!saved_mount_point) {
2054 SLOGE("encrypted fs failed to save mount point, aborting");
2055 return -1;
2056 }
2057
Ken Sumrall160b4d62013-04-22 12:15:39 -07002058 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002059 SLOGE("Error getting crypt footer and key\n");
2060 return -1;
2061 }
2062
2063 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2064 /* If the device has no password, then just say the password is valid */
2065 rc = 0;
2066 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002067 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002068 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2069 /* They match, the password is correct */
2070 rc = 0;
2071 } else {
2072 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2073 sleep(1);
2074 rc = 1;
2075 }
2076 }
2077
2078 return rc;
2079}
2080
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002081/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002082 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002083 * Presumably, at a minimum, the caller will update the
2084 * filesystem size and crypto_type_name after calling this function.
2085 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002086static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002087 off64_t off;
2088
2089 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002090 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002091 ftr->major_version = CURRENT_MAJOR_VERSION;
2092 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002093 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002094 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002095
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002096 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002097 case 1:
2098 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2099 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002100
Paul Crowley14c8c072018-09-18 13:30:21 -07002101 case 0:
2102 ftr->kdf_type = KDF_SCRYPT;
2103 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002104
Paul Crowley14c8c072018-09-18 13:30:21 -07002105 default:
2106 SLOGE("keymaster_check_compatibility failed");
2107 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002108 }
2109
Kenny Rootc4c70f12013-06-14 12:11:38 -07002110 get_device_scrypt_params(ftr);
2111
Ken Sumrall160b4d62013-04-22 12:15:39 -07002112 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2113 if (get_crypt_ftr_info(NULL, &off) == 0) {
2114 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002115 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002116 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002117
2118 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002119}
2120
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002121#define FRAMEWORK_BOOT_WAIT 60
2122
Paul Crowley14c8c072018-09-18 13:30:21 -07002123static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2124 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002125 if (fd == -1) {
2126 SLOGE("Error opening file %s", filename);
2127 return -1;
2128 }
2129
2130 char block[CRYPT_INPLACE_BUFSIZE];
2131 memset(block, 0, sizeof(block));
2132 if (unix_read(fd, block, sizeof(block)) < 0) {
2133 SLOGE("Error reading file %s", filename);
2134 close(fd);
2135 return -1;
2136 }
2137
2138 close(fd);
2139
2140 SHA256_CTX c;
2141 SHA256_Init(&c);
2142 SHA256_Update(&c, block, sizeof(block));
2143 SHA256_Final(buf, &c);
2144
2145 return 0;
2146}
2147
Paul Crowley81796e92020-02-07 11:27:49 -08002148static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2149 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002150 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002151 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002152
Paul Lawrence87999172014-02-20 12:21:31 -08002153 /* The size of the userdata partition, and add in the vold volumes below */
2154 tot_encryption_size = crypt_ftr->fs_size;
2155
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002156 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002157 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002158
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002159 if (rc == ENABLE_INPLACE_ERR_DEV) {
2160 /* Hack for b/17898962 */
2161 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2162 cryptfs_reboot(RebootType::reboot);
2163 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002164
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002165 if (!rc) {
2166 crypt_ftr->encrypted_upto = cur_encryption_done;
2167 }
Paul Lawrence87999172014-02-20 12:21:31 -08002168
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002169 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2170 /* The inplace routine never actually sets the progress to 100% due
2171 * to the round down nature of integer division, so set it here */
2172 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002173 }
2174
2175 return rc;
2176}
2177
Paul Crowleyb64933a2017-10-31 08:25:55 -07002178static int vold_unmountAll(void) {
2179 VolumeManager* vm = VolumeManager::Instance();
2180 return vm->unmountAll();
2181}
2182
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002183int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002184 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002185 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002186 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002187 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002188 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002189 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002190 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002191 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002192 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002193 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002194 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002195 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002196 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002197 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002198
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002199 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002200 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2201 /* An encryption was underway and was interrupted */
2202 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2203 crypt_ftr.encrypted_upto = 0;
2204 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002205
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002206 /* At this point, we are in an inconsistent state. Until we successfully
2207 complete encryption, a reboot will leave us broken. So mark the
2208 encryption failed in case that happens.
2209 On successfully completing encryption, remove this flag */
2210 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002211
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002212 put_crypt_ftr_and_key(&crypt_ftr);
2213 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2214 if (!check_ftr_sha(&crypt_ftr)) {
2215 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2216 put_crypt_ftr_and_key(&crypt_ftr);
2217 goto error_unencrypted;
2218 }
2219
2220 /* Doing a reboot-encryption*/
2221 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2222 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2223 rebootEncryption = true;
2224 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002225 } else {
2226 // We don't want to accidentally reference invalid data.
2227 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002228 }
2229
2230 property_get("ro.crypto.state", encrypted_state, "");
2231 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2232 SLOGE("Device is already running encrypted, aborting");
2233 goto error_unencrypted;
2234 }
2235
Tom Cherry4c5bde22019-01-29 14:34:01 -08002236 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002237
Ken Sumrall3ed82362011-01-28 23:31:16 -08002238 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002239 uint64_t nr_sec;
2240 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002241 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002242 goto error_unencrypted;
2243 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002244
2245 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002246 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002247 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002248 fs_size_sec = get_fs_size(real_blkdev.c_str());
2249 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002250
Paul Lawrence87999172014-02-20 12:21:31 -08002251 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002252
2253 if (fs_size_sec > max_fs_size_sec) {
2254 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2255 goto error_unencrypted;
2256 }
2257 }
2258
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002259 /* Get a wakelock as this may take a while, and we don't want the
2260 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2261 * wants to keep the screen on, it can grab a full wakelock.
2262 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002263 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002264 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002265
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002266 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002267 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002268 */
2269 property_set("vold.decrypt", "trigger_shutdown_framework");
2270 SLOGD("Just asked init to shut down class main\n");
2271
Jeff Sharkey9c484982015-03-31 10:35:33 -07002272 /* Ask vold to unmount all devices that it manages */
2273 if (vold_unmountAll()) {
2274 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002275 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002276
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002277 /* no_ui means we are being called from init, not settings.
2278 Now we always reboot from settings, so !no_ui means reboot
2279 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002280 if (!no_ui) {
2281 /* Try fallback, which is to reboot and try there */
2282 onlyCreateHeader = true;
2283 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2284 if (breadcrumb == 0) {
2285 SLOGE("Failed to create breadcrumb file");
2286 goto error_shutting_down;
2287 }
2288 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002289 }
2290
2291 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002292 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002293 /* Now that /data is unmounted, we need to mount a tmpfs
2294 * /data, set a property saying we're doing inplace encryption,
2295 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002296 */
xzj7e38a3a2018-10-12 10:17:11 +08002297 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002298 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002299 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002300 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002301 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002302 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002303
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002304 /* restart the framework. */
2305 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002306 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002307
Ken Sumrall92736ef2012-10-17 20:57:14 -07002308 /* Ugh, shutting down the framework is not synchronous, so until it
2309 * can be fixed, this horrible hack will wait a moment for it all to
2310 * shut down before proceeding. Without it, some devices cannot
2311 * restart the graphics services.
2312 */
2313 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002314 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002315
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002316 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002317 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002318 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002319 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2320 goto error_shutting_down;
2321 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002322
Tom Cherry4c5bde22019-01-29 14:34:01 -08002323 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002324 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002325 } else {
2326 crypt_ftr.fs_size = nr_sec;
2327 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002328 /* At this point, we are in an inconsistent state. Until we successfully
2329 complete encryption, a reboot will leave us broken. So mark the
2330 encryption failed in case that happens.
2331 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002332 if (onlyCreateHeader) {
2333 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2334 } else {
2335 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2336 }
Paul Lawrence87999172014-02-20 12:21:31 -08002337 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002338 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2339 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002340
Paul Lawrence87999172014-02-20 12:21:31 -08002341 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002342 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2343 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002344 SLOGE("Cannot create encrypted master key\n");
2345 goto error_shutting_down;
2346 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002347
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002348 /* Replace scrypted intermediate key if we are preparing for a reboot */
2349 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002350 unsigned char fake_master_key[MAX_KEY_LEN];
2351 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002352 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002353 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2354 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002355 }
2356
Paul Lawrence87999172014-02-20 12:21:31 -08002357 /* Write the key to the end of the partition */
2358 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002359
Paul Lawrence87999172014-02-20 12:21:31 -08002360 /* If any persistent data has been remembered, save it.
2361 * If none, create a valid empty table and save that.
2362 */
2363 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002364 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2365 if (pdata) {
2366 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2367 persist_data = pdata;
2368 }
Paul Lawrence87999172014-02-20 12:21:31 -08002369 }
2370 if (persist_data) {
2371 save_persistent_data();
2372 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002373 }
2374
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002375 if (onlyCreateHeader) {
2376 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002377 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002378 }
2379
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002380 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002381 /* startup service classes main and late_start */
2382 property_set("vold.decrypt", "trigger_restart_min_framework");
2383 SLOGD("Just triggered restart_min_framework\n");
2384
2385 /* OK, the framework is restarted and will soon be showing a
2386 * progress bar. Time to setup an encrypted mapping, and
2387 * either write a new filesystem, or encrypt in place updating
2388 * the progress bar as we work.
2389 */
2390 }
2391
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002392 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002393 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002394 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002395
Paul Lawrence87999172014-02-20 12:21:31 -08002396 /* If we are continuing, check checksums match */
2397 rc = 0;
2398 if (previously_encrypted_upto) {
2399 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002400 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002401
Paul Crowley14c8c072018-09-18 13:30:21 -07002402 if (!rc &&
2403 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002404 SLOGE("Checksums do not match - trigger wipe");
2405 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002406 }
2407 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002408
Paul Lawrence87999172014-02-20 12:21:31 -08002409 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002410 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002411 previously_encrypted_upto);
2412 }
2413
2414 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002415 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002416 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002417 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002418 SLOGE("Error calculating checksum for continuing encryption");
2419 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002420 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002421 }
2422
2423 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002424 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002425
Paul Crowley14c8c072018-09-18 13:30:21 -07002426 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002427 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002428 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002429
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002430 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002431 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2432 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002433 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002434 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002435
Paul Lawrence6bfed202014-07-28 12:47:22 -07002436 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002437
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002438 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2439 char value[PROPERTY_VALUE_MAX];
2440 property_get("ro.crypto.state", value, "");
2441 if (!strcmp(value, "")) {
2442 /* default encryption - continue first boot sequence */
2443 property_set("ro.crypto.state", "encrypted");
2444 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002445 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002446 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2447 // Bring up cryptkeeper that will check the password and set it
2448 property_set("vold.decrypt", "trigger_shutdown_framework");
2449 sleep(2);
2450 property_set("vold.encrypt_progress", "");
2451 cryptfs_trigger_restart_min_framework();
2452 } else {
2453 cryptfs_check_passwd(DEFAULT_PASSWORD);
2454 cryptfs_restart_internal(1);
2455 }
2456 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002457 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002458 sleep(2); /* Give the UI a chance to show 100% progress */
2459 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002460 }
Paul Lawrence87999172014-02-20 12:21:31 -08002461 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002462 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002463 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002464 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002465 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002466 char value[PROPERTY_VALUE_MAX];
2467
Ken Sumrall319369a2012-06-27 16:30:18 -07002468 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002469 if (!strcmp(value, "1")) {
2470 /* wipe data if encryption failed */
2471 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002472 std::string err;
2473 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002474 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002475 if (!write_bootloader_message(options, &err)) {
2476 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002477 }
Josh Gaofec44372017-08-28 13:22:55 -07002478 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002479 } else {
2480 /* set property to trigger dialog */
2481 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002482 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002483 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002484 }
2485
Ken Sumrall3ed82362011-01-28 23:31:16 -08002486 /* hrm, the encrypt step claims success, but the reboot failed.
2487 * This should not happen.
2488 * Set the property and return. Hope the framework can deal with it.
2489 */
2490 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002491 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002492
2493error_unencrypted:
2494 property_set("vold.encrypt_progress", "error_not_encrypted");
2495 return -1;
2496
2497error_shutting_down:
2498 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2499 * but the framework is stopped and not restarted to show the error, so it's up to
2500 * vold to restart the system.
2501 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002502 SLOGE(
2503 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2504 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002505 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002506
2507 /* shouldn't get here */
2508 property_set("vold.encrypt_progress", "error_shutting_down");
2509 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002510}
2511
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002512int cryptfs_enable(int type, const char* passwd, int no_ui) {
2513 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002514}
2515
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002516int cryptfs_enable_default(int no_ui) {
2517 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002518}
2519
Paul Crowley14c8c072018-09-18 13:30:21 -07002520int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002521 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002522 SLOGE("cryptfs_changepw not valid for file encryption");
2523 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002524 }
2525
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002526 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002527 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002528
2529 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002530 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002531 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002532 return -1;
2533 }
2534
Paul Lawrencef4faa572014-01-29 13:31:03 -08002535 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2536 SLOGE("Invalid crypt_type %d", crypt_type);
2537 return -1;
2538 }
2539
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002540 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002541 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002542 SLOGE("Error getting crypt footer and key");
2543 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002544 }
2545
Paul Lawrencef4faa572014-01-29 13:31:03 -08002546 crypt_ftr.crypt_type = crypt_type;
2547
Paul Crowley14c8c072018-09-18 13:30:21 -07002548 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2549 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002550 if (rc) {
2551 SLOGE("Encrypt master key failed: %d", rc);
2552 return -1;
2553 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002554 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002555 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002556
2557 return 0;
2558}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002559
Rubin Xu85c01f92014-10-13 12:49:54 +01002560static unsigned int persist_get_max_entries(int encrypted) {
2561 struct crypt_mnt_ftr crypt_ftr;
2562 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002563
2564 /* If encrypted, use the values from the crypt_ftr, otherwise
2565 * use the values for the current spec.
2566 */
2567 if (encrypted) {
2568 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002569 /* Something is wrong, assume no space for entries */
2570 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002571 }
2572 dsize = crypt_ftr.persist_data_size;
2573 } else {
2574 dsize = CRYPT_PERSIST_DATA_SIZE;
2575 }
2576
Rubin Xuf83cc612018-10-09 16:13:38 +01002577 if (dsize > sizeof(struct crypt_persist_data)) {
2578 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2579 } else {
2580 return 0;
2581 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002582}
2583
Paul Crowley14c8c072018-09-18 13:30:21 -07002584static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002585 unsigned int i;
2586
2587 if (persist_data == NULL) {
2588 return -1;
2589 }
2590 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2591 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2592 /* We found it! */
2593 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2594 return 0;
2595 }
2596 }
2597
2598 return -1;
2599}
2600
Paul Crowley14c8c072018-09-18 13:30:21 -07002601static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002602 unsigned int i;
2603 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002604 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002605
2606 if (persist_data == NULL) {
2607 return -1;
2608 }
2609
Rubin Xu85c01f92014-10-13 12:49:54 +01002610 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002611
2612 num = persist_data->persist_valid_entries;
2613
2614 for (i = 0; i < num; i++) {
2615 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2616 /* We found an existing entry, update it! */
2617 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2618 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2619 return 0;
2620 }
2621 }
2622
2623 /* We didn't find it, add it to the end, if there is room */
2624 if (persist_data->persist_valid_entries < max_persistent_entries) {
2625 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2626 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2627 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2628 persist_data->persist_valid_entries++;
2629 return 0;
2630 }
2631
2632 return -1;
2633}
2634
Rubin Xu85c01f92014-10-13 12:49:54 +01002635/**
2636 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2637 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2638 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002639int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002640 std::string key_ = key;
2641 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002642
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002643 std::string parsed_field;
2644 unsigned parsed_index;
2645
2646 std::string::size_type split = key_.find_last_of('_');
2647 if (split == std::string::npos) {
2648 parsed_field = key_;
2649 parsed_index = 0;
2650 } else {
2651 parsed_field = key_.substr(0, split);
2652 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002653 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002654
2655 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002656}
2657
2658/*
2659 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2660 * remaining entries starting from index will be deleted.
2661 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2662 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2663 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2664 *
2665 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002666static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002667 unsigned int i;
2668 unsigned int j;
2669 unsigned int num;
2670
2671 if (persist_data == NULL) {
2672 return PERSIST_DEL_KEY_ERROR_OTHER;
2673 }
2674
2675 num = persist_data->persist_valid_entries;
2676
Paul Crowley14c8c072018-09-18 13:30:21 -07002677 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002678 // Filter out to-be-deleted entries in place.
2679 for (i = 0; i < num; i++) {
2680 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2681 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2682 j++;
2683 }
2684 }
2685
2686 if (j < num) {
2687 persist_data->persist_valid_entries = j;
2688 // Zeroise the remaining entries
2689 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2690 return PERSIST_DEL_KEY_OK;
2691 } else {
2692 // Did not find an entry matching the given fieldname
2693 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2694 }
2695}
2696
Paul Crowley14c8c072018-09-18 13:30:21 -07002697static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002698 unsigned int i;
2699 unsigned int count;
2700
2701 if (persist_data == NULL) {
2702 return -1;
2703 }
2704
2705 count = 0;
2706 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2707 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2708 count++;
2709 }
2710 }
2711
2712 return count;
2713}
2714
Ken Sumrall160b4d62013-04-22 12:15:39 -07002715/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002716int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002717 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002718 SLOGE("Cannot get field when file encrypted");
2719 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002720 }
2721
Ken Sumrall160b4d62013-04-22 12:15:39 -07002722 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002723 /* CRYPTO_GETFIELD_OK is success,
2724 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2725 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2726 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002727 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002728 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2729 int i;
2730 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002731
2732 if (persist_data == NULL) {
2733 load_persistent_data();
2734 if (persist_data == NULL) {
2735 SLOGE("Getfield error, cannot load persistent data");
2736 goto out;
2737 }
2738 }
2739
Rubin Xu85c01f92014-10-13 12:49:54 +01002740 // Read value from persistent entries. If the original value is split into multiple entries,
2741 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002742 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002743 // 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 -07002744 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002745 // value too small
2746 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2747 goto out;
2748 }
2749 rc = CRYPTO_GETFIELD_OK;
2750
2751 for (i = 1; /* break explicitly */; i++) {
2752 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002753 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002754 // If the fieldname is very long, we stop as soon as it begins to overflow the
2755 // maximum field length. At this point we have in fact fully read out the original
2756 // value because cryptfs_setfield would not allow fields with longer names to be
2757 // written in the first place.
2758 break;
2759 }
2760 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002761 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2762 // value too small.
2763 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2764 goto out;
2765 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002766 } else {
2767 // Exhaust all entries.
2768 break;
2769 }
2770 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002771 } else {
2772 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002773 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002774 }
2775
2776out:
2777 return rc;
2778}
2779
2780/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002781int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002782 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002783 SLOGE("Cannot set field when file encrypted");
2784 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002785 }
2786
Ken Sumrall160b4d62013-04-22 12:15:39 -07002787 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002788 /* 0 is success, negative values are error */
2789 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002790 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002791 unsigned int field_id;
2792 char temp_field[PROPERTY_KEY_MAX];
2793 unsigned int num_entries;
2794 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002795
2796 if (persist_data == NULL) {
2797 load_persistent_data();
2798 if (persist_data == NULL) {
2799 SLOGE("Setfield error, cannot load persistent data");
2800 goto out;
2801 }
2802 }
2803
2804 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002805 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002806 encrypted = 1;
2807 }
2808
Rubin Xu85c01f92014-10-13 12:49:54 +01002809 // Compute the number of entries required to store value, each entry can store up to
2810 // (PROPERTY_VALUE_MAX - 1) chars
2811 if (strlen(value) == 0) {
2812 // Empty value also needs one entry to store.
2813 num_entries = 1;
2814 } else {
2815 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2816 }
2817
2818 max_keylen = strlen(fieldname);
2819 if (num_entries > 1) {
2820 // Need an extra "_%d" suffix.
2821 max_keylen += 1 + log10(num_entries);
2822 }
2823 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2824 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002825 goto out;
2826 }
2827
Rubin Xu85c01f92014-10-13 12:49:54 +01002828 // Make sure we have enough space to write the new value
2829 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2830 persist_get_max_entries(encrypted)) {
2831 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2832 goto out;
2833 }
2834
2835 // Now that we know persist_data has enough space for value, let's delete the old field first
2836 // to make up space.
2837 persist_del_keys(fieldname, 0);
2838
2839 if (persist_set_key(fieldname, value, encrypted)) {
2840 // fail to set key, should not happen as we have already checked the available space
2841 SLOGE("persist_set_key() error during setfield()");
2842 goto out;
2843 }
2844
2845 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002846 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002847
2848 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2849 // fail to set key, should not happen as we have already checked the available space.
2850 SLOGE("persist_set_key() error during setfield()");
2851 goto out;
2852 }
2853 }
2854
Ken Sumrall160b4d62013-04-22 12:15:39 -07002855 /* If we are running encrypted, save the persistent data now */
2856 if (encrypted) {
2857 if (save_persistent_data()) {
2858 SLOGE("Setfield error, cannot save persistent data");
2859 goto out;
2860 }
2861 }
2862
Rubin Xu85c01f92014-10-13 12:49:54 +01002863 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002864
2865out:
2866 return rc;
2867}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002868
2869/* Checks userdata. Attempt to mount the volume if default-
2870 * encrypted.
2871 * On success trigger next init phase and return 0.
2872 * Currently do not handle failure - see TODO below.
2873 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002874int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002875 int crypt_type = cryptfs_get_password_type();
2876 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2877 SLOGE("Bad crypt type - error");
2878 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002879 SLOGD(
2880 "Password is not default - "
2881 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002882 property_set("vold.decrypt", "trigger_restart_min_framework");
2883 return 0;
2884 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2885 SLOGD("Password is default - restarting filesystem");
2886 cryptfs_restart_internal(0);
2887 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002888 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002889 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002890 }
2891
Paul Lawrence6bfed202014-07-28 12:47:22 -07002892 /** Corrupt. Allow us to boot into framework, which will detect bad
2893 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002894 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002895 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002896 return 0;
2897}
2898
2899/* Returns type of the password, default, pattern, pin or password.
2900 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002901int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002902 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002903 SLOGE("cryptfs_get_password_type not valid for file encryption");
2904 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002905 }
2906
Paul Lawrencef4faa572014-01-29 13:31:03 -08002907 struct crypt_mnt_ftr crypt_ftr;
2908
2909 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2910 SLOGE("Error getting crypt footer and key\n");
2911 return -1;
2912 }
2913
Paul Lawrence6bfed202014-07-28 12:47:22 -07002914 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2915 return -1;
2916 }
2917
Paul Lawrencef4faa572014-01-29 13:31:03 -08002918 return crypt_ftr.crypt_type;
2919}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002920
Paul Crowley14c8c072018-09-18 13:30:21 -07002921const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002922 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002923 SLOGE("cryptfs_get_password not valid for file encryption");
2924 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002925 }
2926
Paul Lawrence399317e2014-03-10 13:20:50 -07002927 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002928 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002929 if (now.tv_sec < password_expiry_time) {
2930 return password;
2931 } else {
2932 cryptfs_clear_password();
2933 return 0;
2934 }
2935}
2936
Paul Crowley14c8c072018-09-18 13:30:21 -07002937void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002938 if (password) {
2939 size_t len = strlen(password);
2940 memset(password, 0, len);
2941 free(password);
2942 password = 0;
2943 password_expiry_time = 0;
2944 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002945}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002946
Paul Crowley14c8c072018-09-18 13:30:21 -07002947int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002948 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2949 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002950}